Back to Community
data.history() and data.current()

In the algorithmic environment, I need to retrieve the historical daily close price series + the last traded price (concatenated in the same dataframe).
What function should I use?
I know there are 2 functions: data.history() and data.current().
If I understand correctly none of them can do that?

Thanks

3 responses

To fetch the current price and yesterdays close in a single dataframe use the data.history method with a frequency of '1d'. It's not stated explicitly in the documentation but the last row of returned data will always be todays data (as of when the method is called) and the second to the last row will be yesterdays data. The price field will return the last traded price as of when the method is called (ie the current price). So this will return a dataframe with two rows of prices and a column for each asset. The last row contains the current prices and the first row is yesterdays close prices.

    my_asset_list = symbols('AAPL', 'IBM')  
    prices = data.history(my_asset_list,  
                               fields='price',  
                               bar_count=2,  
                               frequency='1d'  
                               )

One subtlety is the current price timestamps reflect midnight and not the actual time (eg 9:31). This is a result of using the '1d' frequency. The data.history dataframe only knows days and not times. Typically this isn't an issue but something to take note of.

Check out the logs in the attached algo for verification.

Clone Algorithm
2
Loading...
Total Returns
--
Alpha
--
Beta
--
Sharpe
--
Sortino
--
Max Drawdown
--
Benchmark Returns
--
Volatility
--
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
"""
This is an algo with an example using data.history to get yesterdays close
"""
 
def initialize(context):
    context.aapl = symbol('AAPL')
    context.aapl_ibm = symbols('AAPL', 'IBM')
    
    schedule_function(my_trade, 
                      date_rules.every_day(), 
                      time_rules.market_open()
                     )
    schedule_function(my_trade, 
                      date_rules.every_day(), 
                      time_rules.market_open(hours=1)
                     ) 

def my_trade(context,data):
    """
    Fetch last traded price and yesterdays close.
    The last row is the curret price and the first row is 
    yesterdays close price.
    """
    # For a single stock a series is returned
    prices_aapl = data.history(context.aapl, 
                               fields='price', 
                               bar_count=2, 
                               frequency='1d'
                               )
    
    # For a multiple stocks a dataframe is returned
    # one column for each stock
    prices_aapl_ibm = data.history(context.aapl_ibm, 
                               fields='price', 
                               bar_count=2, 
                               frequency='1d'
                               )
    log.info(prices_aapl)
    log.info(prices_aapl_ibm)
    pass
There was a runtime error.
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.

I notice that 'price' and 'close' give the same result. Should not 'close' give the price from the previous days only? Why is it giving a price for the current day?
What's the difference between 'price' and 'close'?

The close field is the last traded price of either the day (if '1d' frequency is selected) or the minute bar (if '1m' frequency is chosen). If there are no trades in a given bar then the value will be nan. These nan values show up especially with lower volume stocks which may not be traded every minute.

The price field is simply the close price but forward filled to eliminate the nans. It is the last traded price and not simply the last traded price in a given bar. The price and close values will always be the same except where close is nan. It's generally a good idea to use price.

The way to think of the data.history method is that it will return all the history it can. Specifically, it will return data up through the minute it was called. Consider the following code called during market hours (ie not in before_trading_start).

    prices = data.history(my_asset_list,  
                               fields='price',  
                               bar_count=2,  
                               frequency='1d'  
                               )

This will return a dataframe with two rows (since bar_count=2). The last row (row -1) will always contain the most recent data. In this case, the most recent data is today's data and will be the most recent minute close price. The second to the last row (row -2) will always be the previous bar data. In this case, yesterday's close. Including the current bar data in history makes the method consistent for both '1d' and 1m' bars (one would typically not want to exclude the most recent bar when fetching minute data). Additionally, it eliminates the need for two function calls in many instances, one for history and one for current.

Below is the behavior for the current days open, high, low, close, price, and volume when using data.history. The last values for these (eg high[-1] ) are the current days values as of the minute the method was called.

open: this is the days open price and will be constant throughout the day
high: the days high up to this time
low: the days low up to this time
close: the close price as of the last minute. This will update every minute and is the same as the data.current close price
price: the same as close but forward filled in cases where the close is nan.
volume: cumulative volume for the day

Hope that helps.