calingal-fmdexer7
December 11, 2023
1 Stock Market Analysis Project Overview
Welcome to your first Python Project! This project introduces the basics of Financial Modeling
Using Python.
You will be analyzing stock data related to a few car companies, from January 1, 2012, to Jan 1,
2017. Keep in mind that this project is mainly just to practice your skills with matplotlib, pandas,
and numpy. Do not infer financial trading advice from it.
1.0.1 Part 0: Import
Import the various libraries you will need. You can always just come back up here or import as
you go along.
[1]: import numpy as np
import pandas as pd
import [Link] as plt
%matplotlib inline
[2]: pip install pandas_datareader
Requirement already satisfied: pandas_datareader in
/srv/conda/envs/notebook/lib/python3.6/site-packages (0.10.0)
Requirement already satisfied: requests>=2.19.0 in
/srv/conda/envs/notebook/lib/python3.6/site-packages (from pandas_datareader)
(2.27.1)
Requirement already satisfied: pandas>=0.23 in
/srv/conda/envs/notebook/lib/python3.6/site-packages (from pandas_datareader)
(1.1.5)
Requirement already satisfied: lxml in
/srv/conda/envs/notebook/lib/python3.6/site-packages (from pandas_datareader)
(4.9.3)
Requirement already satisfied: python-dateutil>=2.7.3 in
/srv/conda/envs/notebook/lib/python3.6/site-packages (from
pandas>=0.23->pandas_datareader) (2.8.2)
Requirement already satisfied: pytz>=2017.2 in
/srv/conda/envs/notebook/lib/python3.6/site-packages (from
pandas>=0.23->pandas_datareader) (2021.3)
Requirement already satisfied: numpy>=1.15.4 in
1
/srv/conda/envs/notebook/lib/python3.6/site-packages (from
pandas>=0.23->pandas_datareader) (1.19.5)
Requirement already satisfied: charset-normalizer~=2.0.0 in
/srv/conda/envs/notebook/lib/python3.6/site-packages (from
requests>=2.19.0->pandas_datareader) (2.0.10)
Requirement already satisfied: urllib3<1.27,>=1.21.1 in
/srv/conda/envs/notebook/lib/python3.6/site-packages (from
requests>=2.19.0->pandas_datareader) (1.26.8)
Requirement already satisfied: idna<4,>=2.5 in
/srv/conda/envs/notebook/lib/python3.6/site-packages (from
requests>=2.19.0->pandas_datareader) (3.3)
Requirement already satisfied: certifi>=2017.4.17 in
/srv/conda/envs/notebook/lib/python3.6/site-packages (from
requests>=2.19.0->pandas_datareader) (2021.5.30)
Requirement already satisfied: six>=1.5 in
/srv/conda/envs/notebook/lib/python3.6/site-packages (from python-
dateutil>=2.7.3->pandas>=0.23->pandas_datareader) (1.16.0)
Note: you may need to restart the kernel to use updated packages.
1.1 Part 1: Getting the Data
1.1.1 Tesla Stock (Ticker: TSLA on the NASDAQ)
Use pandas_datareader to obtain the historical stock information for Tesla from Jan 1, 2012 to
Jan 1, 2017.
[3]: import pandas_datareader
import datetime
[4]: import pandas_datareader.data as web
[5]: start = [Link](2012, 1, 1)
end = [Link](2017, 1, 1)
tesla = [Link]("TSLA", 'yahoo', start, end)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-5-8978b4444a5d> in <module>
1 start = [Link](2012, 1, 1)
2 end = [Link](2017, 1, 1)
----> 3 tesla = [Link]("TSLA", 'yahoo', start, end)
/srv/conda/envs/notebook/lib/python3.6/site-packages/pandas/util/_decorators.py␣
↪in wrapper(*args, **kwargs)
197 else:
198 kwargs[new_arg_name] = new_arg_value
--> 199 return func(*args, **kwargs)
200
2
201 return cast(F, wrapper)
/srv/conda/envs/notebook/lib/python3.6/site-packages/pandas_datareader/[Link]␣
↪in DataReader(name, data_source, start, end, retry_count, pause, session,␣
↪api_key)
376 retry_count=retry_count,
377 pause=pause,
--> 378 session=session,
379 ).read()
380
/srv/conda/envs/notebook/lib/python3.6/site-packages/pandas_datareader/[Link]␣
↪in read(self)
251 # If a single symbol, (e.g., 'GOOG')
252 if isinstance([Link], (string_types, int)):
--> 253 df = self._read_one_data([Link], params=self.
↪_get_params([Link]))
254 # Or multiple symbols, (e.g., ['GOOG', 'AAPL', 'MSFT'])
255 elif isinstance([Link], DataFrame):
/srv/conda/envs/notebook/lib/python3.6/site-packages/pandas_datareader/yahoo/
↪[Link] in _read_one_data(self, url, params)
151 try:
152 j = [Link]([Link](ptrn, [Link], [Link]).
↪group(1))
--> 153 data =␣
↪j["context"]["dispatcher"]["stores"]["HistoricalPriceStore"]
154 except KeyError:
155 msg = "No data fetched for symbol {} using {}"
TypeError: string indices must be integers
[6]: [Link]()
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-6-fc96ec1e29c9> in <module>
----> 1 [Link]()
NameError: name 'tesla' is not defined
[7]: tesla.to_csv('Tesla_Stock.csv')
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-7-29909d1e55af> in <module>
3
----> 1 tesla.to_csv('Tesla_Stock.csv')
NameError: name 'tesla' is not defined
1.1.2 Other Car Companies
Repeat the same steps to grab data for Ford and General Motors (GM).
[8]: ford = [Link]("F", 'yahoo', start, end)
gm = [Link]("GM",'yahoo',start,end)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-8-ac64ec160103> in <module>
----> 1 ford = [Link]("F", 'yahoo', start, end)
2 gm = [Link]("GM",'yahoo',start,end)
/srv/conda/envs/notebook/lib/python3.6/site-packages/pandas/util/_decorators.py␣
↪in wrapper(*args, **kwargs)
197 else:
198 kwargs[new_arg_name] = new_arg_value
--> 199 return func(*args, **kwargs)
200
201 return cast(F, wrapper)
/srv/conda/envs/notebook/lib/python3.6/site-packages/pandas_datareader/[Link]␣
↪in DataReader(name, data_source, start, end, retry_count, pause, session,␣
↪api_key)
376 retry_count=retry_count,
377 pause=pause,
--> 378 session=session,
379 ).read()
380
/srv/conda/envs/notebook/lib/python3.6/site-packages/pandas_datareader/[Link]␣
↪in read(self)
251 # If a single symbol, (e.g., 'GOOG')
252 if isinstance([Link], (string_types, int)):
--> 253 df = self._read_one_data([Link], params=self.
↪_get_params([Link]))
254 # Or multiple symbols, (e.g., ['GOOG', 'AAPL', 'MSFT'])
255 elif isinstance([Link], DataFrame):
/srv/conda/envs/notebook/lib/python3.6/site-packages/pandas_datareader/yahoo/
↪[Link] in _read_one_data(self, url, params)
151 try:
4
152 j = [Link]([Link](ptrn, [Link], [Link]).
↪group(1))
--> 153 data =␣
↪j["context"]["dispatcher"]["stores"]["HistoricalPriceStore"]
154 except KeyError:
155 msg = "No data fetched for symbol {} using {}"
TypeError: string indices must be integers
[9]: [Link]()
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-9-e4705156e782> in <module>
----> 1 [Link]()
NameError: name 'ford' is not defined
[10]: ford.to_csv('Ford_Stock.csv')
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-10-1ce938052052> in <module>
----> 1 ford.to_csv('Ford_Stock.csv')
NameError: name 'ford' is not defined
[11]: [Link]()
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-11-65d251d047b7> in <module>
----> 1 [Link]()
NameError: name 'gm' is not defined
[12]: gm.to_csv('GM_Stock.csv')
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-12-85734562347e> in <module>
----> 1 gm.to_csv('GM_Stock.csv')
5
NameError: name 'gm' is not defined
1.2 Part 2: Visualizing the Data
Time to visualize the data. Follow along and recreate the plots below according to the instructions
and explanations.
Recreate the linear plot of all the stocks’ Open price! Hint: For the legend, use label parameter
and [Link]().
[13]: from matplotlib import pyplot as plt
tesla['Open'].plot(label='Tesla',figsize=(16,8),title='Open Price')
gm['Open'].plot(label='GM')
ford['Open'].plot(label='Ford')
[Link]()
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-13-be2c30f9add4> in <module>
1 from matplotlib import pyplot as plt
----> 2 tesla['Open'].plot(label='Tesla',figsize=(16,8),title='Open Price')
3 gm['Open'].plot(label='GM')
4 ford['Open'].plot(label='Ford')
5 [Link]()
NameError: name 'tesla' is not defined
Plot the Volume of stock traded each day.
[14]: tesla['Volume'].plot(label='Tesla',figsize=(16,8),title='Volume Traded')
gm['Volume'].plot(label='gm')
ford['Volume'].plot(label='ford')
[Link]()
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-14-511fcff41b97> in <module>
----> 1 tesla['Volume'].plot(label='Tesla',figsize=(16,8),title='Volume Traded')
2 gm['Volume'].plot(label='gm')
3 ford['Volume'].plot(label='ford')
4 [Link]()
NameError: name 'tesla' is not defined
6
As can be observed, Ford had a really big spike somewhere in late 2013. What was the date of this
maximum trading volume for Ford?
[15]: ford['Volume'].argmax()
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-15-368048eda2a5> in <module>
----> 1 ford['Volume'].argmax()
NameError: name 'ford' is not defined
The Open Price Time Series Visualization makes Tesla look like its always been much more valuable
as a company than GM and Ford. But to understand this, one would need to look at the total
market cap of the company, not just the stock price. Unfortunately, the current data does not
have that information of total units of the stock present. But a simple calculation can be done to
represent the total money traded. It is by multiplying the Volume column with the Open price.
Remember that this still is not the actual Market Cap, it is just a visual representation of the total
amount of money being traded around using the time series.
To do the above, create a new column for each dataframe called “Total Traded” which is the Open
Price multiplied by the Volume Traded.
[16]: tesla['Total Traded'] = tesla['Open']*tesla['Volume']
ford['Total Traded'] = ford['Open']*ford['Volume']
gm['Total Traded'] = gm['Open']*gm['Volume']
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-16-ac5481831135> in <module>
----> 1 tesla['Total Traded'] = tesla['Open']*tesla['Volume']
2 ford['Total Traded'] = ford['Open']*ford['Volume']
3 gm['Total Traded'] = gm['Open']*gm['Volume']
NameError: name 'tesla' is not defined
Plot the “Total Traded” against the time index.
[17]: tesla['Total Traded'].plot(label='Tesla',figsize=(16,8))
gm['Total Traded'].plot(label='GM')
ford['Total Traded'].plot(label='Ford')
[Link]()
[Link]('Total Traded')
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
7
<ipython-input-17-78b7ffc42905> in <module>
----> 1 tesla['Total Traded'].plot(label='Tesla',figsize=(16,8))
2 gm['Total Traded'].plot(label='GM')
3 ford['Total Traded'].plot(label='Ford')
4 [Link]()
5 [Link]('Total Traded')
NameError: name 'tesla' is not defined
As can be observed, there was a huge amount of money traded for Tesla somewhere in early 2014.
What date was that and what happened?
[18]: tesla['Total Traded'].argmax()
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-18-a1317819a29b> in <module>
----> 1 tesla['Total Traded'].argmax()
NameError: name 'tesla' is not defined
Let us practice plotting a sample moving average (MA) of one of the cars. Plot out the MA50 and
MA200 for GM.
[19]: gm['MA50'] = gm['Open'].rolling(50).mean()
gm['MA200'] = gm['Open'].rolling(200).mean()
gm[['Open','MA50','MA200']].plot(label='gm',figsize=(16,8))
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-19-750af5317d14> in <module>
----> 1 gm['MA50'] = gm['Open'].rolling(50).mean()
2 gm['MA200'] = gm['Open'].rolling(200).mean()
3 gm[['Open','MA50','MA200']].plot(label='gm',figsize=(16,8))
NameError: name 'gm' is not defined