Hi All - I had an issue previously with an algorithm that focused on moving averages. Specifically, the 126 day MA was incorrect for the first 125 days of the backtest due to lack of data to properly calculate the MA. So my object was to hold trading until the 126th day of the backtest. To accomplish this I attempted to create two datetime objects and one timedelta object. However, the program does not seem to be handling them correctly.
#Buy and sell SPY when 15 day MA is above 126 day MA
def initialize(context):
#Define and initialize globals
global i
i=0
global startdate
startdate= None
#Add SPDR SPY
context.SPY = sid(8554)
#Set min/max notional
context.max_notional = 1000000.0
context.min_notional = -1000000.0
def handle_data(context, data):
#Get the first date
global startdate
if startdate==None:
startdate=get_datetime()
#Get the change in date time
global newdate
newdate=get_datetime()
#Get the difference in time
timedelta=newdate-startdate
if timedelta.days>126:
print ("Time to trade")
else:
print ("timedelta.days = "+str(timedelta.days))
#compute a notional value where short positions require 2x cash
notional = abs(context.portfolio.positions[context.SPY].amount * data[context.SPY].price)
#test the market MA
MAR_SPY = data[context.SPY].vwap(15) / data[context.SPY].vwap(126)
if MAR_SPY >= 1.0 and notional < context.max_notional:
order(context.SPY,+100)
# print("MAR_SPY>=1 and Notional="+str(notional))
elif MAR_SPY < 1.0 and notional > context.min_notional:
order(context.SPY,-100)
# print("MAR_SPY<1 and Notional="+str(notional))
So the program runs but timedelta.days =0 for all timesteps in the backtest. Any ideas how to rectify this? Thanks.