This get's the adjusted price of a security N days a go.
from quantopian.pipeline import Pipeline, CustomFactor
from quantopian.research import run_pipeline
from quantopian.pipeline.data.builtin import USEquityPricing
class CloseOnN(CustomFactor):
# Define inputs
inputs = [USEquityPricing.close]
# Set window_length to one more than the number of days to look back
# my_close_on_10 = CloseOnN(window_length = 10+1)
window_length = 2
def compute(self, today, assets, out, close):
out[:] = close[0]
def create_pipeline():
# Create a Pipeline computing the previous close factor.
close_5 = CloseOnN(window_length = 5+1)
p = Pipeline()
p.add(close_5, 'close_5')
p.add(USEquityPricing.close.latest, 'close_0')
return p
# Run the pipeline with desired date(s). close_5 collumn will be close 5 trading days before that date
# In this case it will be the close on 6-30-2016 because of the July 4 holiday.
results = run_pipeline(create_pipeline(), '7-8-2016', '8-8-2016')
results
# Let's check if that really did get the value 5 days ago.
# Make it easier and look at a single stock
results.xs(symbols('AAPL'), level=1)
# We can also use the shift method to 'unshift' the data back 5
results['test'] = results.groupby(level=1).close_5.shift(-5)
results.xs(symbols('AAPL'), level=1)