I have a relative large xts object. It contains the daily adjusted closing prices from 2012-2021 for each company in the STOXX 600 Europe. I want to calculate the yearly volatility of the stocks for each year for each company.
Here is a link of how my dataset look like:
https://i.stack.imgur.com/wKzx8.jpg
So I started by calculate the log differences by:
XTS.LOGDIFFS <- diff(log(XTS.ADJCLOSE))
The next step would be to calculate the volatility of the stocks for a specific period of time, for example from 2012-05-01 till 2012-12-31, by using the standard deviation and multiply it with the square root of 252 ( 252 are the average trading days).
So my idea is this: First I want to extract the data from my dataset for a specific period of time, in this case from 2012-05-01 till 2012-12-31.
I tried this XT1<-xts(XTS.LOGDIFFS [1:174])
.
As an alternativ I have thought about this:
start_date<- as.Date("2012-05-01")
end_date<-as.Date("2012-12-31")
The next step would be to calculate the volatility for the extracted xts object.
So I tried this: vol<-sd(XTS.1, na.rm = TRUE) *sqrt (252)
.
But this only give me the stock volatility for all combined and not for every single one.
So I think I need a function to get the stock volatility for every company for the extracted period of time in the xts object. But I have no clue how this should look like.