{"cells":[{"cell_type":"markdown","id":"0d974b88-7ed7-4c03-9d37-db92ba074a9b","metadata":{},"outputs":[],"source":["<p style=\"text-align:center\">\n","    <a href=\"https://skills.network/?utm_medium=Exinfluencer&utm_source=Exinfluencer&utm_content=000026UJ&utm_term=10006555&utm_id=NA-SkillsNetwork-Channel-SkillsNetworkCoursesIBMDeveloperSkillsNetworkPY0220ENSkillsNetwork900-2022-01-01\" target=\"_blank\">\n","    <img src=\"https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/assets/logos/SN_web_lightmode.png\" width=\"200\" alt=\"Skills Network Logo\">\n","    </a>\n","</p>\n"]},{"cell_type":"markdown","id":"ab75481d-8eed-479b-99f1-1aa7b973e78b","metadata":{},"outputs":[],"source":["<h1>Extracting and Visualizing Stock Data</h1>\n","<h2>Description</h2>\n"]},{"cell_type":"markdown","id":"e822e056-6316-4966-bff0-1812bcdf027c","metadata":{},"outputs":[],"source":["Extracting essential data from a dataset and displaying it is a necessary part of data science; therefore individuals can make correct decisions based on the data. In this assignment, you will extract some stock data, you will then display this data in a graph.\n"]},{"cell_type":"markdown","id":"5f3423c5-2624-4b15-9487-abaa266f9657","metadata":{},"outputs":[],"source":["<h2>Table of Contents</h2>\n","<div class=\"alert alert-block alert-info\" style=\"margin-top: 20px\">\n","    <ul>\n","        <li>Define a Function that Makes a Graph</li>\n","        <li>Question 1: Use yfinance to Extract Stock Data</li>\n","        <li>Question 2: Use Webscraping to Extract Tesla Revenue Data</li>\n","        <li>Question 3: Use yfinance to Extract Stock Data</li>\n","        <li>Question 4: Use Webscraping to Extract GME Revenue Data</li>\n","        <li>Question 5: Plot Tesla Stock Graph</li>\n","        <li>Question 6: Plot GameStop Stock Graph</li>\n","    </ul>\n","<p>\n","    Estimated Time Needed: <strong>30 min</strong></p>\n","</div>\n","\n","<hr>\n"]},{"cell_type":"markdown","id":"27f12765-e277-4d1e-a443-16ed143410b9","metadata":{},"outputs":[],"source":["***Note***:- If you are working Locally using anaconda, please uncomment the following code and execute it.\n"]},{"cell_type":"code","id":"d469f510-a296-4049-b9a8-bd6f4c1b8898","metadata":{},"outputs":[],"source":["#!pip install yfinance==0.2.38\n#!pip install pandas==2.2.2\n#!pip install nbformat"]},{"cell_type":"code","id":"dfc689f5-a599-4f9c-a284-5bbe3232b218","metadata":{},"outputs":[],"source":["!pip install yfinance\n!pip install bs4\n!pip install nbformat\n!pip install --upgrade plotly"]},{"cell_type":"code","id":"91694435-3882-4853-9176-7b527bd7d699","metadata":{},"outputs":[],"source":["import yfinance as yf\nimport pandas as pd\nimport requests\nfrom bs4 import BeautifulSoup\nimport plotly.graph_objects as go\nfrom plotly.subplots import make_subplots"]},{"cell_type":"code","id":"eb18d6bb-edbb-45ae-86f0-998ee3ed09a3","metadata":{},"outputs":[],"source":["import plotly.io as pio\npio.renderers.default = \"iframe\""]},{"cell_type":"markdown","id":"6f6fcb0b-e22f-4a59-991c-2dbfc857abcc","metadata":{},"outputs":[],"source":["In Python, you can ignore warnings using the warnings module. You can use the filterwarnings function to filter or ignore specific warning messages or categories.\n"]},{"cell_type":"code","id":"bf6cd16f-b632-439d-a9c9-2b8cfbf59219","metadata":{},"outputs":[],"source":["import warnings\n# Ignore all warnings\nwarnings.filterwarnings(\"ignore\", category=FutureWarning)"]},{"cell_type":"markdown","id":"162d3bb7-ddc0-462e-9708-e0b05b5c1b39","metadata":{},"outputs":[],"source":["## Define Graphing Function\n"]},{"cell_type":"markdown","id":"6a01e854-6c54-42bb-b720-27a837fb3cbb","metadata":{},"outputs":[],"source":["In this section, we define the function `make_graph`. **You don't have to know how the function works, you should only care about the inputs. It takes a dataframe with stock data (dataframe must contain Date and Close columns), a dataframe with revenue data (dataframe must contain Date and Revenue columns), and the name of the stock.**\n"]},{"cell_type":"code","id":"ef3ae4f8-42a2-4a6b-98f0-7109d77df07d","metadata":{},"outputs":[],"source":["def make_graph(stock_data, revenue_data, stock):\n    fig = make_subplots(rows=2, cols=1, shared_xaxes=True, subplot_titles=(\"Historical Share Price\", \"Historical Revenue\"), vertical_spacing = .3)\n    stock_data_specific = stock_data[stock_data.Date <= '2021--06-14']\n    revenue_data_specific = revenue_data[revenue_data.Date <= '2021-04-30']\n    fig.add_trace(go.Scatter(x=pd.to_datetime(stock_data_specific.Date), y=stock_data_specific.Close.astype(\"float\"), name=\"Share Price\"), row=1, col=1)\n    fig.add_trace(go.Scatter(x=pd.to_datetime(revenue_data_specific.Date), y=revenue_data_specific.Revenue.astype(\"float\"), name=\"Revenue\"), row=2, col=1)\n    fig.update_xaxes(title_text=\"Date\", row=1, col=1)\n    fig.update_xaxes(title_text=\"Date\", row=2, col=1)\n    fig.update_yaxes(title_text=\"Price ($US)\", row=1, col=1)\n    fig.update_yaxes(title_text=\"Revenue ($US Millions)\", row=2, col=1)\n    fig.update_layout(showlegend=False,\n    height=900,\n    title=stock,\n    xaxis_rangeslider_visible=True)\n    fig.show()\n    from IPython.display import display, HTML\n    fig_html = fig.to_html()\n    display(HTML(fig_html))"]},{"cell_type":"markdown","id":"529490b2-6457-4618-a1bc-d2c6ea214dfb","metadata":{},"outputs":[],"source":["Use the make_graph function that we’ve already defined. You’ll need to invoke it in questions 5 and 6 to display the graphs and create the dashboard. \n","> **Note: You don’t need to redefine the function for plotting graphs anywhere else in this notebook; just use the existing function.**\n"]},{"cell_type":"markdown","id":"201ffb65-55ba-411d-be3a-db2057996247","metadata":{},"outputs":[],"source":["## Question 1: Use yfinance to Extract Stock Data\n"]},{"cell_type":"markdown","id":"a5c8fee1-6c02-475d-9c85-abb14d8573fe","metadata":{},"outputs":[],"source":["Using the `Ticker` function enter the ticker symbol of the stock we want to extract data on to create a ticker object. The stock is Tesla and its ticker symbol is `TSLA`.\n"]},{"cell_type":"code","id":"5d72198d-ce2d-4b78-a915-64189c56fda8","metadata":{},"outputs":[],"source":[""]},{"cell_type":"markdown","id":"5ac92393-35d1-41c0-845a-36aec369cadc","metadata":{},"outputs":[],"source":["Using the ticker object and the function `history` extract stock information and save it in a dataframe named `tesla_data`. Set the `period` parameter to ` \"max\" ` so we get information for the maximum amount of time.\n"]},{"cell_type":"code","id":"1805fe6d-c940-4412-80ce-2c69a203c50d","metadata":{},"outputs":[],"source":[""]},{"cell_type":"markdown","id":"87730931-fa38-49a2-b098-f9f69c21f9a4","metadata":{},"outputs":[],"source":["**Reset the index** using the `reset_index(inplace=True)` function on the tesla_data DataFrame and display the first five rows of the `tesla_data` dataframe using the `head` function. Take a screenshot of the results and code from the beginning of Question 1 to the results below.\n"]},{"cell_type":"code","id":"a180cff4-b4ae-4b99-8351-110c1acfbb4d","metadata":{},"outputs":[],"source":[""]},{"cell_type":"markdown","id":"94ced709-9a99-4de2-b800-3f60a95c6910","metadata":{},"outputs":[],"source":["## Question 2: Use Webscraping to Extract Tesla Revenue Data\n"]},{"cell_type":"markdown","id":"862f17c8-3122-45ab-b01c-feb3e436dd5f","metadata":{},"outputs":[],"source":["Use the `requests` library to download the webpage https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-PY0220EN-SkillsNetwork/labs/project/revenue.htm Save the text of the response as a variable named `html_data`.\n"]},{"cell_type":"code","id":"d785c9a8-9684-49c6-91a4-74488e3a8138","metadata":{},"outputs":[],"source":[""]},{"cell_type":"markdown","id":"f2f1d4f3-bcda-4070-9321-0daf92a55477","metadata":{},"outputs":[],"source":["Parse the html data using `beautiful_soup` using parser i.e `html5lib` or `html.parser`. Make sure to use the `html_data` with the content parameter as follow `html_data.content` .\n"]},{"cell_type":"code","id":"59cd4add-1a30-4c22-9376-d0c4fa840ae0","metadata":{},"outputs":[],"source":[""]},{"cell_type":"markdown","id":"0ec3933d-9ab6-4292-97a2-a183fd1f9dbd","metadata":{},"outputs":[],"source":["Using `BeautifulSoup` or the `read_html` function extract the table with `Tesla Quarterly Revenue` and store it into a dataframe named `tesla_revenue`. The dataframe should have columns `Date` and `Revenue`.\n"]},{"cell_type":"markdown","id":"3da37c3c-c91f-46b4-99bd-8e52102530cc","metadata":{},"outputs":[],"source":["<details><summary>Step-by-step instructions</summary>\n","\n","```\n","\n","Here are the step-by-step instructions:\n","\n","1. Find All Tables: Start by searching for all HTML tables on a webpage using `soup.find_all('table')`.\n","2. Identify the Relevant Table: then loops through each table. If a table contains the text “Tesla Quarterly Revenue,”, select that table.\n","3. Initialize a DataFrame: Create an empty Pandas DataFrame called `tesla_revenue` with columns “Date” and “Revenue.”\n","4. Loop Through Rows: For each row in the relevant table, extract the data from the first and second columns (date and revenue).\n","5. Clean Revenue Data: Remove dollar signs and commas from the revenue value.\n","6. Add Rows to DataFrame: Create a new row in the DataFrame with the extracted date and cleaned revenue values.\n","7. Repeat for All Rows: Continue this process for all rows in the table.\n","\n","```\n","</details>\n"]},{"cell_type":"markdown","id":"8d0f3cb3-d5fc-41cd-85c1-696743acab87","metadata":{},"outputs":[],"source":["<details><summary>Click here if you need help locating the table</summary>\n","\n","```\n","    \n","Below is the code to isolate the table, you will now need to loop through the rows and columns like in the previous lab\n","    \n","soup.find_all(\"tbody\")[1]\n","    \n","If you want to use the read_html function the table is located at index 1\n","\n","We are focusing on quarterly revenue in the lab.\n","> Note: Instead of using the deprecated pd.append() method, consider using pd.concat([df, pd.DataFrame], ignore_index=True).\n","```\n","\n","</details>\n"]},{"cell_type":"code","id":"6b78db04-0a30-4a58-bc32-757bf2a491e9","metadata":{},"outputs":[],"source":[""]},{"cell_type":"markdown","id":"2714ffb4-e06e-451d-b321-7db66ce70412","metadata":{},"outputs":[],"source":["Execute the following line to remove the comma and dollar sign from the `Revenue` column. \n"]},{"cell_type":"code","id":"fe83b511-9cdd-4424-83a3-4ab2223b33ff","metadata":{},"outputs":[],"source":["tesla_revenue[\"Revenue\"] = tesla_revenue['Revenue'].str.replace(',|\\$',\"\", regex=True)"]},{"cell_type":"markdown","id":"77f049b6-21a1-4bbe-a06f-e5af87a3e5e5","metadata":{},"outputs":[],"source":["Execute the following lines to remove an null or empty strings in the Revenue column.\n"]},{"cell_type":"code","id":"4cee4045-949a-41d6-a9d1-2fd271101fe6","metadata":{},"outputs":[],"source":["tesla_revenue.dropna(inplace=True)\n\ntesla_revenue = tesla_revenue[tesla_revenue['Revenue'] != \"\"]"]},{"cell_type":"markdown","id":"4bf934d7-be5a-4f56-9863-f5aa44c3598c","metadata":{},"outputs":[],"source":["Display the last 5 row of the `tesla_revenue` dataframe using the `tail` function. Take a screenshot of the results.\n"]},{"cell_type":"code","id":"58ede691-6bc3-4aba-8837-215346fc295e","metadata":{},"outputs":[],"source":[""]},{"cell_type":"markdown","id":"9803aa86-a73f-46fc-9ec9-7657865726a1","metadata":{},"outputs":[],"source":["## Question 3: Use yfinance to Extract Stock Data\n"]},{"cell_type":"markdown","id":"01ca6974-4e23-42bd-a5e3-7dc8b0abd353","metadata":{},"outputs":[],"source":["Using the `Ticker` function enter the ticker symbol of the stock we want to extract data on to create a ticker object. The stock is GameStop and its ticker symbol is `GME`.\n"]},{"cell_type":"code","id":"53f5dd12-0243-48a8-9f6f-99d5567a5552","metadata":{},"outputs":[],"source":[""]},{"cell_type":"markdown","id":"5df37e9c-a254-4252-a870-92e08fb1c170","metadata":{},"outputs":[],"source":["Using the ticker object and the function `history` extract stock information and save it in a dataframe named `gme_data`. Set the `period` parameter to ` \"max\" ` so we get information for the maximum amount of time.\n"]},{"cell_type":"code","id":"08890085-7460-40b8-88f7-7528a691fd13","metadata":{},"outputs":[],"source":[""]},{"cell_type":"markdown","id":"34da5e2a-3100-408c-b431-7921ec26ab66","metadata":{},"outputs":[],"source":["**Reset the index** using the `reset_index(inplace=True)` function on the gme_data DataFrame and display the first five rows of the `gme_data` dataframe using the `head` function. Take a screenshot of the results and code from the beginning of Question 3 to the results below.\n"]},{"cell_type":"code","id":"9b9834d3-2e44-4618-8ba4-740704d3f768","metadata":{},"outputs":[],"source":[""]},{"cell_type":"markdown","id":"038d3bcb-8310-4449-8bcd-53eab257ec1a","metadata":{},"outputs":[],"source":["## Question 4: Use Webscraping to Extract GME Revenue Data\n"]},{"cell_type":"markdown","id":"1ecc6b7e-5f27-478b-96f2-e4cd60b59178","metadata":{},"outputs":[],"source":["Use the `requests` library to download the webpage https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-PY0220EN-SkillsNetwork/labs/project/stock.html. Save the text of the response as a variable named `html_data_2`.\n"]},{"cell_type":"code","id":"3a9fd46c-183e-411c-9036-0f89621a0156","metadata":{},"outputs":[],"source":[""]},{"cell_type":"markdown","id":"5a4bd03d-de59-4ee3-9edb-da689c88a1e5","metadata":{},"outputs":[],"source":["Parse the html data using `beautiful_soup` using parser i.e `html5lib` or `html.parser`.\n"]},{"cell_type":"code","id":"11474507-b4e2-447e-9ce8-18f73c110401","metadata":{},"outputs":[],"source":[""]},{"cell_type":"markdown","id":"1f37d348-d284-4a90-9097-99e3bb1324b2","metadata":{},"outputs":[],"source":["Using `BeautifulSoup` or the `read_html` function extract the table with `GameStop Quarterly Revenue` and store it into a dataframe named `gme_revenue`. The dataframe should have columns `Date` and `Revenue`. Make sure the comma and dollar sign is removed from the `Revenue` column.\n"]},{"cell_type":"markdown","id":"3d541b9e-cb9f-4076-b6db-bd10a2642963","metadata":{},"outputs":[],"source":["> **Note: Use the method similar to what you did in question 2.**  \n"]},{"cell_type":"markdown","id":"a1f94661-728f-4012-94a7-86c4de2b5eb1","metadata":{},"outputs":[],"source":["<details><summary>Click here if you need help locating the table</summary>\n","\n","```\n","    \n","Below is the code to isolate the table, you will now need to loop through the rows and columns like in the previous lab\n","    \n","soup.find_all(\"tbody\")[1]\n","    \n","If you want to use the read_html function the table is located at index 1\n","\n","\n","```\n","\n","</details>\n"]},{"cell_type":"code","id":"3e73bdf4-475c-4fae-8f14-3abf71638550","metadata":{},"outputs":[],"source":[""]},{"cell_type":"markdown","id":"eecaa113-ce7a-4b8c-9da5-f57f8763bf59","metadata":{},"outputs":[],"source":["Display the last five rows of the `gme_revenue` dataframe using the `tail` function. Take a screenshot of the results.\n"]},{"cell_type":"code","id":"ce75ccd6-71b7-4d21-b43a-2048c98caa85","metadata":{},"outputs":[],"source":[""]},{"cell_type":"markdown","id":"f8aed3ff-7b0e-47f7-b223-b1df5b044fff","metadata":{},"outputs":[],"source":["## Question 5: Plot Tesla Stock Graph\n"]},{"cell_type":"markdown","id":"ff9a5634-23bb-4d99-87d6-6ce69bf1e4fa","metadata":{},"outputs":[],"source":["Use the `make_graph` function to graph the Tesla Stock Data, also provide a title for the graph. Note the graph will only show data upto June 2021.\n"]},{"cell_type":"markdown","id":"b1c5a49e-bf4c-4702-a5e0-def4e4dc95d3","metadata":{},"outputs":[],"source":["<details><summary>Hint</summary>\n","\n","```\n","\n","You just need to invoke the make_graph function with the required parameter to print the graphs.The structure to call the `make_graph` function is `make_graph(tesla_data, tesla_revenue, 'Tesla')`.\n","\n","```\n","    \n","</details>\n"]},{"cell_type":"code","id":"6bc22c15-1c01-4433-917e-e385a2760721","metadata":{},"outputs":[],"source":[""]},{"cell_type":"markdown","id":"b55f5fc8-a8dd-486f-bc27-36584e987493","metadata":{},"outputs":[],"source":["## Question 6: Plot GameStop Stock Graph\n"]},{"cell_type":"markdown","id":"30870cb1-26a2-4a0f-ad02-f7873faaaabb","metadata":{},"outputs":[],"source":["Use the `make_graph` function to graph the GameStop Stock Data, also provide a title for the graph. The structure to call the `make_graph` function is `make_graph(gme_data, gme_revenue, 'GameStop')`. Note the graph will only show data upto June 2021.\n"]},{"cell_type":"markdown","id":"51d7dcfc-be9d-40cc-a0f0-10774b0e7184","metadata":{},"outputs":[],"source":["<details><summary>Hint</summary>\n","\n","```\n","\n","You just need to invoke the make_graph function with the required parameter to print the graphs.The structure to call the `make_graph` function is `make_graph(gme_data, gme_revenue, 'GameStop')`\n","\n","```\n","    \n","</details>\n"]},{"cell_type":"code","id":"c5378a51-9d1b-4a6d-8a9c-cd517f8e3dc2","metadata":{},"outputs":[],"source":[""]},{"cell_type":"markdown","id":"1ab18b69-96e3-4923-a6d4-2946f81a4633","metadata":{},"outputs":[],"source":["<h2>About the Authors:</h2> \n","\n","<a href=\"https://www.linkedin.com/in/joseph-s-50398b136/\">Joseph Santarcangelo</a> has a PhD in Electrical Engineering, his research focused on using machine learning, signal processing, and computer vision to determine how videos impact human cognition. Joseph has been working for IBM since he completed his PhD.\n"]},{"cell_type":"markdown","id":"218fae3c-ffea-4c9f-898d-46a60ab3a7e0","metadata":{},"outputs":[],"source":["## <h3 align=\"center\"> © IBM Corporation 2020. All rights reserved. <h3/>\n","\n","```toggle ## Change Log\n","```\n","```toggle | Date (YYYY-MM-DD) | Version | Changed By    | Change Description        |\n","```\n","```toggle | ----------------- | ------- | ------------- | ------------------------- |\n","```\n","```toggle | 2022-02-28        | 1.2     | Lakshmi Holla | Changed the URL of GameStop |\n","```\n","```toggle | 2020-11-10        | 1.1     | Malika Singla | Deleted the Optional part |\n","```\n","```toggle | 2020-08-27        | 1.0     | Malika Singla | Added lab to GitLab       |\n","```\n"]}],"metadata":{"kernelspec":{"display_name":"Python 3 (ipykernel)","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.12.8","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"prev_pub_hash":"59e64f892e2342725ffba464f746953f585208e1754e3f92f7a93792425a43ce"},"nbformat":4,"nbformat_minor":4}