import pandas as pd
class HyperActiveGreenHyena(QCAlgorithm):
def Initialize(self):
self.SetStartDate(2010, 12, 7)
self.SetCash(100000)
self.AddEquity("SPY", Resolution.Daily)
self.value_symbol=self.AddEquity('IVE',Resolution.Daily).Symbol
self.growth_symbol=self.AddEquity('IVW',Resolution.Daily).Symbol
self.lookback=60
self.value_bb=self.BB(self.value_symbol,self.lookback,2)
self.growth_bb=self.BB(self.growth_symbol,self.lookback,2)
self.SetWarmUp(timedelta(self.lookback*2))
self.ratio_df=pd.DataFrame(columns=['value','growth','ratio'])
def OnData(self, data):
''' OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
Arguments:
data: Slice object keyed by symbol containing the stock data
'''
if (data.Bars.ContainsKey(self.value_symbol)) & (data.Bars.ContainsKey(self.growth_symbol)):
new_df=pd.DataFrame({'value':data.Bars[self.value_symbol].Close, 'growth':data.Bars[self.growth_symbol].Close, 'ratio':data.Bars[self.value_symbol].Close/data.Bars[self.growth_symbol].Close}, index=[self.Time.date()])
self.ratio_df=pd.concat([self.ratio_df.loc[:,['value','growth','ratio']],new_df],axis=0)
self.ratio_df['ma']=self.ratio_df['ratio'].rolling(self.lookback).mean()
self.Log('last value number is {}'.format(self.ratio_df['value'][-1]))
self.Log('last growth number is {}'.format(self.ratio_df['growth'][-1]))
self.Log('last ratio is {}'.format(self.ratio_df['ratio'][-1]))
self.Log('last ma is {}'.format(self.ratio_df['ma'][-1]))
if (self.ratio_df['ratio'][-1])>(self.ratio_df['ma'][-1]):
if not self.Portfolio.Invested:
self.SetHoldings(self.value_symbol, 0.45)
self.SetHoldings(self.growth_symbol, -0.45)
elif (self.ratio_df['ratio'][-1])<(self.ratio_df['ma'][-1]):
if self.Portfolio.Invested:
self.Liquidate()