Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
How to convert from business days to calendar days

Hello,

I am a relative newbie to both python and quantopian

I am trying to get a stock series and want to fill in NaN for the non trading days. I am trying the reindex function but it fills NaN for all the days.

Could somebody please guide me?

Thanks,

najmuddin

Code and output is below

Research environment functions

from quantopian.research import prices, symbols

Pandas library: https://pandas.pydata.org/

import pandas as pd

Query historical pricing data for AAPL

aapl_close = prices(
assets=symbols('AAPL'),
start='2017-01-01',
end='2017-01-31'
)

aapl_close.reindex(pd.DatetimeIndex(start='2017-01-01',end='2017-01-31', freq='D'))

Output:
2017-01-01 NaN
2017-01-02 NaN
2017-01-03 NaN
2017-01-04 NaN
2017-01-05 NaN
2017-01-06 NaN
2017-01-07 NaN
2017-01-08 NaN
2017-01-09 NaN
2017-01-10 NaN
2017-01-11 NaN
2017-01-12 NaN

3 responses

One can use the 'resample' method to add in the non-trading calendar days to a pandas series or dataframe. Something like this.

aapl_close_with_trading_days = prices(  
            assets=symbols('AAPL'),  
            start='2017-01-01',  
            end='2017-01-31'  
            )  
aaple_close_with_calendar_days = aapl_close_with_trading_days.resample('1D').last()  

See attached notebook. Good luck.

One may also use the resample() and ffill() methods to fill NaNs for non-trading days.

aaple_close_with_calendar_days = aapl_close.resample('1D').last().ffill()  

2017-01-03 00:00:00+00:00 116.14
2017-01-04 00:00:00+00:00 116.02
2017-01-05 00:00:00+00:00 116.61
2017-01-06 00:00:00+00:00 117.91
2017-01-07 00:00:00+00:00 117.91
2017-01-08 00:00:00+00:00 117.91
2017-01-09 00:00:00+00:00 119.00
2017-01-10 00:00:00+00:00 119.11
2017-01-11 00:00:00+00:00 119.74
2017-01-12 00:00:00+00:00 119.25
2017-01-13 00:00:00+00:00 119.04
2017-01-14 00:00:00+00:00 119.04
2017-01-15 00:00:00+00:00 119.04
2017-01-16 00:00:00+00:00 119.04
2017-01-17 00:00:00+00:00 119.99
2017-01-18 00:00:00+00:00 119.99
2017-01-19 00:00:00+00:00 119.77
2017-01-20 00:00:00+00:00 120.00
2017-01-21 00:00:00+00:00 120.00
2017-01-22 00:00:00+00:00 120.00
2017-01-23 00:00:00+00:00 120.09
2017-01-24 00:00:00+00:00 119.98
2017-01-25 00:00:00+00:00 121.90
2017-01-26 00:00:00+00:00 121.93
2017-01-27 00:00:00+00:00 121.72
2017-01-28 00:00:00+00:00 121.72
2017-01-29 00:00:00+00:00 121.72
2017-01-30 00:00:00+00:00 121.57
2017-01-31 00:00:00+00:00 121.30

Many thanks this is exactly what I wanted.