Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
How is the portfolio allocation adjusted?
def initialize(context):  
    context.stocks = [sid(1419),sid(12652)]

def handle_data(context, data):  
    # This will order as many shares as needed to  
    # achieve the desired portfolio allocation.  
    # In our case, we end up with 20% allocation for  
    # one stock and 80% allocation for the other stock.  
    order_target_percent(context.stocks[0], .2)  
    order_target_percent(context.stocks[1], .8)

    # Plot portfolio allocations  
    pv = float(context.portfolio.portfolio_value)  
    #print pv  
    portfolio_allocations = []  
    for stock in context.stocks:  
        pos = context.portfolio.positions[stock]  
        #print pos  
        portfolio_allocations.append(  
            pos.last_sale_price * pos.amount / pv * 100  
        )

    record(perc_stock_0=portfolio_allocations[0],  
           perc_stock_1=portfolio_allocations[1])  

I am a little confused about how quantopian runs the backtest. At first I thought it runs to check every minute data.But in the example above, how the portfolio is adjusted? By every minute or on a daily basis?
In the transaction details buy and sell are based on daily basis. (two transactions everyday).If this is right,does that mean quantopian choose close price to adjust the portfolio?

4 responses

Hi Eric,

When the backtest runs, an order is placed in bar 0 and filled in bar 1. This means that in daily mode, if you place an order on 1/6/2014 it will be filled on 1/7/2014. Similarly, if you place at order at 10:00 AM in minute mode, it will be filled at 10:01AM. This is to prevent any look-ahead bias in your algo. It uses the close price of the previous bar to fill the next order and adjust the portfolio.

Handle_data() runs once per bar. If you ran the above code in daily mode, your portfolio will be readjusted once per day to the target allocations. If you ran this in minute mode, it will readjust every minute. What is not included in the code sample, but is very important to consider, are the commission costs and slippage from executing the trades. You can use the default values or set your own according to the stocks you're trading.

Hope that helps!

Alisa

Disclaimer

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by Quantopian. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. No information contained herein should be regarded as a suggestion to engage in or refrain from any investment-related course of action as none of Quantopian nor any of its affiliates is undertaking to provide investment advice, act as an adviser to any plan or entity subject to the Employee Retirement Income Security Act of 1974, as amended, individual retirement account or individual retirement annuity, or give advice in a fiduciary capacity with respect to the materials presented herein. If you are an individual retirement or other investor, contact your financial advisor or other fiduciary unrelated to Quantopian about whether any given investment idea, strategy, product or service described herein may be appropriate for your circumstances. All investments involve risk, including loss of principal. Quantopian makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances.

@Alisa Could u give a example of the 'look ahead bias' placing a order at 10:00 AM and filled by 10:00 AM?

Hello Eric,

Alisa can flesh-out the details, but the basic idea here is that the backtester attempts to simulate the real-world activity of trading. To do so, latency has to be built in to the simulator, since in the real world, when an order is submitted it will not be filled immediately. So, the backtester imposes a minimum conservative delay of one bar period (the delay could be longer for thinly traded securities) to set the fulfillment price.

In effect, you will have a look-ahead bias when the backtest is run if the simulator allows your code to know exactly what the purchase price will be for a given order that is constrained in time (e.g. to be filled as soon as possible).

One could argue that the backtester could be improved by filling orders based on a model that better matches reality (orders filled within a few seconds), but it is conservative in using prices delayed by a minute. There's probably a hack to the slippage model to fix this (e.g. https://www.quantopian.com/posts/trade-at-the-open-slippage-model), but I haven't digested the details.

Grant

Hi Eric,

Grant is exactly right in his explanation. When you backtest, it's critically important to only use information that was available at the time of the trade. When you're running a simulation, you might introduce the bias if you're using information that was not available. For example, you would have look-ahead bias if you tried to trade today using today's close price - simply because you can't know what the close price is until markets close.

We took a conservative approach, as Grant explained, to order filling. When you place an order in the market, it is not filled instantaneously. It can take a couple seconds or more in the real world. Our backtest simulation will fill the order on the next bar, but you can control the fillings by customizing the slippage and commission costs.

Best,
Alisa