# Install necessary packages if not already installed# install.packages("quantmod")# install.packages("RQuantLib")library(quantmod)# Load necessary packageslibrary(data.table)library(RQuantLib)# Fetch the Nifty 50 index datanifty_data <-getSymbols("^NSEI", src ="yahoo", from ="1980-01-01", auto.assign =TRUE)
Warning: ^NSEI contains missing values. Some functions will not work if objects
contain missing values in the middle of the series. Consider using na.omit(),
na.approx(), na.fill(), etc to remove or replace them.
# Convert the data to a data.tablenifty_data <-data.table(date =index(NSEI),open =as.numeric(Op(NSEI)),high =as.numeric(Hi(NSEI)),low =as.numeric(Lo(NSEI)),close =as.numeric(Cl(NSEI)),volume =as.numeric(Vo(NSEI)),adjusted =as.numeric(Ad(NSEI)))# Extract the last closing price directly from nifty_data# Get the latest closing priceclosing_price <- nifty_data[.N, close]closing_price
[1] 25966.4
# Select the relevant columns and calculate returnsdt <- nifty_data[, .(date, adjusted, returns = adjusted /shift(adjusted, 1) -1)]# Calculate mean return and annualized standard deviationresult <- dt[, .(annualized_mean_return =252*mean(returns, na.rm =TRUE) *100,annualized_sd =sqrt(252) *sd(returns, na.rm =TRUE) *100)]show(result)