import numpy as np
import pandas as pd
import statsmodels
from statsmodels.tsa.stattools import coint
import matplotlib.pyplot as plt
from nsepy.archives import get_price_history
from datetime import date
S1 = get_price_history(stock = 'SBIN',
start = date(2015,1,1),
end = date(2015,10,10))
S2 = get_price_history(stock = 'ICICIBANK',
start = date(2015,1,1),
end = date(2015,10,10))
result = coint(S1[['Close']], S2[['Close']])
score = result[0]
pvalue = result[1]
S1[['Close']].plot()
S2[['Close']].plot()
score, pvalue, _ = coint(S1[['Close']], S2[['Close']])
pvalue
diff_series= S2[['Close']] - S1[['Close']]
diff_series.plot()
def zscore(series):
return (series - series.mean()) / np.std(series)
zscore(diff_series).plot()
#plt.axhline(zscore(diff_series).mean(), color='black')
plt.axhline(1.0, color='red', linestyle='--')
plt.axhline(-1.0, color='green', linestyle='--')
Go "Long" the spread whenever the z-score is below -1.0
Go "Short" the spread when the z-score is above 1.0
Exit positions when the z-score approaches zero
Since we originally defined the "spread" as S1-S2, "Long" the spread would mean "Buy 1 share of S1, and Sell Short 1 share of S2" (and vice versa if you were going "Short" the spread)