stddev pct contrib / rollapply / performanceanalytics / R / subscript out of bounds - r

I am trying to construct rolling risk contributions by each security using the PerformanceAnalytics package. Once I can get past this error I would like to plot the results over time. I keep receiving the error that the subscript is out of bounds and i'm not sure where to start in terms of resolving it. This is the error specifically:
Error in `[.xts`(x, i, which.i = TRUE) : subscript out of bounds
Not very experienced with R. Thank you for any guidance! Here is the code.
library(PerformanceAnalytics)
symbols <- c("SPY","EEM","BND","BIL")
prices <-
getSymbols(symbols, src = 'yahoo', from = "2016-01-01",
auto.assign = TRUE, warnings = FALSE) %>%
map(~Cl(get(.))) %>%
reduce(merge) %>%
`colnames<-`(symbols)
portfolioComponentReturns <- na.omit(Return.calculate(prices, method = "log"))
w = c(.25,.25,.25,.25)
rollingvolpct <- na.omit(rollapply(portfolioComponentReturns,
width=252,
FUN = function(Z)
{
t = StdDev(portfolioComponentReturns,weights = w, portfolio_method = "components", data = as.data.frame(Z), na.rm=T);
return(t$pct_contrib)
},
by.column=FALSE, align="right"))

Related

Error in svd(X, nu = 0L) : infinite or missing values in 'x'

I am currentry working with some kind of data analysis by R studio.
My project code is something like this:
library(Momocs)
library(geomorph)
CharredCoords <- list.files("C:\\Users\\grain_coords_mod", full.names = TRUE)
CharredFrame <- read.csv("C:\\Users\\data_matrix_new_mod.csv", header = TRUE)
CharredTxt <- import_txt(CharredCoords, fileEncoding="UTF-8-BOM")
CharredOut <- Out(CharredTxt, fac=CharredFrame)
CharredOut1 <-coo_scale (CharredOut)
CharredOut.l <- filter(CharredOut1, View == "l")
CharredOut.d <- filter(CharredOut1, View == "d")
CharredOut.l.efour <- efourier(CharredOut.l, nb.h=8, norm = FALSE, start = TRUE)
CharredOut.d.efour <- efourier(CharredOut.d, nb.h=8, norm = FALSE, start = TRUE)
Till its okay... Then after when I execute the following line, error occurs
CharredOut.l %>% chop(~View) %>% lapply(efourier,nb.h=8, norm = FALSE, start = FALSE) %>% combine %>% LDA ('G_Variety', scale=FALSE, center= TRUE)
Output: Error in svd(X, nu = 0L) : infinite or missing values in 'x'
In addition: Warning message:
In lda.default(x, grouping, ...) : variables are collinear
Looking for some suggestion like what I suppose to do or check to solve that isuue.
Thanks in advance.`enter image description here
Code should be render for further ploting procedure.

How does the "LoadBeatRR" function from the RHRV package work?

I was trying to analyze my RR intervals using the RHRV package.
I have used:
hrv.data = CreateHRVData()
hrv.data = SetVerbose(hrv.data, TRUE)
hrv.data = LoadBeatRR(hrv.data, "dataset.txt", RecordPath = "#the path of dataset.txt here", datetime = "1/1/1900 0:0:0", verbose = NULL)
Unfortunately, when I do this I get the warning message :
"NAs introduced by coercion".
And all my following analyses do not work.
I do not see what the problem could be.
You should make sure the time, hr and rr variables are named as such: "Time", "niHR", and "RR" respectively.
A work-around would to just to manually create the beat object.
hrv.data$Beat <- readr::read_delim("txt file") %>%
dplyr::rename("Time" = time, "niHR" = hr, "RR" = rr) %>%
dplyr::select(Time, niHR, RR)
hrv.data <- RHRV::BuildNIHR(hrv.data)

Please select a longer horizon when the forecasts are first computed in forecast package in r

When I run the following code, I do NOT get this error:
## https://www.dataiku.com/learn/guide/code/r/time_series.html
library(readxl)
library(forecast)
library(dplyr)
library(prophet)
library(rstan)
library(Hmisc)
library(caret)
data<-read_excel("Time Series/Items.xlsx", col_types = c("text", "numeric"))
Nper=0.75
stmodels=c("meanf","naive","snaive","rwf","croston","stlf","ses","holt","hw","splinef","thetaf","ets","auto.arima","tbats","prophet")
gkuniforecast = function(data, Np, Ncolumn, tsfreq, model) {
## Preparation
N = ceiling(Np*nrow(data))
## Models
if (model=="prophet"){
df=data
names(df)=c("ds","y")
df$ds=as.Date(paste(df$ds,"-01",sep=""), "%Y-%b-%d")
train.df = df[1:N,]
na.df=data.frame(ds=rep(NA, N),y=rep(NA, N))
test.df <- rbind(na.df, df[(N+1):nrow(data),])
m <- prophet(train.df)
future <- make_future_dataframe(m, periods = nrow(data)-N, freq = 'month')
pro_forecast <- predict(m, future)
plot(m, pro_forecast)
##prophet_plot_components(m, forecast)
acc=matrix(rep(NA, 16),nrow=2,ncol=8,dimnames=list(c("Training set", "Test set"),c("ME","RMSE","MAE","MPE","MAPE","MASE","ACF1","Theil's U")))
acc["Test set","RMSE"]=sqrt(mean((pro_forecast$yhat - test.df)^2, na.rm = TRUE))
}else{
x=pull(data,Ncolumn)
train.x = ts(x[1:N], frequency=tsfreq)
test.x <- ts(c(rep(NA, N), x[(N+1):NROW(x)]), frequency=tsfreq)
str1=paste0("m_",model," = ",model,"(train.x)")
if (Np==1) {str2=paste0("f_",model," = forecast(m_",model,", h=NROW(x)")
} else {str2=paste0("f_",model," = forecast(m_",model,", h=NROW(x)-N)")}
str3=paste0("plot(f_",model,")")
str4="lines(test.x)"
str5=paste0("acc=accuracy(f_",model,",test.x)")
str=paste0(str1,";",str2,";",str3,";",str4,";",str5)
eval(parse(text=str))
}
return(acc)
}
acc = lapply(stmodels, gkuniforecast, data=data, Np=Nper, Ncolumn=2,tsfreq=12)
But when I run this code, I do:
##Forecast data prep
tsfreq=5
x=pull(data,1)
train.x = ts(x[1:N], frequency=tsfreq)
test.x <- ts(c(rep(NA, N), x[(N+1):NROW(x)]), frequency=tsfreq)
stmodels=c("meanf","naive","snaive","rwf","croston","stlf","ses","holt","hw"##,"splinef"
,"thetaf","ets","auto.arima","tbats")
for (i in 1:length(stmodels)){
str1=paste0("m_",stmodels[i]," = ",stmodels[i],"(train.x)")
str2=paste0("f_",stmodels[i]," = forecast(m_",stmodels[i],", h=NROW(x)-N)")
str3=paste0("plot(f_",stmodels[i],")")
str4="lines(test.x)"
str5=paste0('acc[["',stmodels[i],'"]]=accuracy(f_',stmodels[i],',test.x)')
str=paste0(str1,";",str2,";",str3,";",str4,";",str5)
eval(parse(text=str))
}
There seems to be a problem with 'hw' (splinef is commented out, because it gives me another error), but I do not understand why in the first dataset, I get no errors and I do with the second dataset. What is also different is the frequency.
Again the error is:
Please select a longer horizon when the forecasts are first computed
You are mixing functions that create forecasts directly (like meanf()) with functions that generate models (like ets()). For functions that generate forecasts directly, you need to specify the forecast horizon when you call the function. See https://otexts.org/fpp2/the-forecast-package-in-r.html for a list of functions that produce forecasts directly.

'Unused Arguments' error in mediate function in R

I'm trying to run a mediation analysis in R using the mediation package, but I keep getting an error of the type:
Error in mediate(model.m, model.y, sims = 1000, boot = TRUE, treat = "Treat", :
unused arguments (sims = 1000, boot = TRUE, treat = "Treat", mediator = "Med")
The code I'm running is:
model.y <- lm(Perf~Treat*InteractionVar + Med, s)
model.m <- lm(Med~Treat, s)
out.1 <- mediate(model.m, model.y, sims = 1000, boot = TRUE, treat="Treat", mediator = "Med")
I get the same error even if I remove the InteractionVar from the formula too. Any ideas what I'm doing wrong? Thanks!

Error when doing power spectrum analysis in R

I am trying to do a spectral density analysis with ozone data but have run into the error:
Error in ts(tser, frequency = x.fsamp, start = x.start) : 'ts'
object must have one or more observations
I am not sure what the problem is because it sounds like it is having a problem with the number of entries in the file but the file is certainly not empty. What could be causing this problem? The code is as follows:
library(openair)
library(psd)
filedir <-"C:/Users/dfmcg/Documents/Thesis files/ALL_GPMP_O3_Met"
myfiles <-c(list.files(path = filedir))
paste(filedir,myfiles,sep = '/')
npsfiles<-c(paste(filedir,myfiles,sep = '/'))
for (i in npsfiles[1:3]){
x <- substr(i,55,61)
y<-paste(paste('C:/Users/dfmcg/Documents/Thesis files/nps images',x,sep='/'), '.png', sep='')
png(filename = y)
timeozone<-import(i,date="DATE",date.format = "%m/%d/%Y %H",header=TRUE,na.strings="-999")
psdcore(timeozone, ntaper = ,
na.action = "-999", plot = TRUE,
refresh = TRUE)
dev()
}

Resources