How to get weekly closes starting from a given date?

Working in Notebook currently and I am trying to calculate the standard deviation of the weekly close price of an equity starting from a given date. When I attempted to use data.history, I attempted to use '1w' which did not work, and I'm not sure how I should go about defining the bar_count if it's a dynamic variable as it will change from week to week. I tried to find an existing thread about this, but had no luck. Anyone help would be greatly appreciated, thanks!

1 response

Quantopian only supports two data frequencies - 'daily' and 'minutely'. However, one can easily get other frequencies from these. Pandas resample method to the rescue (https://pandas.pydata.org/pandas-docs/version/0.18/generated/pandas.DataFrame.resample.html).

The first step is to get daily prices. Next use the resample method to sample/extract the weekly close prices. Something like this

daily_prices = get_pricing(my_securities, fields='price', start_date=start, end_date=end, frequency='daily')

# These are daily bars. Since we want weekly bars, use the resample method.
# Use a frequency of 'W-FRI' to get Friday values
# This would typically be the Friday close price unless it's a short trading week.
weekly_prices = daily_prices.resample('W-FRI', closed='right', label='right').last()



Now simply apply the pandas std method to get the standard deviation of prices. However (and this is a big however), one really cannot, and should not, calculate the standard deviation of prices. Prices are 'non-stationary' and don't behave well when typical statistics functions are applied. Most statistics functions assume 'stationary' data. No problem. Use returns instead of prices.

weekly_log_returns = np.log(1 + weekly_prices.pct_change())
weekly_log_returns_std = weekly_log_returns.std()



There are a couple of posts on this which go into a bit more detail.
https://www.quantopian.com/posts/testing-accuracy-of-resample-1w-for-weekly-history-dataframe
https://www.quantopian.com/posts/how-to-use-the-resample-correctly
https://www.quantopian.com/posts/correlation-between-prices-or-returns

Attached is a notebook showing the code in action. To accomplish the same thing in an algo, one would do things very similarly. Just use the data.history method to fetch prices. Probably, the best approach in an algo however, is to write a custom factor (and avoid the data.history method). Let me know if that's an approach you would like to try and if some pointers would help.

0