import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import yfinance as yf
from pandas.plotting import scatter_matrix
TSLA = (yf.download("TSLA", period ="5y"), "TSLA")
tsla = TSLA[0]
GM = (yf.download("GM", period = "5y"), "GM")
gm = GM[0]
FORD = (yf.download("F", period = "5y"), "Ford")
ford = FORD[0]
FORD[0].head()
def plottern(df, col, type="line"):
df[0][col].plot(figsize = (12,8), label=df[1], kind =type)
FIRMS = [TSLA, GM, FORD]
for a in FIRMS:
plottern(a, "Close")
plt.legend()
plt.show()
for a in FIRMS:
plottern(a, "Volume")
plt.legend()
plt.show()
ford["Volume"].argmax()
ford.iloc[1149,:]
# Total trade
def totaltrade(df):
df[0]["Totaltrade"] = df[0]["Close"]*df[0]["Volume"]
for a in FIRMS:
totaltrade(a)
FORD[0].head()
for a in FIRMS:
plottern(a, "Totaltrade")
plt.legend()
plt.show()
TSLA[0]["Totaltrade"].argmax()
TSLA[0].iloc[TSLA[0]["Totaltrade"].argmax(),:]
## Moving averages
GM[0]["Close"].rolling(50).mean().plot(figsize = (12,8), label="MA50")
GM[0]["Close"].rolling(200).mean().plot(figsize = (12,8), label = "MA200")
GM[0]["Close"].plot()
plt.legend()
plt.show()
GM[0]["returns"] = GM[0]["Close"]/GM[0]["Close"].shift(1) - 1
FORD[0]["returns"] = FORD[0]["Close"].pct_change()
TSLA[0]["returns"] = TSLA[0]["Close"].pct_change()
GM[0].head()
GM[0]["returns"].hist(bins = 50)
FORD[0]["returns"].hist(bins = 50)
TSLA[0]["returns"].hist(bins = 50)
def histo(df, col):
df[0][col].hist(bins=50, figsize =(12,8), label=df[1], alpha=0.4)
for a in FIRMS:
histo(a, "returns")
plt.legend()
plt.show()
#KDE plot of returns
for a in FIRMS:
plottern(a, "returns", "kde")
plt.legend()
plt.show()
#boxplot of returns
box = pd.concat([TSLA[0]["returns"],GM[0]["returns"],FORD[0]["returns"]], axis=1)
box.columns = ["TSLA returns", "GM returns", "FORD returns"]
box.plot(kind="box", figsize = (12,8), colormap="jet")
#
scatter_matrix(box, figsize = (9,9), alpha = 0.2, hist_kwds={"bins":50});
# Relationship between ford and GM.
# Cumulative returns
def cumulativeR(df):
df[0]["CumRet"] = (1 + df[0]["returns"]).cumprod()
for a in FIRMS:
cumulativeR(a)
FORD[0].head()
# LINE PLOT OF CUMULATIVE RETURNS
for a in FIRMS:
plottern(a, "CumRet")
plt.legend()
plt.show()