Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Question about the Quantity Field

Hi,

I have a simple strategy which only does buy and hold on AAPL.

As specified in the code, there are no slippage and no transaction cost and 100% full investment on $1,000,000 initial capital.
There was a buy order been executed. In the "Transaction Details" section, the "Last Sale Price" was $109.51.
The Quantity field has shown that I have bought 9,135 number of shares. But I have worked out that I should be buying 1,000,000/109.51 = 9,132 (rounded down the nearest integer) number of shares instead. Any ideas?

Thank you.

Anthony

3 responses

You are using the actual buy price of 109.51 for your calculation. The problem is that the order_target_percent method can't look into the future and know what price you will actually buy at. The best it can do is use the last price. It looks at the last price and uses that price to calculate the number of shares and then simply places a market order for that many shares.

I added some logging to your code (see attached backtest) to show what is actually happening. Here's the log output...

Last price: 109.465  Account cash 1000000.0. Opened order for 9135 shares at 109.465. Total order 999962.775

As you can see, the method used the last price of 109.465 and ordered 9135 shares to order (what it thought) would be 100% of your portfolio value (rounded down to the nearest share). As you noticed however, the market price went up to 109.51 at the next tick when the order executed and you ended up exceeding the amount in your portfolio. There are several posts here in the forums regarding this. I posted one https://www.quantopian.com/posts/backtest-transactions.

In real trading it's best to always use limit orders and maintain a small cash buffer to account for this. Not a big problem with a margin account but for a cash account you don't want to find yourself with negative cash.

Here's your code modified to use a limit order with a limit price of the last price. Notice that the order goes through but it fills a few ticks later (and you get it at a lower price - that limit order saved you about $500).

In general I find this approach be good practice in real trading. You would never pay more than the limit amount. Worse case is that the order wouldn't execute. Technically one would buy at a lower price if the market price is lower, but my experience is the order always fills at exactly your limit.

FWIW, you can define a custom slippage model, such as:

https://www.quantopian.com/posts/trade-at-the-open-slippage-model

You can shift the price closer to the current price, as the example illustrates.