I am new to R programming. When i try to plot the "optimize.portfolio" object from portfolioAnalytics package, Im getting the error below.
Error in applyFUN(R = R, weights = wts, FUN = risk.col
argument "arguments" is missing, with no default
In addition: Warning message:
In chart.Scatter.DE(object = DE, risk.col = risk.col, return.col = return.col,
mean or ES do not match extractStats output of $objective_measures slot
Below is my code.
library(PortfolioAnalytics)
library(DEoptim)
library(PerformanceAnalytics)
#get stock data
s = c("AMGN", "CSCO", "BA", "C")
start = "2017-01-01"
end = "2019-01-01"
getSymbols(s, from = start, to = end)
#create dateframe with close prices
p.price = NULL
for ( i in seq_along(s)){
j = s[i]
p.price = cbind(p.price, Cl(get(j)))
}
p.ret = na.omit(ROC(p.price))
colnames(p.ret) = gsub(".Close", "", colnames(p.ret))
funds = colnames(p.ret)
#create portfolio
ip = portfolio.spec(funds)
ip = add.constraint(ip, type ="weight_sum",
min_sum = 0.99, max_sum = 1.01)
ip = add.constraint(ip, type = "long_only")
ip = add.objective(ip, type = "return", name = "mean")
ip = add.objective(ip, type = "risk", name = "StdDev")
.storage = new.env()
opt = optimize.portfolio(p.ret, ip, optimize_method = "DEoptim",
search_size = 1000, trace = TRUE, traceDE = 5)
running the two below gives the mentioned error message
plot(opt)
chart.RiskReward(opt)
running the below, plots the weights without problem
chart.Weights(opt)
Thanks in advance!
The argument risk.col in chart.RiskReward() is set to "ES" by default, but you call function add.objective() by setting type = "risk", name = "StdDev".
try setting name = "ES" in add.objective(), or
setting risk.col = "StdDev" in chart.RiskReward()
Related
I am trying to run the Monocle3 function find_gene_modules() on a cell_data_set (cds) but am getting a variety of errors in this. I have not had any other issues before this. I am working with an imported Seurat object. My first error came back stating that the number of rows were not the same between my cds and cds#preprocess_aux$gene_loadings values. I took a look and it seems my gene loadings were a list under cds#preprocess_aux#listData$gene_loadings. I then ran the following code to make a dataframe version of the gene loadings:
test <- seurat#assays$RNA#counts#Dimnames[[1]]
test <- as.data.frame(test)
cds#preprocess_aux$gene_loadings <- test
rownames(cds#preprocess_aux$gene_loadings) <- cds#preprocess_aux$gene_loadings[,1]
Which created a cds#preprocess_aux$gene_loadings dataframe with the same number of rows and row names as my cds. This resolved my original error but now led to a new error being thrown from uwot as:
15:34:02 UMAP embedding parameters a = 1.577 b = 0.8951
Error in uwot(X = X, n_neighbors = n_neighbors, n_components = n_components, :
No numeric columns found
Running traceback() produces the following information.
> traceback()
4: stop("No numeric columns found")
3: uwot(X = X, n_neighbors = n_neighbors, n_components = n_components,
metric = metric, n_epochs = n_epochs, alpha = learning_rate,
scale = scale, init = init, init_sdev = init_sdev, spread = spread,
min_dist = min_dist, set_op_mix_ratio = set_op_mix_ratio,
local_connectivity = local_connectivity, bandwidth = bandwidth,
gamma = repulsion_strength, negative_sample_rate = negative_sample_rate,
a = a, b = b, nn_method = nn_method, n_trees = n_trees, search_k = search_k,
method = "umap", approx_pow = approx_pow, n_threads = n_threads,
n_sgd_threads = n_sgd_threads, grain_size = grain_size, y = y,
target_n_neighbors = target_n_neighbors, target_weight = target_weight,
target_metric = target_metric, pca = pca, pca_center = pca_center,
pca_method = pca_method, pcg_rand = pcg_rand, fast_sgd = fast_sgd,
ret_model = ret_model || "model" %in% ret_extra, ret_nn = ret_nn ||
"nn" %in% ret_extra, ret_fgraph = "fgraph" %in% ret_extra,
batch = batch, opt_args = opt_args, epoch_callback = epoch_callback,
tmpdir = tempdir(), verbose = verbose)
2: uwot::umap(as.matrix(preprocess_mat), n_components = max_components,
metric = umap.metric, min_dist = umap.min_dist, n_neighbors = umap.n_neighbors,
fast_sgd = umap.fast_sgd, n_threads = cores, verbose = verbose,
nn_method = umap.nn_method, ...)
1: find_gene_modules(cds[pr_deg_ids, ], reduction_method = "UMAP",
max_components = 2, umap.metric = "cosine", umap.min_dist = 0.1,
umap.n_neighbors = 15L, umap.fast_sgd = FALSE, umap.nn_method = "annoy",
k = 20, leiden_iter = 1, partition_qval = 0.05, weight = FALSE,
resolution = 0.001, random_seed = 0L, cores = 1, verbose = T)
I really have no idea what I am doing wrong or how to proceed from here. Does anyone with experience with uwot know where my error is coming from? Really appreciate the help!
I am trying to load a few data with a nested-loop using pageviews. You already helped me get this result:
library("pageviews")
lang = c("it.wikipedia")
bm = c("ECB","Christine Lagarde")
x <- list(
list(),
list(),
list(),
list(),
list()
) # store results
for (i in seq_along(lang)) {
for (j in seq_along(bm)) {
x[[i]][[j]] = article_pageviews(project = lang[i], article = bm[j], platform = "all", user_type = "user", start = "2015100100", end = today(), reformat = TRUE, granularity = "daily")
}
}
The last step I need to do, however, involves reading some article for which project doesn't exist. Find an example below:
lang = c("it.wikipedia")
bm = c("Philip Lane")
x = article_pageviews(project = lang, article = bm, platform = "all", user_type = "user", start = "2015100100", end = today(), reformat = TRUE, granularity = "daily")
# Error in FUN(X[[i]], ...) :
# The date(s) you used are valid, but we either do not have data for those date(s), or the project you asked for is not loaded yet. Please check https://wikimedia.org/api/rest_v1/?doc for more information.
I would like to add this to the loop. I tried a few solutions but I don't manage to make the loop skip over if there is an error. I post below one mistaken attempt:
lang = c("it.wikipedia")
bm = c("ECB", "Christine Lagarde", "Philip Lane")
for (i in seq_along(lang)) {
for (j in seq_along(bm)) {
skip_to_next <- FALSE
tryCatch(x[[i]][[j]] = article_pageviews(project = lang[i], article = bm[j], platform = "all", user_type = "user", start = "2015100100", end = today(), reformat = TRUE, granularity = "daily"), error = function(e) {skip_to_next <<- TRUE})
if(skip_to_next) { next }
}
}
Can anyone help me run the loop and skip whenever it meets an error?
Thanks a lot!
You can use tryCatch as :
library(pageviews)
library(purrr)
lang = c("it.wikipedia")
bm = c("ECB", "Christine Lagarde", "Philip Lane")
map_df(lang, function(x) map_df(bm, function(y)
tryCatch(article_pageviews(project = x, article = y, platform = "all", user_type = "user", start = "2015100100", end = today(), reformat = TRUE, granularity = "daily"),
error = function(e) {}))) -> result
I use the R package fPortfolio for portfolio optimization for a rolling portfolio (adaptive asset allocation). Therefore, I use the backtesting function.
I aim at constructing a portfolio for a set of assets for a predefined target return (and minimized risk) or for a predefined target risk and maximized returns.
Even allowing for short selling (as proposed in another post 5 years ago) seems not to work. Besides, I do not want to allow for short selling in my approach.
I cannot figure out why changing values for target return or target risk do not influence the solution at all.
Where do I go wrong?
require(quantmod)
require(fPortfolio)
require(PortfolioAnalytics)
tickers= c("SPY","TLT","GLD","VEIEX","QQQ","SHY")
getSymbols(tickers)
data.raw = as.timeSeries(na.omit(cbind(Ad(SPY),Ad(TLT),Ad(GLD),Ad(VEIEX),Ad(QQQ),Ad(SHY))))
data.arith = na.omit(Return.calculate(data.raw, method="simple"))
colnames(data.arith) = c("SPY","TLT","GLD","VEIEX","QQQ","SHY")
cvarSpec <- portfolioSpec(
model = list(
type = "CVAR",
optimize = "maxReturn",
estimator = "covEstimator",
tailRisk = list(),
params = list(alpha = 0.05, a = 1)),
portfolio = list(
weights = NULL,
targetReturn = NULL,
targetRisk = 0.08,
riskFreeRate = 0,
nFrontierPoints = 50,
status = 0),
optim = list(
solver = "solveRglpk.CVAR",
objective = NULL,
params = list(),
control = list(),
trace = FALSE))
backtest = portfolioBacktest()
setWindowsHorizon(backtest) = "12m"
assets <- SPY ~ SPY + TLT + GLD + VEIEX + QQQ + SHY
portConstraints ="LongOnly"
myPortfolio = portfolioBacktesting(
formula = assets,
data = data.arith,
spec = cvarSpec,
constraints = portConstraints,
backtest = backtest,
trace = TRUE)
setSmootherLambda(myPortfolio$backtest) <- "1m"
myPortfolioSmooth <- portfolioSmoothing(myPortfolio)
backtestPlot(myPortfolioSmooth, cex = 0.6, font = 1, family = "mono")
I am getting an error saying
Error in object#promisedInterfaces[[spec$oModule]] <- spec :
invalid subscript type 'S4'"
when I use the function "MiodinWorkflow" from miodin package.
I have used the following code:
mw <- MiodinWorkflow(name = "Lecture 4")
mw <- mw +
downloadRepositoryData(
name = "RNA downloader",
accession = "E-MTAB-7473",
repository = "ArrayExpress",
path = "data",
type = "processed")+
importProcessedData(
name = "RNA-seq importer",
experiment = "sequencing",
dataType = "rna",
studyName = "E-MTAB-7473",
assayName = "RNA-seq",
datasetName = "E-MTAB-7473",
contrastName = "Treatment") %>%
processSequencingData(
name = "RNA-seq processor",
contrastName = "Treatment",
filterLowCount = TRUE)
I'm trying to set up priors for my MLM using brms. I have ran my model with the priors I had set with no error messages and now would like to check them using pp_check. I get an the 'Error in sdata[[paste0("Y", usc(resp))]] : subscript out of bounds' error and couldn't find any tips as to why this is happening. Thanks!
Edit: I have checked the structure of my fit and only the init variables are 0, which I think should be the case since I set the initialisation parameter to 0? Otherwise there is nothing problematic as I can see.
I couldn't try anything since googling led to nothing.
library(brms)
df <- data.frame( subjno = as.factor(c('sub-01', 'sub-01','sub-01','sub-01','sub02','sub02','sub02','sub02')),
L1 = c(0.898922096, -0.673393065, -2.240150247,-0.932520537, -0.472701111, -0.188825324,0.808675919, 0.293666248),
L2 = c(0.64888, 2.0891, -0.655322708, 0.007098555, -0.648887797, -0.249716343, -0.698128026,0.119511014),
W1 = c(0.5,0.5,-0.5,-0.5,0.5,-0.5,0.5,-0.5), W2 = c(0.5,-0.5,0.5,-0.5,0.5,0.5,-0.5,-0.5),
t = as.factor(c(12,23,34,45,12,23,34,45)))
ff_s = brmsformula(cbind(L1,L2) ~ W1 * W2 * t +
(W1*W2* t|p|subjno))
get_prior(formula = ff_s, family = gaussian(),
data = df)
pp_s <- c(set_prior('normal(0,1)', class = "b"),
set_prior("normal(0,10)", class = "sd", resp = 'L1'),
set_prior("normal(0,10)", class = "sd", resp = 'L2'),
set_prior("normal(0,5)", class = "sigma",resp = 'L1'),
set_prior("normal(0,5)", class = "sigma",resp = 'L2'),
set_prior("normal(0,10)", class = "Intercept", resp = 'L1'),
set_prior("normal(0,10)", class = "Intercept", resp = 'L2'),
set_prior("lkj(3)", class = "cor"))
fit_s <- brm(formula = ff_s,
data = df, family = gaussian(),
prior = pp_s,
chains = 6, cores = 3,
iter = 2e3, warmup = 1e3,
init = 0,
sample_prior = "only")
pp_check(fit_s)
I found out that I was calling the function pp_check without specifying the level I am interested in, problem solved!