0
$\begingroup$

I'm pretty new to python/data viz and this is my first time asking a question on here but I have a df with monthly price data back to 2016 for 6 different instruments. I just want to be able to calculate each asset's annualized volatility (std dev of each year's log returns) for each year from 2017 to YTD 2021. Here's what I have thus far:

df = pd.read_csv('csv.csv',index_col='Dates')
df.index = pd.to_datetime(df.index,format='%Y-%m-%d')
df = df.sort_index()

returns_2017 =  df['2017-01-31':].pct_change()
log_returns_2017 = np.log(returns_2017+1)

vol_ann = log_returns_2017.groupby([log_returns_2017.index.year]).first().mean()*(252**0.5)
vol_ann.fillna(method='ffill', inplace=True)

ax = sns.lineplot(data=vol_ann).set_title('Annualized Vol since 2017')
plt.xlabel('Date')
plt.ylabel('Vol')
plt.show()

I apologize in advance if I'm not providing enough color but I can't seem to get the df to show me each year's annualized vol. This is what I get when I print out vol_ann:

Asset No 1    0.222027
Asset No 2    0.060578
Asset No 3    0.486497
Asset No 4    0.122261
Asset No 5    0.170447
Asset No 6    0.193511

Here's what the log returns look like, FYI (just the head):

           Asset No 1  Asset No 2  Asset No 3  Asset No 4  Asset No 5  Asset No 6
Dates
2017-01-31         NaN         NaN         NaN         NaN         NaN         NaN
2017-02-28    0.044188    0.001672    0.036523    0.022114    0.028128    0.005650
2017-03-31    0.024026   -0.027594   -0.000389   -0.010130   -0.024969   -0.009259
2017-04-30    0.004389   -0.015801    0.009050   -0.001275   -0.010357   -0.005727
2017-05-31    0.056327   -0.014189    0.011510    0.000381   -0.003176    0.001087

Thanks for any advice! If I asked anything incorrectly, please let me know.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.