Home > database >  Calculate the Standard Deviation of the log changes in hourly prices for each simulation in R Studio
Calculate the Standard Deviation of the log changes in hourly prices for each simulation in R Studio

Time:10-01

I'm new to R language, using price data table, I want to calculate the standard deviation of the log changes in hourly prices of each simulation ("sim"). Store in a 5x1 vector. I know that log(x) values need to convert to a numeric form before calculating std.

prices <- matrix(sample(40:100,25,replace=T),ncol=5,byrow=T)
colnames(prices) <- c("P1","P2","P3","P4","P5")
cbind(sim=1:5,prices)

I have tried the following code which giving me an error:

for (i in 1:5){
    empty_vec = c()
    for (j in 1:5){
     logchange = c(empty_vec,log[prices[j 1]]-log[prices[j]])
    }
     std = sd(as.numeric(logchanges))
}

Error in log[prices[j 1]]: object of type 'special' is not subsettable

CodePudding user response:

Here is a way. Define a function log_ret to compute the log returns and use apply loops to get the changes and the standard errors by row.
Note that the log changes matrix only has 4 columns, the first empty column (c() in your code) is not needed.

log_ret <- function(x, na.rm = FALSE) diff(log(x), na.rm = na.rm)

logchange <- t(apply(prices, 1, log_ret, na.rm = TRUE))
logchange
#              P2          P3         P4          P5
#[1,]  0.51516403  0.09884583 0.13205972 -0.21800215
#[2,]  0.57903387 -0.70419702 0.53714293  0.24116206
#[3,]  0.09884583 -0.65846162 0.67015766 -0.09763847
#[4,] -0.25489225 -0.19530875 0.56798404  0.09531018
#[5,]  0.54191621  0.01015237 0.01005034 -0.86750057


sdt <- apply(logchange, 1, sd, na.rm = TRUE)
sdt
#[1] 0.3002307 0.5975524 0.5483141 0.3757008 0.5839863

CodePudding user response:

You'd define empty_vec outside the loop.

empty_vec <- c()

for (i in 1:5){
    empty_vec <- c(empty_vec, sd(diff(log(prices[i, ]))))
}

empty_vec
[1] 0.40748900 0.08224775 0.38648016 0.49286912 0.55398038
  •  Tags:  
  • r
  • Related