Back to Community
Algo logs the wrong dates and doesn't have accurate pricing

I am a noob just testing out a very simple strategy of buying leveraged ETFs during the last two trading hours if they have moved a certain percentage.

I noticed the logs in my backtests had some big issues with the dates and prices. First the dates all seem to be off one day; the quantopian data is all one day ahead. For example, when it is actually the 6th, it generates logs as the 7th, and the I have logs Saturdays when the market is not open.

Regarding pricing data, I suspect the error is on my part, but I can't get an accurate figure for the previous day's close. I define closing price as:

close_price = data.current(context.securities[0],"close")

inside a scheduled function that runs at the end of the of the day. I log this number, and it appears to just be a random number. When I schedule the function to run at a different time (but still on the same day), the supposed closing price changes as well. Not too sure where I went wrong here, and what price I'm actually referencing.

Lastly, what is the most efficient way to get a stock's current price? I use:

current_price = data.history(context.securities[0], "price", 2, "1m").iloc[0]

But I'm sure there's a much more efficient way that I don't know.

Thanks for any feedback. I'm a complete beginner programmer, and I'm really eager to learn.

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
For this example, we're going to write a simple momentum script.  
When the stock goes up quickly, we're going to buy; 
when it goes down we're going to sell.  
Hopefully we'll ride the waves.

To run an algorithm in Quantopian, you need to define two functions: 
initialize and handle_data.

Note: AAPL had a 7:1 split in June 2014, which is reflected in the 
recorded variables plot.

The initialize function sets any data or variables that 
you'll use in your algorithm. 
It's only called once at the beginning of your algorithm.
def initialize(context):
    #Labu and LABD
    context.securities = [sid(49073),sid(49072)]
        #Buy at 2 pm
    schedule_function(purchase, date_rule=date_rules.every_day(),time_rule=time_rules.market_close(hours=3))
    schedule_function(sell, date_rule=date_rules.every_day(),time_rule=time_rules.market_close(minutes=10))

def purchase(context, data):

    close_price = data.current(context.securities[0],"close")
    current_price = data.history(context.securities[0], "price", 2, "1m").iloc[0]

    # If our stock is currently listed on a major exchange
    if data.can_trade(context.securities[0]):
        #buy whichever stock is up 1%
        if current_price > (1.01 * close_price):
            order_target_percent(context.securities[0], 1)
  "Buying %s" % (context.securities[0].symbol))
        elif current_price < (.99 * close_price):
            order_target_percent(context.securities[1], 1)
  "Selling %s" % (context.securities[1].symbol))
def sell(context,data):
    order_target_percent(context.securities[0], 0)
    order_target_percent(context.securities[1], 0)
There was a runtime error.
1 response

Hi Yuyang, thanks for posting! Here are some answers to your questions:

  • Log dates one day ahead: Log dates are printed based on your system timezone. By your name, I assume you're in China, which means your timezone is 12+ hours ahead of US Eastern Time. This means that logs that are simulated in the afternoon Eastern Time will appear as the next day in China.

    To get logs with Eastern Time simulation dates, you can change your system time zone to US/Eastern if you want. Alternatively you could prefix your logs with get_datetime('US/Eastern') to make clear what the Eastern Time simulation date is.

  • Getting the previous day's close / getting the current price: data.current gets the pricing data for the current minute bar; specifically, data.current( ... , "close") gets the close of the last minute, i.e., the current price of the equity. So you can get the current price that way or by using the alias for "close", "price" (reflecting that the latest data available for the price is the close of the last minute).

    If you want the previous day's close, that would be the close of the last complete daily bar. To get daily bars, you have to use data.history. As the documentation says, the last daily bar given by data.history is a partial bar for the current day's data; so to get the previous day you have to look back 2 days. Here's how it's done:

data.history(context.securities[0], "close", 2, "1d")[-2]  

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.