Back to Community
Getting Yesterdays Close Price

Does anyone know how to get yesterday's close price?

11 responses

Import USEquityPricing from and then add close = USEquityPricing.close.latest in the pipeline.

How would you get the close price of the day prior to this?

One can get the close price of the day before yesterday (ie 2 days ago) with a custom factor something like this:

class Factor_N_Days_Ago(CustomFactor):  
    def compute(self, today, assets, out, input_factor):  
        out[:] = input_factor[0]

Then instantiate this factor using inputs = [USEquityPricing.close] and window_length = 2.

close_day_before_yesterday = Factor_N_Days_Ago(inputs = [USEquityPricing.close], window_length = 2)

Notice this custom factor can be used to get the value of any factor and any number of days ago. Simply change the input and the window_length. Take a look at this post for more discussion on the topic. There are also some notebooks to look at and run.

Hope that helps.


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.

What are we seeing here?
(Especially considering the potential of off-hours trading. I think this might be Eastern 8p on 4-15 and 4-16).

''' Output:
2019-04-17 07:30 trade:17 INFO ARNC  
2019-04-16 00:00:00+00:00    20.680  
2019-04-17 00:00:00+00:00    19.985  
from quantopian.pipeline  import Pipeline  
from quantopian.algorithm import attach_pipeline, pipeline_output

def initialize(context):  
    schedule_function(trade, date_rules.every_day(), time_rules.market_open(minutes=60))  
    attach_pipeline(Pipeline(), 'pipeline')

def trade(context, data):  
    out = pipeline_output('pipeline')

    for s in out.index:

        prices = data.history(s, 'price', 2, '1d')'{} \n{}'.format(s.symbol, prices))  
        assert 0 # deliberate halt for just 1 item and quit, see Logs tab

I thought I recalled discussions regarding the most recent record from data.history with 1 day resolution like this for more than one day being the latest price during the current market day underway, once upon a time.

By the way it seems timely to talk about time a bit. I'm lucky if I know what today's date is, and time is always confusing for me, and backtesting adds an extra dimension. I look forward to a time when all times everywhere are pegged to the particular market time , in this case NYC, letting user override timezone if they wish. We have a mix of local and UTC making things more complicated to talk about with a worldwide audience. For example, checking my watch, this might be a good time for me to take the time to explain that the 7:30 you see here is 1 hour after market open in pacific time because that's where I happen to be at the moment. If we are on the move flying around and saving logs [trying to compare later], they have the potential to not be consistent, or if we are collaborating with people in Sidney and London, we're all looking at different timestamps in logs. Making them all the same is easier said than done I think, considering the possibility of also picking up Shanghai and others in the future, but chances are good that there's an engineer who knows just what to do.

If that '1d' is changed to '1m', since this is running at the start of the current minute, how can it know the close price of this minute?
It is looking into the future is it not?

> get_datetime()  
    Timestamp: 2019-04-17 14:30:00+00:00  
> prices  
    prices: Series  
    Timestamp('2019-04-17 14:29:00+0000', tz='UTC'): 20.015  
    Timestamp('2019-04-17 14:30:00+0000', tz='UTC'): 19.985  

Sorry -- I'm looking for the same solution (except 1 yr back) and I'm not able to get your code to build -- I keep getting
Runtime exception: NameError: name 'CustomFactor' is not defined

I tried plugging the inputs directly into the class input, leaving it CustomFactor as shown, nothing is working.
(defined class before Initialize in my strategy), and called it within initialize like so:

prevYr = Factor_N_Days_Ago(inputs = [USEquityPricing.close], window_length = 255)

First tried:

prevYr = Factor_N_Days_Ago([USEquityPricing.close],window_length=255)

Still nothing. Please help!

I've tried putting these in every combination of locations within my strategy -- it will not build.
I don't understand this code AT all, should this have a return or something?

Please advise exactly how this should be entered into strategy so I can get PrevYr price.


The error NameError: name 'CustomFactor' is not defined seems to imply you haven't imported the class definition for CustomFactor. Ensure there is this import statement in the code

from quantopian.pipeline import  CustomFactor

# Define our custom factor  
class Factor_N_Days_Ago(CustomFactor):  
    Returns the factor value N days ago where window_length=N  
    This is the price adjusted as of the current simulation day.  
    inputs = [USEquityPricing.close]  
    def compute(self, today, assets, out, close_price):  
        out[:] = close_price[0]

# Create an instance of our close price 252 days (~1 year) ago  
close_1_yr_ago_factor = Factor_N_Days_Ago(inputs=[USEquityPricing.close], window_length=252)

Now, if one doesn't want to use a custom factor this can also be calculated from the returns like this

from quantopian.pipeline.factors import Returns  
close_price = USEquityPricing.close.latest  
close_1_yr_ago_calculated = close_price / (Returns(window_length=252) + 1.0)  

Both these approaches will return the close price 252 trading days ago adjusted as of the current simulation day. See the attached notebook. I'll also post an algo which uses this.

Notebook for above...

Loading notebook preview...

Algo using Factor_N_Days_Ago custom factor...

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
This is a sample algorithm on Quantopian showing the use of previous close price.

# Import necessary Pipeline modules
from quantopian.pipeline import Pipeline, CustomFactor
from quantopian.algorithm import attach_pipeline, pipeline_output

# Import specific filters and factors which will be used
from quantopian.pipeline.filters import QTradableStocksUS, StaticAssets
from quantopian.pipeline.factors import Returns

# Import datasets which will be used
from import USEquityPricing

# import optimize
import quantopian.optimize as opt
# Import pandas
import pandas as pd

def initialize(context):
    Initialize constants, create pipeline, and schedule functions
    This uses the default slippage and commission models
    # Universe we wish to trade
    # Place one or more desired symbols below
    context.MY_STOCKS = symbols('SPY', 'GLD')
    # Create our weights (evenly weighted)
    context.WEIGHT = 1.0 / len(context.MY_STOCKS)

    # Make our pipeline and attach to the algo
    attach_pipeline(make_pipeline(context), 'my_pipe')

    # Place orders

def make_pipeline(context):
    Define a pipeline.
    # Specify the universe of securities
    base_universe = StaticAssets(context.MY_STOCKS)
    # Create any needed factors.
    close_price = USEquityPricing.close.latest
    close_1_yr_ago_factor = Factor_N_Days_Ago(
    close_1_yr_ago_calculated = close_price / (Returns(window_length=252) + 1.0)
    # Create our pipeline
    return Pipeline(
        'close_price': close_price,
        'close_1_yr_ago_factor': close_1_yr_ago_factor,
        'close_1_yr_ago_calculated': close_1_yr_ago_calculated,
def before_trading_start(context, data):
    Run our pipeline to fetch the actual data. 
    It's a good practice to place the pipeline execution here. 
    This gets allocated more time than scheduled functions.
    context.output = pipeline_output('my_pipe')
def place_orders_using_optimize(context, data):
    Use Optimize to place orders all at once
    # Make a series of the securities to order and associated weights
    # Ensure that all the short weights are negative (this is what tells opt to short them)
    weights = pd.Series(context.WEIGHT, context.output.index)

    # Create our TargetWeights objective
    target_weights = opt.TargetWeights(weights) 

    # Execute the order_optimal_portfolio method with above objective and constraint
    # No need to loop through the stocks. 
    # The order_optimal_portfolio does all the ordering at one time
    # Also closes any positions not in 'weights'
    # As a bonus also checks for 'can_trade'
    # Could set constraints here if desired
        objective = target_weights,
        constraints = []
######## CUSTOM FACTORS ###########

class Factor_N_Days_Ago(CustomFactor):
    Returns the factor value N days ago where window_length=N
    This is the price adjusted as of the current simulation day.
    def compute(self, today, assets, out, close_price): 
        out[:] = close_price[0]
There was a runtime error.

This is SO much simpler haha and I cannot believe I was missing an import — sorry about that.
I assume that’s what’s missing, let me give it a try !
Thanks so much :)