Hello,
I would like to ask for your help in finding the bug in my code (or Quantopian's) in the Halloween code that I previously shared. Here is a cleaner version:
def initialize(context):
#context.stocks = [sid(24)] #AAPL
context.stocks = [sid(22169)] #SNP
#context.stocks = [sid(8554)] #S&P500
# Setting our maximum position size
context.max_notional = 1000000.1
context.min_notional = -1000000.0
# Don't forget to change this number to match the number of stocks in your portfolio
context.max_stock = len(context.stocks)
log.info(' SID-- Price-- Shares Value------- Order')
def handle_data(context, data):
max_notional = int(context.max_notional / context.max_stock)
for stock in context.stocks:
trade_date = data[stock].datetime
# buy if not already in trade and if we are in November
if (context.portfolio.positions[stock].amount == 0) and (trade_date.month == 10):
price = data[stock].price
shares = int(max_notional / price)
value = price * shares
order(stock, shares)
log.info('{:>5} {:>7.3f} {:>6} {:> 12.3f} BUY'.format(stock, price, shares, -value))
# sell if already in trade and if we are in March
elif (context.portfolio.positions[stock].amount != 0) and (trade_date.month == 5):
price = data[stock].price
shares = context.portfolio.positions[stock].amount
value = price * shares
order(stock, -shares)
log.info('{:>5} {:>7.3f} {:>6} {:> 12.3f} SELL'.format(stock, price, shares, value))
What happens is that if I run the code with AAPL or S&P500 everything works, but if I run the same code with SNP it shows the following output (with too many sells):
1970-01-01initialize:13INFO SID-- Price-- Shares Value------- Order
2008-10-01handle_data:28INFO22169 78.350 12763 -999981.050 BUY
2009-05-01handle_data:36INFO22169 78.560 12763 1002661.280 SELL
2009-10-01handle_data:28INFO22169 82.590 12108 -999999.720 BUY
2010-05-03handle_data:36INFO22169 80.040 12108 969124.320 SELL
2010-10-01handle_data:28INFO22169 88.940 11243 -999952.420 BUY
2011-05-02handle_data:36INFO22169 99.940 11243 1123625.420 SELL
2011-10-03handle_data:28INFO22169 95.650 10454 -999925.100 BUY
2012-05-01handle_data:36INFO22169 107.450 10454 1123282.300 SELL
2012-10-01handle_data:28INFO22169 92.550 10804 -999910.200 BUY
2013-05-01handle_data:36INFO22169 108.720 10804 1174610.880 SELL
2013-05-02handle_data:36INFO22169 108.680 5268 572526.240 SELL
2013-05-03handle_data:36INFO22169 109.130 -370 -40378.100 SELL
2013-05-06handle_data:36INFO22169 109.290 -4898 -535302.420 SELL
If you analyze the code, there should be a sell for every buy, but with this specific sid it shows 3 extra sells.
Thanks in advance,
JM