Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Can't get correct price by data.history in algo

Just run a simple algo to print the price of AAPL(data range:03/05/2018-03/06/2018).You get a wrong price when you print 03-05's date on 03-05.But you can get correct price of 03-05 on 03-06. Why? Is there any way to get correct price on the day you run.

def rebalance(context, data):
price_history = data.history(
context.security,
fields='price',
bar_count=5,
frequency='1d'
)
print price_history
====the result=====

2018-03-05 22:31
2018-02-27 00:00:00+00:00 178.34
2018-02-28 00:00:00+00:00 178.10
2018-03-01 00:00:00+00:00 174.90
2018-03-02 00:00:00+00:00 176.28
2018-03-05 00:00:00+00:00 175.85
Freq: C, Name: Equity(24 [AAPL]), dtype: float64

2018-03-06 22:31
2018-02-28 00:00:00+00:00 178.10
2018-03-01 00:00:00+00:00 174.90
2018-03-02 00:00:00+00:00 176.28
2018-03-05 00:00:00+00:00 176.83
2018-03-06 00:00:00+00:00 177.95
Freq: C, Name: Equity(24 [AAPL]), dtype: float64

2 responses

The prices are all correct. The issue is understanding what the 'data.history' method returns. It's not explicit in the documentation (https://www.quantopian.com/help#api-data-history) but the last value returned by 'data.history' (eg price_history[-1]) is the current value. Using fields='price', frequency='1d' will get the last known price for each day. For previous days this is the days close price. However, for the the current day, the last known price is the current price. This value depends upon the time of day the method is called.

In the example above, when run on 2018-03-05 at 22:31 UTC the last price for AAPL was 175.85. That's the current price as of that date and time (which is probably market open).

Now, when that is run the next day 2018-03-06, the price for AAPL on 03-05 will be the closing price for that day. It won't be the same as the price returned above.

Another way to look at it is that one can't look into the future and get the closing price for today. All one can get is the latest price. It isn't until the following day that I can know the close price of the previous day.

I hope that makes sense?

@Dan Whitnable Thanks for your detailed explain.Now I understand.