I have a simple moving average algorithm that analyzes the prevailing price of the SPY versus its 10d moving average---it sells a different security (e.g. AAPL) if the price of the SPY falls below its 10d moving average.
One thing I dont like about the standard definition of moving averages is they require "waiting" until a close value has occurred, and then execute on the next days closing price. But say around 3:59 you've got a great idea of what the closing price is....and could enter/exit your trade at that point if you wanted to (I am a small investor; my volume wouldnt impact anything).
For example, On February 10, 2009, the SPY closing price was below the 10d MA (and the day before it was previously above). As a result, my backtest algorithm executed a sell order on AAPL, but the AAPL share price in the sell order is $96.80 -- which is the closing price of AAPL on February 11th. (see the transaction line below)
2009-02-10 16:00:00 AAPL SELL -51 $96.80 ($4,936.80)
How can/would I modify the algorithm so that when the SPY cross-over occured (based on the closing prices on February 10th), it executes the sell order for AAPL on February 10th (instead of 11th)?
def initialize(context):
context.spy = sid(8554)
context.aapl = sid(24)
context.invested = False
# Will be called on every trade event for the securities you specify.
def handle_data(context, data):
mavg = data[context.spy].mavg(10)
price = data[context.spy].price
traded_shares = 5000/data[context.aapl].price
if (price < mavg) and context.invested == False:
order(context.aapl, traded_shares * -1)
context.invested = True
elif (price > mavg) and context.invested == True:
holder = -1 * context.portfolio.positions[sid(24)].amount
order(context.aapl, holder)
context.invested = False