Back to Community
Weird problem in implementing EWA/EWC pair trading: different prices in Logs and Full Backtest

I was trying to implement Ernie Chan's EWA/EWC pair trading strategy. However, I encountered a weird problem. When I print the prices of EWA and EWC in "Build Algorithm", the Logs says that the price of EWA is $20.37 on 2006-06-06, and the price of EWC is $23.78 on 2006-06-06. However, when I run full back test, the Transaction Details says that EWA is $20.23 on 2006-06-06, and EWC is $23.23. There is some difference in the price in the Logs and Transaction Details everyday. Why is that? Can anyone help to explain? This strategy is supposed to be a winning strategy, but this price difference totally screwed the algorithm up. Thanks a lot

Clone Algorithm
Total Returns
Max Drawdown
Benchmark Returns
Returns 1 Month 3 Month 6 Month 12 Month
Alpha 1 Month 3 Month 6 Month 12 Month
Beta 1 Month 3 Month 6 Month 12 Month
Sharpe 1 Month 3 Month 6 Month 12 Month
Sortino 1 Month 3 Month 6 Month 12 Month
Volatility 1 Month 3 Month 6 Month 12 Month
Max Drawdown 1 Month 3 Month 6 Month 12 Month
import numpy as np
import pandas as pd
from collections import deque

R_P = 1 # refresh period in days
W_L = 28 # window length in days
def initialize(context):
    context.nobs = W_L
    context.max_notional = 100000
    context.min_notional = -100000
    context.stocks = [sid(14516), sid(14517)]
    context.evec = [0.943, -0.822]
    context.unit_shares = 10000
    context.tickers = [int(str(e).split(' ')[0].strip("Security(")) for e in context.stocks]    
    context.prices = pd.DataFrame({ k : pd.Series() for k in context.tickers } )
def handle_data(context, data):
    if len(context.prices)<context.nobs:
        newRow = pd.DataFrame({k:float(data[s].price) for k,s in zip(context.tickers, context.stocks) },index=[0])
        context.prices = context.prices.append(newRow, ignore_index = True)
        comb_price_past_window = np.zeros(len(context.prices))
        for ii,k in enumerate(context.tickers):
            comb_price_past_window += context.evec[ii]*context.prices[k]
        meanPrice = np.mean(comb_price_past_window); stdPrice = np.std(comb_price_past_window)
        comb_price = sum([e*data[s].price for e,s in zip(context.evec, context.stocks)])
        h = (comb_price - meanPrice)/stdPrice
        current_amount = []; cash_spent = [];
        for ii, stock in enumerate(context.stocks):
            current_position = context.portfolio.positions[stock].amount
            new_position = context.unit_shares * (-h) * context.evec[ii]
            cash_spent.append((new_position - current_position)*data[stock].price)
            order(stock, new_position - current_position)

        notionals = []
        for ii,stock in enumerate(context.stocks):
            notionals.append((context.portfolio.positions[stock].amount*data[stock].price)/context.portfolio.starting_cash)"h = {h}, comb_price = {comb_price}, notionals = {notionals}, total = {tot}, price0 = {p0}, price1 = {p1}, cash = {cash}, amount = {amount}, new_cash = {nc}".\
                 format(h = h, comb_price = comb_price, notionals = notionals, \
                        tot = context.portfolio.positions_value +, p0 = data[context.stocks[0]].price, \
                        p1 = data[context.stocks[1]].price, cash =, amount = current_amount, \
                        nc = - sum(cash_spent)))
        newRow = pd.DataFrame({k:float(data[s].price) for k,s in zip(context.tickers, context.stocks) },index=[0])
        context.prices = context.prices.append(newRow, ignore_index = True)
        context.prices = context.prices[1:len(context.prices)]    
        record(h = h, mPri = meanPrice)
        record(comb_price = comb_price)
        record(not0 = notionals[0], not1 = notionals[1])
        #record(price0 = data[context.stocks[0]].price*abs(context.evec[0]), price1 = data[context.stocks[1]].price*abs(context.evec[1]))
        #record(price0 = data[context.stocks[0]].price, price1 = data[context.stocks[1]].price)
    #record(port = context.portfolio.positions_value, cash =

We have migrated this algorithm to work with a new version of the Quantopian API. The code is different than the original version, but the investment rationale of the algorithm has not changed. We've put everything you need to know here on one page.
This backtest was created using an older version of the backtester. Please re-run this backtest to see results using the latest backtester. Learn more about the recent changes.
There was a runtime error.
3 responses


You are printing $20.37/$23.78 on 2006-06-06 which are the closing prices for that day. You are placing orders on that day that are filled with the next day's closing prices which are $20.20/$23.26. With the default commission model of $0.03 per share your orders are filled at $20.23/$23.23.

If you add


in initialize you can disable the commision model.



Thanks a lot for the explanation. What I intended to do is that if I see the price of that day decreases, I go long at the end of that day, not the next day. What should I do to realize this? Do I have to use the minute data and place the order at the end of the day? Thanks.

You definitely need intra-day trading if you're looking at an early-day price and a late-day price.

It's not actually possible to trade at the close price while also knowing the close price. You can know the price a few minutes before the close, and then place your order, and then you'll get the price as it approaches the close.

At first it seems simple to just look at they daily open and close and try to act with those prices, but when you think about it, it's actually more complex. The close price is only the close price AFTER the opportunity to trade is past. You have to put the trade in before you know what the close price will be.


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.