I am writing a script to calculate the standard deviation of S&P500 and want to compare the rolling standard deviation to the long term average of the SD.
I can make my codes work but seems kind of clumsy. I want to ask two questions to make my code easier to understand.
- Suppose I have two indices. Can I use one line of code to find the annualised SD for both tickers? Now I have to do it ticker by ticker
GSPC.new <- merge(GSPC.new,rollapply(GSPC.new$GSPC.adj.ret, 252, sd))
- It is easier to slice a xts object. Can I do the same in tibble dataframe?
gspc.avg10yr <- mean(na.omit(GSPC.new$GSPC.adj.std.annualised["2011/2022"]))
All code below can be executed directly in RStudio directly.
library(tidyverse)
library(quantmod)
library(ggplot2)
tickers <- c("^HSI","^GSPC")
getSymbols(Symbols = tickers,
src = "yahoo",
index.class = "POSIXct",
from = "1997-01-01")
GSPC.new <- na.omit(GSPC)
GSPC.new <- merge(GSPC.new, dailyReturn(GSPC.new$GSPC.Adjusted))
colnames(GSPC.new)[7] <- "GSPC.adj.ret"
GSPC.new <- merge(GSPC.new,rollapply(GSPC.new$GSPC.adj.ret, 252, sd)) # how to annualised both tickers in one line
colnames(GSPC.new)[8] <- "GSPC.adj.std"
GSPC.new <- merge(GSPC.new, GSPC.new$GSPC.adj.std*sqrt(252))
colnames(GSPC.new)[9] <- "GSPC.adj.std.annualised"
GSPC.new.tbl <- as_tibble(fortify(GSPC.new))
p.gspc <- ggplot(GSPC.new.tbl, aes(x=Index,y=GSPC.adj.std.annualised))
p.gspc + geom_line()
gspc.avg10yr <- mean(na.omit(GSPC.new$GSPC.adj.std.annualised["2011/2022"])) # is it possible to do in tibble way?
gspc.avg15yr <- mean(na.omit(GSPC.new$GSPC.adj.std.annualised["2006/2022"]))
gspc.avg20yr <- mean(na.omit(GSPC.new$GSPC.adj.std.annualised["2001/2022"]))
gspc.avg25yr <- mean(na.omit(GSPC.new$GSPC.adj.std.annualised["1997/2022"]))
p.gspc + geom_line()+
geom_hline(yintercept = gspc.avg10yr, color = "red")+
geom_hline(yintercept = gspc.avg15yr, color = "blue")+
geom_hline(yintercept = gspc.avg20yr, color = "green")+
geom_hline(yintercept = gspc.avg25yr, color = "black")