xtsible object, looping in quantmod - r

I would like to loop through a list of stock symbols and print them with chartSeries. It would be easier than always changing the argument. Unfortunatly I always get an error, when I want to loop or subset:
Error in try.xts(x, error = "chartSeries requires an xtsible object"):
chartSeries requires an xtsible object
Here the code that produces the error:
library(quantmod)
stocks <- c("FIS", "AXP", "AVB")
symbols <- (getSymbols(stocks, src='yahoo'))
for (i in symbols){
chartSeries(i, theme="white",
TA="addVo();addBBands();addCCI();addSMA(20, col='blue');
addSMA(5, col='red');addSMA(50, col='black')", subset='last 30 days')
}
or only:
chartSeries(symbols[1], theme="white",
TA="addVo();addBBands();addCCI();addSMA(20, col='blue');
addSMA(5, col='red');addSMA(50, col='black')", subset='last 30 days')

symbols is a character vector. It's not a list of xts objects. Calling chartSeries on a character vector causes the error.
R> chartSeries("OOPS")
Error in try.xts(x, error = "chartSeries requires an xtsible object") :
chartSeries requires an xtsible object
One solution is to put all the downloaded data into one environment, then call chartSeries on every object in the environment.
library(quantmod)
stocks <- c("FIS", "AXP", "AVB")
stockEnv <- new.env()
symbols <- getSymbols(stocks, src='yahoo', env=stockEnv)
for (stock in ls(stockEnv)){
chartSeries(stockEnv[[stock]], theme="white", name=stock,
TA="addVo();addBBands();addCCI();addSMA(20, col='blue');
addSMA(5, col='red');addSMA(50, col='black')", subset='last 30 days')
}

Related

Error in is.single.string(object) : argument "object" is missing, with no default

I want to parse the AAChange.refGene column and then use biomaRt R package to extract information. My code is raising Error in is.single.string(object) : argument "object" is missing, with no default even though the getSequence function is meant to accept multiple arguments.
library(tidyr)
variant_calls = read.delim("variant_calls.txt")
info = tidyr::separate(variant_calls["AAChange.refGene"], AAChange.refGene, c("Refseq ID", "cDNA level change", "Protein level change"), ":")
df = cbind(variant_calls["Gene.refGene"],info)
library(biomaRt)
ensembl <- useMart(biomart="ENSEMBL_MART_ENSEMBL", dataset="hsapiens_gene_ensembl", host="https://grch37.ensembl.org", path="/biomart/martservice")
pep <- vector()
for(i in 1:length(df$`Refseq ID`)){
temp <- getSequence(id=df$`Refseq ID`[i],type='refseq_mrna',seqType='peptide', mart=ensembl)
temp <- sapply(temp$peptide, nchar)
temp <- sort(temp, decreasing = TRUE)
temp <- names(temp[1])
pep[i] <- temp
}
df$Sequence <- pep
Traceback:
Error in is.single.string(object) :
argument "object" is missing, with no default
I got the same error and found out (using ?getSequence) that it was a conflict between packages (classic R), specifically biomart and seqinr which is used to handle fasta format thus probably used together often.
My solution consisted in calling the function like this:
biomaRt::getSequence()

Extraction of specific result in R outputs

I want to extract the values of "b1p" and "b2p" from the mardia's command and want to save it in bskew.
For this i have used the "psych" package R version is 4.0.3. I have tried several commands for extraction but failed.
bskew <- mardia$b1p
bskew <- mardia[b1p
bskew <- mardia[[b1p
for this i got the error "object of type 'closure' is not subsettable"
By using names() i got only names and by using class() i got "psych", "mardia".
By using summary() i got the message "Warning message:
In summary.psych(mardia(x)) :
I am sorry, I do not have a summary function for this object" and then i used mna$coefficients[[]] command
and i got the message "NULL".
I saved my mardia command in mna.
Minimum Working Example is:
n0 <- 5
p0 <- 2
m0 <- matrix(rep(0,p0),ncol=p0)
s0 <- diag(1,p0)
x <- rmvnorm(5,mean=m0, sigma=s0)
mardia$"b1p"
bskew <- mardia["b1p"]
bskew <- mardia[["b1p"]]
bkurt <- mardia[["b2p"]]
bskew <- mardia$b1p$
mna<-mardia(x)
class(mna)
names(mna)
summary(mardia(x))
summary(mna)
sk1 <- mna$coefficients[[3]]
mna$coefficients
the error is because you're trying to subset a function mardia which always throws the error you have, also you should subset the mna object instead of subsetting the actual function.
> mna$b1p
[1] 1.95888
> mna["b1p"]
$b1p
[1] 1.95888
> mna[["b1p"]]
[1] 1.95888
> mardia(x)$b1p
[1] 1.95888
> mardia$b1p
Error in mardia$b1p : object of type 'closure' is not subsettable
> mardia<-mardia(x)
> mardia$b1p
[1] 1.95888

Having trouble fixing error using quantmod package in R : Error in inherits(x, "xts"): object 'M' not found calls

below is my code. What I am trying to do is download multiple symbols of stocks and plot charts, but I am getting this error:
Error in inherits(x, "xts"): object 'M' not found calls: ...
eval-> chartSeries -> try.xts ->is.xts -> inherits
library(quantmod)
stocks <- c("INFY.NS","HINDALCO.NS","TCS.NS","TATASTEEL.NS","NESTLEIND.NS",
"TECHM.NS","HCLTECH.NS","HDFCBANK.NS","JETAIRWAYS.NS","BLUEDART.NS",
"AUROPHARMA.NS","APOLLOHOSP.NS", "IOC.NS", "HINDPETRO.NS","BHEL.NS",
"NTPC.NS", "HINDZINC.NS", "M&M.NS", "RELIANCE.NS","ONGC.NS", "ORIENTBANK.NS",
"MARUTI.NS", "ASHOKLEY.NS", "ASIANPAINT.NS", "DABUR.NS", "DRREDDY.NS",
"BHARTIARTL.NS", "BATAINDIA.NS", "LTI.NS")
getSymbols(stocks,from="2017-01-01")
chartSeries(INFY.NS)
chartSeries(HINDALCO.NS)
chartSeries(TCS.NS)
chartSeries(TATASTEEL.NS)
chartSeries(NESTLEIND.NS)
chartSeries(TECHM.NS)
chartSeries(HCLTECH.NS)
chartSeries(HDFCBANK.NS)
chartSeries(JETAIRWAYS.NS)
chartSeries(BLUEDART.NS)
chartSeries(AUROPHARMA.NS)
chartSeries(APOLLOHOSP.NS)
chartSeries(IOC.NS)
chartSeries(HINDPETRO.NS)
chartSeries(BHEL.NS)
chartSeries(NTPC.NS)
chartSeries(HINDZINC.NS)
chartSeries(M&M.NS)
chartSeries(RELIANCE.NS)
chartSeries(ONGC.NS)
chartSeries(ORIENTBANK.NS)
chartSeries(MARUTI.NS)
chartSeries(ASHOKLEY.NS)
chartSeries(ASIANPAINT.NS)
chartSeries(DABUR.NS)
chartSeries(DRREDDY.NS)
chartSeries(BHARTIARTL.NS)
chartSeries(BATAINDIA.NS)
chartSeries(LTI.NS)
The problem is that M&M.NS is not a syntactically valid R name (the & has special meaning).
library(quantmod)
getSymbols("M&M.NS")
chartSeries(M&M.NS) # error
chartSeries(`M&M.NS`) # use backticks for names that aren't syntactically valid
Or you can use setSymbolLookup() to map the symbol to a syntactically valid name. Then you can use the syntactically valid ticker in your getSymbols() and chartSeries() calls.
setSymbolLookup(M.AMP.M.NS = list(name = "M&M.NS"))
getSymbols("M.AMP.M.NS")
chartSeries(M.AMP.M.NS)

Custom indicator function for quantstrat

I'm having trouble writing a custom indicator function for use with quanstrat::add.indicator
Error:
Error in inherits(x, "xts") : object 'price' not found
My code:
library(quantstrat)
symbols<-getSymbols("USD/EUR",src="oanda")
strat<-acct<-portfolio<-"tempTest"
initEq<-1000
initDate <- '2009-12-31'
currency("USD")
exchange_rate(symbols, currency="USD")
rm.strat(strat) # remove portfolio, account, orderbook if re-run
initPortf(name=portfolio, symbols, initDate=Sys.Date())
initAcct(name=acct, portfolios=portfolio,initDate=Sys.Date(), initEq=initEq)
initOrders(portfolio=portfolio, initDate=Sys.Date())
strategy(strat, store=TRUE)
colnames(USDEUR)<-"Close"
#################################################################################################
RSI.lagged<-function(lag=1,n=2,...){
RSI <- RSI(price)
RSI <- lag(RSI, lag)
out <- RSI$rsi
colnames(out) <- "rsi"
return(out)
}
########RSI indicator
####THIS IS LAGGED TO PREVENT FOREKNOWLEDGE
add.indicator(strat, name="RSI.lagged", arguments=list(price = quote(Cl(mktdata)), n=2), label="rsiIndLagged")
test <- applyIndicators(strat, mktdata=USDEUR)
After adding the parameter price to the RSI.lagged function eg RSI.lagged<-function(lag=1,n=2,price,...) I get the error:
Error in `colnames<-`(`*tmp*`, value = "rsi") : attempt to set 'colnames' on an object with less than two dimensions
You were trying to access the name of a column that does not exist. Try this instead to get your indicator to work:
RSI.lagged<-function(price, lag=1,n=2,...){
# Stick in a browser to see your problem more clearly:
# browser()
rsi <- RSI(price)
rsi <- lag(rsi, lag)
# This column name does not exist: "rsi". The name of the column gets the default "EMA"
# tail(rsi)
# EMA
# 2017-11-04 63.48806
# 2017-11-05 66.43532
# 2017-11-06 64.41188
# 2017-11-07 66.02659
# 2017-11-08 67.96394
# 2017-11-09 66.08134
colnames(rsi) <- "rsi"
return(out)
}
(Aside, also strongly suggest you do not try using Oanda data to backtest with,as the prices aren't "real"; they are a weighted average price for each day. See: Exact time stamp on quantmod currency (FX) data)

Error when plotting HoltWinters graph

The following R code is giving me an error when trying to plot the HoltWinters graph as done here:
# init X
X11()
# get data
mydata = read.csv("lookup.csv", header=TRUE, stringsAsFactors=FALSE)
# data post-proc
mydata = as.data.frame(mydata)
mydata$Time = as.POSIXlt(mydata$Time, format='%d.%m.%Y %H:%M:%S')
# create time series - hourly data -> 8765 hours/year
dataTimeSeries <- ts(mydata$Close, frequency=8765)
dataForecasts = HoltWinters(dataTimeSeries, beta=FALSE, gamma=FALSE)
# output
plot.ts(dataForecasts)
message("Press Return To Continue")
invisible(readLines("stdin", n=1))
The error I'm getting is:
$ Rscript simple_forecast.R
Error in xy.coords(x, NULL, log = log) :
(list) object cannot be coerced to type 'double'
Calls: plot.ts -> plotts -> xy.coords
Execution halted
I'm quite perplexed, since print(dataForecasts) prints the correct data. I can also plot dataTimeSeries without a problem.
lookup.csv (pastebin)
Generally one should rely upon R to do the dispatch of class-dependent functions, and do notice that the example you cited at Avril Coghlan's page only used plot, not plot.ts.
(m <- HoltWinters(co2))
plot.ts(m)
Error in xy.coords(x, NULL, log = log) :
(list) object cannot be coerced to type 'double'
plot(m) # success

Resources