I have a time series "Ser" and I want to compute volatilities (standard deviations) with a rolling window. My current code correctly does it in this form:
w = 10
for timestep in range(length):
subSer = Ser[timestep:timestep + w]
mean_i = np.mean(subSer)
vol_i = (np.sum((subSer - mean_i)**2) / len(subSer))**0.5
volList.append(w_i)
This seems to me very inefficient. Does Pandas have built-in functionality for doing something like this?
Volatility is used as a measure of a security's riskiness. Typically investors view a high volatility as high risk. Formula. 30 Day Rolling Volatility = Standard Deviation of the last 30 percentage changes in Total Return Price * Square-root of 252.
In Python, we can calculate the moving average using . rolling() method. This method provides rolling windows over the data, and we can use the mean function over these windows to calculate moving averages. The size of the window is passed as a parameter in the function .
Typically, [finance-type] people quote volatility in annualized terms of percent changes in price.
Assuming you have daily prices in a dataframe df
and there are 252 trading days in a year, something like the following is probably what you want:
df.pct_change().rolling(window_size).std()*(252**0.5)
It looks like you are looking for Series.rolling
. You can apply the std
calculations to the resulting object:
roller = Ser.rolling(w)
volList = roller.std(ddof=0)
If you don't plan on using the rolling window object again, you can write a one-liner:
volList = Ser.rolling(w).std(ddof=0)
Keep in mind that ddof=0
is necessary in this case because the normalization of the standard deviation is by len(Ser)-ddof
, and that ddof
defaults to 1
in pandas.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With