class PerStockSpreadSlippage(slippage.SlippageModel):
# We specify the constructor so that we can pass state to this class, but this is optional.
def __init__(self, spreads):
# Store a dictionary of spreads, keyed by sid.
self.spreads = spreads
def process_order(self, trade_bar, order):
spread = self.spreads[order.sid]
# in this model, the slippage is going to be half of the spread for the particular stock
slip_amount = spread / 2
new_price = trade_bar.price + (slip_amount * order.direction)
log.info('executing order ' + str(trade_bar.sid) + ' stock bar price: ' + str(trade_bar.price) +
' and trade executes at: ' + str(new_price))
# Create the transaction using the new price we've calculated.
return slippage.create_transaction(
trade_bar,
order,
new_price,
order.amount
)
def initialize(context):
spreads = {
sid(24): 0.05,
sid(3766): 0.08
}
context.position_entered = {
sid(24): False,
sid(3766): False
}
set_slippage(PerStockSpreadSlippage(spreads))
def handle_data(context, data):
for stock in data:
#log.info(stock)
if not context.position_entered[stock]:
order(stock, 100)
log.info('placing market order for ' + str(stock) + ' at price ' + str(data[stock].price))
context.position_entered[stock] = True
I set the period to 01/04/2014 to 02/14/2014. The algorithm is simple. Buy and hold. And I run it @ daily basis. In the full backtest window, I saw the transaction happened at 01/07/2014. Why there's no trade at 01/06/2014?
And the log information is odd to me.
2014-01-06handle_data:47INFOplacing market order for Security(24 [AAPL]) at price 543.949
2014-01-06handle_data:47INFOplacing market order for Security(3766 [IBM]) at price 186.01
2014-01-07process_order:17INFOexecuting order Security(24 [AAPL]) stock bar price: 540.14 and trade executes at: 540.165
2014-01-07process_order:17INFOexecuting order Security(3766 [IBM]) stock bar price: 189.71 and trade executes at: 189.75
How to explain the huge difference between the price of market order and real execution price? why send an order at 01/06 and execute at 01/07? Do I misunderstand something?
Help Plz