-
Notifications
You must be signed in to change notification settings - Fork 0
/
Final Assignment.py
352 lines (220 loc) · 11 KB
/
Final Assignment.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
#!/usr/bin/env python
# coding: utf-8
# <p style="text-align:center">
# <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">
# <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">
# </a>
# </p>
#
# <h1>Extracting and Visualizing Stock Data</h1>
# <h2>Description</h2>
#
# 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.
#
# <h2>Table of Contents</h2>
# <div class="alert alert-block alert-info" style="margin-top: 20px">
# <ul>
# <li>Define a Function that Makes a Graph</li>
# <li>Question 1: Use yfinance to Extract Stock Data</li>
# <li>Question 2: Use Webscraping to Extract Tesla Revenue Data</li>
# <li>Question 3: Use yfinance to Extract Stock Data</li>
# <li>Question 4: Use Webscraping to Extract GME Revenue Data</li>
# <li>Question 5: Plot Tesla Stock Graph</li>
# <li>Question 6: Plot GameStop Stock Graph</li>
# </ul>
# <p>
# Estimated Time Needed: <strong>30 min</strong></p>
# </div>
#
# <hr>
#
# ***Note***:- If you are working in IBM Cloud Watson Studio, please replace the command for installing nbformat from `!pip install nbformat==4.2.0` to simply `!pip install nbformat`
#
# In[1]:
#!pip install yfinance==0.1.67
#!mamba install bs4==4.10.0 -y
get_ipython().system('pip install nbformat')
#==4.2.0
# In[98]:
import yfinance as yf
import pandas as pd
import requests
from bs4 import BeautifulSoup
import plotly.graph_objects as go
from plotly.subplots import make_subplots
# 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.
#
# In[99]:
import warnings
# Ignore all warnings
warnings.filterwarnings("ignore", category=FutureWarning)
# ## Define Graphing Function
#
# 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.
#
# In[100]:
def make_graph(stock_data, revenue_data, stock):
fig = make_subplots(rows=2, cols=1, shared_xaxes=True, subplot_titles=("Historical Share Price", "Historical Revenue"), vertical_spacing = .3)
stock_data_specific = stock_data[stock_data.Date <= '2021--06-14']
revenue_data_specific = revenue_data[revenue_data.Date <= '2021-04-30']
fig.add_trace(go.Scatter(x=pd.to_datetime(stock_data_specific.Date, infer_datetime_format=True), y=stock_data_specific.Close.astype("float"), name="Share Price"), row=1, col=1)
fig.add_trace(go.Scatter(x=pd.to_datetime(revenue_data_specific.Date, infer_datetime_format=True), y=revenue_data_specific.Revenue.astype("float"), name="Revenue"), row=2, col=1)
fig.update_xaxes(title_text="Date", row=1, col=1)
fig.update_xaxes(title_text="Date", row=2, col=1)
fig.update_yaxes(title_text="Price ($US)", row=1, col=1)
fig.update_yaxes(title_text="Revenue ($US Millions)", row=2, col=1)
fig.update_layout(showlegend=False,
height=900,
title=stock,
xaxis_rangeslider_visible=True)
fig.show()
# ## Question 1: Use yfinance to Extract Stock Data
#
# 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`.
#
# In[101]:
tesla = yf.Ticker("TSLA")
# 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.
#
# In[102]:
tesla_data = tesla.history(period="max")
# **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.
#
# In[89]:
tesla_data.reset_index(inplace=True)
tesla_data.head(5)
# ## Question 2: Use Webscraping to Extract Tesla Revenue Data
#
# 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`.
#
# In[90]:
url = "https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-PY0220EN-SkillsNetwork/labs/project/revenue.htm"
html_data = requests.get(url).text
# Parse the html data using `beautiful_soup`.
#
# In[91]:
soup = BeautifulSoup(html_data, 'html5lib')
# Using `BeautifulSoup` or the `read_html` function extract the table with `Tesla Revenue` and store it into a dataframe named `tesla_revenue`. The dataframe should have columns `Date` and `Revenue`.
#
# <details><summary>Click here if you need help locating the table</summary>
#
# ```
#
# Below is the code to isolate the table, you will now need to loop through the rows and columns like in the previous lab
#
# soup.find_all("tbody")[1]
#
# If you want to use the read_html function the table is located at index 1
#
# We are focusing on quarterly revenue in the lab.
# ```
#
# </details>
#
# In[93]:
tesla_revenue = pd.read_html(str(soup)
tesla_revenue = tesla_revenue[1]
tesla_revenue = tesla_revenue.rename(columns= {"Tesla Quarterly Revenue (Millions of US $)": "Date",
"Tesla Quarterly Revenue (Millions of US $).1":"Revenue"})
# Execute the following line to remove the comma and dollar sign from the `Revenue` column.
#
# In[94]:
tesla_revenue["Revenue"] = tesla_revenue['Revenue'].str.replace(',|\$',"")
# Execute the following lines to remove an null or empty strings in the Revenue column.
#
# In[95]:
tesla_revenue.dropna(inplace=True)
tesla_revenue = tesla_revenue[tesla_revenue['Revenue'] != ""]
# Display the last 5 row of the `tesla_revenue` dataframe using the `tail` function. Take a screenshot of the results.
#
# In[96]:
tesla_revenue.tail(5)
# ## Question 3: Use yfinance to Extract Stock Data
#
# 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`.
#
# In[55]:
gamestop = yf.Ticker("GME")
# 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.
#
# In[56]:
gme_data = gamestop.history(period ="max")
# **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.
#
# In[57]:
gme_data.reset_index(inplace=True)
gme_data.head(5)
# ## Question 4: Use Webscraping to Extract GME Revenue Data
#
# 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`.
#
# In[80]:
url = "https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-PY0220EN-SkillsNetwork/labs/project/stock.html"
html_data = requests.get(url).text
# Parse the html data using `beautiful_soup`.
#
# In[81]:
soup = BeautifulSoup(html_data, "html5lib")
# Using `BeautifulSoup` or the `read_html` function extract the table with `GameStop 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 using a method similar to what you did in Question 2.
#
# <details><summary>Click here if you need help locating the table</summary>
#
# ```
#
# Below is the code to isolate the table, you will now need to loop through the rows and columns like in the previous lab
#
# soup.find_all("tbody")[1]
#
# If you want to use the read_html function the table is located at index 1
#
#
# ```
#
# </details>
#
# In[82]:
gme_revenue = pd.read_html(str(soup))
gme_revenue = gme_revenue[1]
gme_revenue = gme_revenue.rename(columns={"GameStop Quarterly Revenue (Millions of US $)":"Date",
"GameStop Quarterly Revenue (Millions of US $).1":"Revenue"})
gme_revenue['Revenue'] = gme_revenue['Revenue'].str.replace(",|\$", "") #Remove symbols
# Remove an null or empty strings in the Revenue column.
# In[83]:
gme_revenue.dropna(inplace=True)
gme_revenue = gme_revenue[gme_revenue['Revenue'] != ""]
# Display the last five rows of the `gme_revenue` dataframe using the `tail` function. Take a screenshot of the results.
#
# In[84]:
gme_revenue.tail(5)
# ## Question 5: Plot Tesla Stock Graph
#
# Use the `make_graph` function to graph the Tesla Stock Data, also provide a title for the graph. The structure to call the `make_graph` function is `make_graph(tesla_data, tesla_revenue, 'Tesla')`. Note the graph will only show data upto June 2021.
#
# In[97]:
make_graph(tesla_data, tesla_revenue, 'Tesla')
# ## Question 6: Plot GameStop Stock Graph
#
# 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.
#
# In[103]:
make_graph(gme_data, gme_revenue, 'GameStop')
# <h2>About the Authors:</h2>
#
# <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.
#
# Azim Hirjani
#
# ## Change Log
#
# | Date (YYYY-MM-DD) | Version | Changed By | Change Description |
# | ----------------- | ------- | ------------- | ------------------------- |
# | 2022-02-28 | 1.2 | Lakshmi Holla | Changed the URL of GameStop |
# | 2020-11-10 | 1.1 | Malika Singla | Deleted the Optional part |
# | 2020-08-27 | 1.0 | Malika Singla | Added lab to GitLab |
#
# <hr>
#
# ## <h3 align="center"> © IBM Corporation 2020. All rights reserved. <h3/>
#
# <p>
#