quantmod, not able to loop through chartSeries - dynamic-chart-series

install.packages("quantmod")
library(quantmod)
company_list <- c("AMD","AMZN","JPM","GOOG","COST")
for (i in 1:length(company_list)){
symbol <- company_list[i]
data_in <- as.name(symbol)
getSymbols(symbol)
chartSeries(data_in,subset="last 9 months")
addSMA(10,col="blue")
addSMA(20,col="red")
}
Error in try.xts(x, error = "chartSeries requires an xtsible object") :
chartSeries requires an xtsible object
somehow this code stuck at chartSeries(data_in,subset="last 9 months")

you have to give the xts object to chartSeries, with get(symbol):
company_list <- c("AMD","AMZN")
for (i in 1:length(company_list)){
symbol <- company_list[i]
getSymbols(symbol)
chartSeries(get(symbol),subset="last 9 months")
addSMA(10,col="blue")
addSMA(20,col="red")
}

Related

Portfolio Optimization Using Quadprog Gives the Same Result for Every time even after changing variables

I have a task to construct the efficient frontier using 25 portfolios (monthly data). I tired writing a quadprog code for calculating minimum variance portfolio weights for a given expected rate of return. However, regardless of the expected return, the solver values give me the same set weights and variance, which the global minimum variance portfolio. I found the answer using an analytical solution. Attached are the codes:
basedf <- read.csv("test.csv", header = TRUE, sep = ",")
data <- basedf[,2:26]
ret <- as.data.frame(colMeans(data))
variance <- diag(var(data))
covmat <-as.matrix(var(data))
###minimum variance portfolio calculation
Q <- 2*cov(data)
A <- rbind(rep(1,25))
a <- 1
result <- solve.QP(Dmat = Q,
dvec = rep(0,25),
Amat = t(A),
bvec = a,
meq = 1)
w <-result$solution
w
var <- result$value
var
sum(w)
this is another set of codes giving the me same value::
mvp <- function(e,ep){
Dmat <- 2*cov(e)
dvec <- rep(0, ncol(e))
Amat <- cbind(rep(1, ncol(e)), colMeans(e))
bvec <- c(1, ep)
result <- solve.QP(Dmat = Dmat, dvec = dvec, Amat = Amat, bvec = bvec, meq=1)
wp <- result$solution
varP <- result$value
ret_values <- list(wp, varP)
names(ret_values) <- c("wp", "VarP")
return(ret_values)
}
z <- mvp(data, -.005)
z$wp
sum(z$wp)
z$VarP
ef <- function(e, min_e, max_e){
list_e <- seq(min_e,max_e, length=50)
loop <- sapply(list_e, function(x) mvp(e, x)$VarP)
effF <- as.data.frame(cbind(list_e,loop))
minvar <- min(effF$loop)
L <- effF$loop==minvar
minret <- effF[L,]$list_e
minpoint <- as.data.frame(cbind(minret,minvar))
minvarwp <- mvp(e, min_e)$wp
rlist <- list(effF, minpoint, minvarwp)
names(rlist) <- c( "eFF", "minPoint", "wp")
return(rlist)
}
in the efficient frontier, all the 50 portfolios have same level of variance. can anyone tell me whats wrong with solver equation??? thanks.
I tried quadprog but couldnt solve it.

I'm trying to forecast an ETS model using data from tsibbledata in R but I'm getting the error message seen at the bottom of the code below

ItalyExp <- global_economy %>%
filter(Country == "Italy")
ItalyExp$Exports <- as.numeric(as.character(ItalyExp$Exports))
ItalyExp %>% autoplot(Exports) + labs(title = "Italian Exports")
etsANNit <- ItalyExp %>%
model(ETS(Exports ~ error("A") + trend("N") + season("N")))
etsANNit
fc <- etsANNit %>%
forecast(h = 10)
This gives the error message:
Warning messages:
1: In mean.default(x, na.rm = TRUE) :
argument is not numeric or logical: returning NA
2: In Ops.factor(left, right) : ā€˜-ā€™ not meaningful for factors

How to make a decoder with an optional element?

Iā€™m stuck with a decoder that should decode an array [ 9.34958, 48.87733, 1000 ] to a Point, where index 2 (elevation) is optional.
type alias Point =
{ elev : Maybe Float
, at : Float
, lng : Float
}
Therefore I created following decoder:
fromArrayDecoder : Decoder Point
fromArrayDecoder =
map3 Point
(index 2 Decode.float |> Decode.maybe)
(index 1 Decode.float)
(index 0 Decode.float)
My problem now is, that this decoder succeeds when index 2 is missing or is of any type like string etc. But I want it only to succeed if elev is missing, not if it has the wrong type. Is there any way of accomplishing this?
If by "missing" you mean the value can be null, you can just use nullable instead of maybe:
fromArrayDecoder : Decoder Point
fromArrayDecoder =
map3 Point
(index 2 Decode.float |> Decode.nullable)
(index 1 Decode.float)
(index 0 Decode.float)
If it's either a 3-element array or a two-element array you can use oneOf to try several decoders in order:
fromTwoArrayDecoder : Decoder Point
fromTwoArrayDecoder =
map3 (Point Nothing)
(index 1 Decode.float)
(index 0 Decode.float)
fromThreeArrayDecoder : Decoder Point
fromThreeArrayDecoder =
map3 Point
(index 2 Decode.float |> Decode.map Just)
(index 1 Decode.float)
(index 0 Decode.float)
fromArrayDecoder : Decoder Point
fromArrayDecoder =
oneOf
[ fromThreeArrayDecoder
, fromTwoArrayDecoder
]
Just remember to try the 3-element decoder first, as the 2-element decoder will succeed on a 3-element array as well, but the opposite does not.
I agree that the fact Json.Decode.maybe giving you Nothing on a wrong value rather than just a missing one is surprising.
elm-json-decode-pipeline can work in the way you want without getting too verbose.
> d = Decode.succeed Point
| |> optional "2" (Decode.float |> Decode.map Just) Nothing
| |> required "1" Decode.float
| |> required "0" Decode.float
|
> "[1, 2, \"3\"]" |> Decode.decodeString d
Err (Failure ("Json.Decode.oneOf failed in the following 2 ways:\n\n\n\n(1) Problem with the given value:\n \n \"3\"\n \n Expecting a FLOAT\n\n\n\n(2) Problem with the given value:\n \n \"3\"\n \n Expecting null") <internals>)
: Result Decode.Error Point
> "[1, 2, 3]" |> Decode.decodeString d
Ok { at = 2, elev = Just 3, lng = 1 }
: Result Decode.Error Point
> "[1, 2]" |> Decode.decodeString d
Ok { at = 2, elev = Nothing, lng = 1 }
: Result Decode.Error Point
(You can see from the error that under the hood it is using oneOf like in glennsl's answer.)
The only potentially surprising thing here is that you need to pass strings rather than int indexes, as there isn't a specific version for lists but you can access list indexes as though they are field names. This does mean that this version is subtly different in that it will not throw an error if you can an object with number field names rather than an array, but I can't imagine that really being an issue. The more real issue is it could make your error messages less accurate:
> "[0]" |> Decode.decodeString (Decode.field "0" Decode.int)
Ok 0 : Result Decode.Error Int
> "[]" |> Decode.decodeString (Decode.field "0" Decode.int)
Err (Failure ("Expecting an OBJECT with a field named `0`") <internals>)
: Result Decode.Error Int
> "[]" |> Decode.decodeString (Decode.index 0 Decode.int)
Err (Failure ("Expecting a LONGER array. Need index 0 but only see 0 entries") <internals>)
Note that you do still have to to avoid using Json.Decode.maybe. It may be tempting to write optional "2" (Decode.maybe Decode.float) Nothing which will result in the same behaviour as you originally got.

Error in sum(x[i:(i + 50)], na.rm = TRUE) : invalid 'type' (character) of argument

I am new in R , and I am trying to do a script to calculate the sliding mean of some data.
This is how my data looks like:
Timestamp Accelerometer X Accelerometer Y Accelerometer Z
1 121219.757080078 -5.66180946541818 8.85684119781125 1.65407075345669
2 121239.288330078 -7.38255951126451 9.4117333531527 1.44410517346543
it has around 6000 rows, and I need to calculate the mean of Accelerometer x, Accelerometer Y, and Accelerometer Z each fifty rows. So from the data of row 1 to 50 I must get the mean of the 3 variables, then from rows 51 to 100, and so on until row 6000.
I tried with (for the first variable):
library(reshape2)
library(reshape)
x <- deadlift$`Accelerometer X`
win.size <- 50
slide <- 50
results <- data.frame(index=numeric(),win.mean=numeric())
i<-1
j<-1
while (i<length(x)) {
win.mean<-sum(x[i:(i+50)],na.rm = TRUE)/win.size
results[j,]<-c(i,win.mean)
i<-i+slide
j<-j+1
}
but I get this message:
Error in sum(x[i:(i + 50)], na.rm = TRUE) :
invalid 'type' (character) of argument
any help?
Thank you.
Problem solved.
the problem was that the object x was created as character. I converted it to numeric with as.numeric.
It worked.
Regards,

Reactive objects and rwunderground functions in R

I am using Shiny R, but I do not know to solve a problem in server. The "climate2" and "weather10" objects were not found. Likely, the "latlong" and "comp" objects show problems, but I do not know. The "latlong" argument of "forecast10day" function does not work with my "latlong" object and the "semi_join" function does not work with my "comp" object. I am copying only a part of the code because it is very long.
Many thanks!
Global R.
# Climate
climate <- cbind(tmin,tmax[,-c(1:3)],rhpm[,-c(1:3)],rham[,-c(1:3)])
names(climate) <- c("Long","Lat","Month","Tmin","Tmax","RHmin","RHmax")
head(climate,2)
Server:
latlong <- reactive({
latlong <- as.character(c(input$Lat,input$Long))
weather.10 <- forecast10day(set_location(lat_long = paste(latlong,collapse = ",")))
names(weather.10)[names(weather.10) == "temp_high"] <- "Tmax"
names(weather.10)[names(weather.10) == "temp_low"] <- "Tmin"
weather.10$Tmax <- fahrenheit.to.celsius(weather.10$Tmax, round = 0)
weather.10$Tmin <- fahrenheit.to.celsius(weather.10$Tmin, round = 0)
})
#Outputs
output$text0 <- renderText({
if(input$Irrigation =="No")
if(round(mean(min(weather.10$Tmin))) > 17 && round(mean(max(weather.10$Tmax))) < 35 && round(mean(min(weather.10$ave_humidity))) > 34 && round(mean(max(weather.10$ave_humidity))) < 87)
{
paste("The combination Biological and Chemical control is recomended in Drought or Rainy period.")
}else{
paste("Biological or chemical control or both may be inefficient and there are low risk of epidemics")
}
})
comp <- reactive ({
#Selecting options of user
comp <- data.frame(input$Long, input$Lat,input$Month)
climate <- semi_join(climate, comp, by=c("Long","Lat","Month"))
climate2 <- data.frame(unique(climate$Long),unique(climate$Lat),unique(climate$Month),round(mean(climate$Tmin)),
round(mean(climate$Tmax)),round(mean(climate$RHmin)),
round(mean(climate$RHmax)))
names(climate2) <- c("Long", "Lat","Mont","Tmin","Tmax","RHmin","RHmax")
})
output$text1 <- renderText({
if(input$Irrigation =="50-60%")
if(climate2$Tmax > 17 && climate2$Tmin < 35 && climate2$RHmin > 34 && climate2$RHmax < 87)
{
paste("The combination Biological and Chemical control is recomended.")
}else{
paste("Biological or chemical control or both may be inefficient. You can see more information in FORECASTING.")
}
})
This is my UI.
ui <- fluidPage(theme = shinytheme("superhero"),
h3("Information system to control Dry Root Rot in Common Beans"),
sidebarLayout(sidebarPanel(
numericInput("Long", label = h3("Longitude:"), value = -49),
numericInput("Lat", label = h3("Latitude:"), value = -17),
actionButton("recalc", "Show point"),
selectInput(inputId = "Irrigation",label = "Irrigation (Soil Available Water)",
choices = c("No","50-60%","80-90%","110-120%","140-150%"),
selected = "80-90%"
),
selectInput(inputId = "Month", label = "Current Month", choices = c("Jan","Feb","March","April","May","June","July",
"Aug","Sep","Oct","Nov","Dec")),