python assignments Flashcards
Imports basics
import yfinance as yf import datetime as dt import pandas as pd import numpy as np start_date = dt.datetime(2015, 1, 2) end_date = dt.datetime(2020, 4, 30)
work out %
work out sma
df_MSFT["range"] = (df_MSFT["High"] - df_MSFT["Close"]) / df_MSFT["Close"] df_MSFT["range"] = df_MSFT["range"].rolling(window=25).mean()
work out on going returns
df_MSFT[‘cc_returns’].cumsum()
how to add data sheets portrait to new df
df = pd.concat( [x, y, z], axis=1 )
How to change column names
df.columns = [‘GLD’, ‘GDX’, ‘USO’]
Change index to datetime
df.index = pd.to_datetime(df.index)
Work out percentages for df, then cumulative growth
df_pct = (df.pct_change()+1).cumprod()
plot df
df_pct.plot(figsize=(16,8))
plt. ylabel(“Percentage Change”)
plt. show()
work with module that allows estimation by ordinary least square
from statsmodels.api import OLS
Fit the model OLS to the first 90 rows,
model = OLS(df[“GLD”].iloc[:90], df[[“USO”,”GDX”]].iloc[:90])
model = model.fit()
print(‘The hedge ratio for GDX and USO are’)
model.params
placing long position
df[‘long_entry’] = df.spread < df.lower_band
df[‘positions_long’] = np.nan
df.loc[df.long_entry, ‘positions_long’] = 1
date for end and start
end_date = dt.date(2020, 4, 30) start_date = dt.date(2015, 1, 2)
Download using yfinance
import yfinance as yf
df = yf.download(“MSFT”, start=start_date, end=end_date)
Work out return
df[“return”] = np.log(df[“Adg Close”] /df[“Adg Close”].shift(1))
Find the day name
data[‘day’] = data.index.day_name()