Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
How does transaction work in backtest ?

I'm newbie in quantopian and tried backtesting with very simple code

def initialize(context):  
    # Reference to AAPL  
    context.aapl = sid(24)

def handle_data(context, data):  
    # Position 100% of our portfolio to be long in AAPL  
    order_target_percent(context.aapl, 1.00)  
  1. Backtest setting
    From 2008-03-03 to 2008-03-05 with $1,000,000 initial capital

  2. Transaction Detail
    2008-03-03 11:32 PM : BUY $125.35 x 4127 (=$517,311.20)
    2008-03-03 11:33 PM : BUY $125.78 x 3886 (=$488,792.74)
    2008-03-03 11:33 PM : BUY $125.79 x 2137 (=$268,808,96)
    2008-03-03 11:34 PM : BUY $125.31 x 1713 (=$214,659.46)
    2008-03-03 11:34 PM : SELL $125.31 x -2186 (= -$273,918.92)
    2008-03-03 11:35 PM : SELL $125.65 x -1721 (= -$216,247.09)
    2008-03-03 11:36 PM : BUY $125.84 x 3 (=$377.52)

This is how I understand "Transaction Detail":

  • 11:32PM : There are only 4127 available shares (at $125.35) in market so bought them all. Cash I hold : 1,000,000 - 517,311.20 = $482,688.8
  • 11:33PM : There are only 3886 available shares (at $125.78) in market so bought them all. Cash I hold : 482,688.8 - 488,792.74 = ($-6,103.94)

Q1. How can I buy shares more than I could afford? I mean, buying 3886 shares make my cash minus value... How could it happen?
Q2. How could transaction occur two times in 11:33pm? Why doesn't it occur only once?
Q3. As you can see above, agent start to sell its share on 11:34pm and 11:35pm. How did it have to sell its share?
Q4. Why does transaction not exist after 11:36pm?

I think that these questions are all caused by my misunderstanding of order_target_percent(context.aapl, 1.00). Isn't it mean "Buy all available shares in every time handle_data() is executed?"

Thanks you in advance for your explanation.