Please update these 2 functions:
Code:
def get_beta(y,x,lb=20,amt=10000):
ratio = y[-lb:] / x[-lb:]
ratio_mean = ratio.mean()
std_dev = ratio.std()
zscore = (ratio- ratio_mean)/std_dev
print('Latest zScore : ',zscore.iloc[-1])
model_ols = sm.OLS(y[-lb:], x[-lb:]).fit()
print("%s Qty: " %y.name, int(amt/y.iloc[-1]))
print("%s Qty: " %x.name, int((amt/y.iloc[-1])*model_ols.params[0]))
return(model_ols.params)
def getnew_zScore(SS1,SS2,SS1_price,SS2_price,lb=20,amt=10000):
S1=SS1.append(pd.Series([SS1_price]),ignore_index=True)
S2=SS2.append(pd.Series([SS2_price]),ignore_index=True)
S1.name = SS1.name
S2.name = SS2.name
spread = S1[-lb:] / S2[-lb:]
spread_mean = spread.mean()
std_dev = spread.std()
zscore = (spread - spread_mean)/std_dev
print('Latest zScore : ',zscore.iloc[-1])
get_beta(S1,S2,lb=20,amt=10000)
Now when you call the function:
Code:
SS1 = df['HINDZINC']
SS2 = df['NMDC']
getnew_zScore(SS1,SS2,275,103,20,10000)
The output will be:
Code:
Latest zScore : 0.24864342871878325
HINDZINC Qty: 36
NMDC Qty: 96
The last value 10000 is the amt you want to invest in each stock in increments. I am trying a slightly different approach to managing the pairs. Instead of buying futures lots, I use cash and start with small increments. I.e at each eod, if the zscore is more than +/- 2.0 then I make adjustments. For the stock to be bought I take Positional trade and for the stock to be shorted, I short it in the morning as MIS order.
i.e after the 1st trade getnew_zScore(SS1,SS2,275,103,20,10000), if the zscore is more than +/-2.0 then I take the 2nd trade next day by investing another 10000. i.e getnew_zScore(SS1,SS2,275,103,20,20000) to get the new qty for the stocks.
Use getnew_zScore(SS1,SS2,275,103,20,10000) only if you want to make adjustment before eod, else you can just use get_beta(S1,S2,lb=20,amt=10000) after end of day to get the new qty for next day.
Code:
SS1 = df['HINDZINC']
SS2 = df['NMDC']
get_beta(SS1,SS2,20,10000);
Output:
Latest zScore : 0.5450456431905395
HINDZINC Qty: 36
NMDC Qty: 96