Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
How to properly get the daily close data?

Hi, I am new to Quantopian. Please forgive me if I have ask some silly questions.

I want to get the daily close price.
Below is the code(simply for testing):

#Imports  
import statsmodels.api as sm  
import quantopian.pipeline.data  
import numpy as np  
import talib  
import scipy

def initialize(context):  
    #  SPY  
    context.assets = sid(8554)

def handle_data(context, data):  
    price_history = data.history(context.assets, fields="price", bar_count=20, frequency="1d")  
    record(price=price_history[-1])  

and in custome data, i get spy = 273.52 on 2/11/2018(Friday) and 271.8 on 3/11/2018(Saturday)
while in tradingview platform, i get 271.89 on 2/11/2018 (Friday)and 273.39 on 5/2/2018(Monday)

  1. I notice there is one day lagging, i must be wrong in somewhere.
  2. there is a little difference, say 273.52 and 273.39 even no lagging.
  3. Why there s data in saturday? do i need to make some timezone setting?
4 responses

The previous day close price is best retrieved using a pipeline. Simply create a factor something like this

    yesterday_close = USEquityPricing.close.latest 

However, the close price can also be fetched using the 'data.history' method something like this

    price_history = data.history(context.assets, fields="close", bar_count=3, frequency="1d")  
    yesterday_close = price_history[-2]

The resulting objects will be a bit different (ie a dataframe indexed by security vs a series indexed by date) but they return the same data. The trick in using the 'data.history' approach is that yesterdays close price is the second from the last (ie [-2]) index in the returned series. The last value (ie [-1]) is the latest close price on the current day and will change.

Most of the questions revolve around data lagging. There isn't any lag. One issue may be that the logging date/time is based upon ones computer timezone. This may make the times confusing. However, that is just the logged time. The algo time can always be fetched using the 'get_datetime' method.

See attached algo. Look specifically at the logs to see the close prices.

Thanks, Dan. Great Help!!

@Dan I've noticed that this doesn't get me Friday's (11/30) closing data...any idea what's wrong here (from TW's HRP notebook)?

rets = get_pricing(symbols,
fields='price',
start_date='2004-1-1',
end_date='2018-12-2'
).pct_change().rename(columns=lambda x: x.symbol)

@Rob Bird Hmm. Your code works for me. The last date returned is Friday 2018-11-30. See attached notebook. Maybe I misunderstood?