There is some missing things in chart - r

I made following function for convenient usage for myself, but line "MeanData60" never goes out on result chart.
ShowStock <- function(Name)
{
Data <- getSymbols(Name, auto.assign=FALSE);
chartSeries( Data, name=Name, subset="last 1 year", TA=c(addMACD()) )
MeanData20 <- runMean(Data[,4], n=20)
addTA(MeanData20, on=1, col="brown1")
MeanData60 <- runMean(Data[,4], n=60)
addTA(MeanData60, on=1, col="cadetblue1")
}
ShowStock("YHOO")
I don't get it.
Please help to figure out where the problem is.

Related

Recursive / Expanding Window forecasts

I am having a small issue with my Rstudio code. I will try to replicate my code but unfortunately there is no easy data for me to show. This is about the package forecast. What I am looking for is somehwat simpler for what is in the manual. But unfortunately, I am not able to work round it.
so the issue is with an expanding window forecast. So I have a dependent variable Y and 3 regressors (X). I am trying to build a recursive one steap ahead forecast for each X.
Here is my code.
library(forecast)
library(zoo)
library(timeDate)
library(xts)
## Load data
data = Dataset[,2:ncol(Dataset)]
st <- as.Date("1990-1-1")
en <- as.Date("2020-12-1")
tt <- seq(st, en, by = "1 month")
data = xts(data, order.by=tt)
##########################################################################
RECFORECAST=function (Y,X,h,window){
st <- as.Date("1990-1-1")
en <- as.Date("2020-12-1")
tt <- seq(st, en, by = "1 month")
datas= cbind(Y,X)
newfcast= matrix(0,nrow(datas),h)
for (k in 1:nrow(datas)){
sample =datas[1:(window+k-1),]
# print(sample)
v= window+k
# print(v)
# fit = Arima(sample[,1], order=c(0,0,0),xreg=sample[,2])
fit = lm(sample[,1]~sample[,2], data = sample)
# fcast=forecast(fit,xreg=rep(sample[v,2],h))$mean
fcast = forecast.lm(fit,sample[v,2],h=1)$mean
print(fcast)
# print(fcast)
# newfcast[k+window+1,]=fcast
}
print(newfcast)
return(newfcast)
}
## Code to send the loop into forecasts
StoreMatrix = data$growth ## This is the first column data[,1]
for (i in 2:4)
{
try({
X=data[,i]
Y=data[,1]
RecModel=RECFORECAST(Y,X,h=1,window=60) ##Here the initial window is 60 obs
StoreMatrix=cbind(StoreMatrix,RecModel)
print(StoreMatrix)
}, silent=T)
}
The bits # were different ways I tried to crosscheck my data and they may not be useful. I have tried so many things but I don't seem to be able to get my head through it. At the end I want to have a matrix (StoreMatrix) with the first variable being the realization, and each of the columns with the corresponding 1 step ahead forecast.
The main lines where there seems to be an issue are these ones:
# fcast=forecast(fit,xreg=rep(sample[v,2],h))$mean
fcast = forecast.lm(fit,sample[v,2],h=1)$mean
Note sure how to solve this. Thank you very much.

Adjusting xaxis in plot.xts

I want to zoom into the chart. The chart from the code below use data from 2007 to 2019. I will like to look at the chart only from 2012 to 2015. Does anyone know how to do this?
I have tried with xlim = ("2012-01-01";"2015-01-01"), but that did not work.
library(quantmod)
getSymbols("AAPL")
plot.xts(AAPL[,6])
You have just to subset your xts-object to zoom it:
xts_data <- AAPL[ , 6]
xts_zoom <- xts_data['2012/2015']
plot.xts(xts_zoom)
The reason why setting xlim manually does not work is that the xlim values are calculated inside the plot.xts() itself. See, for example, the rows 123-134 of the plot.xts() source code:
if (cs$Env$observation.based) {
cs$Env$xycoords <- xy.coords(1:NROW(cs$Env$xdata[subset]))
cs$set_xlim(c(1, NROW(cs$Env$xdata[subset])))
cs$Env$xstep <- 1
}
else {
xycoords <- xy.coords(.index(cs$Env$xdata[cs$Env$xsubset]),
cs$Env$xdata[cs$Env$xsubset][, 1])
cs$Env$xycoords <- xycoords
cs$Env$xlim <- range(xycoords$x, na.rm = TRUE)
...
}
Another option is to use the built-in zoom tools of the quantmod package itself:
chartSeries(xts_data)
zoomChart('2012/2015')

R baseline package saving plots in a loop

I'm trying to optimize the parameters for baseline in the R baseline package by changing each parameters in a loop and comparing plots to determine which parameters give me the best baseline.
I currently have the code written so that the loop produces each plot, but I'm having trouble with getting the plot saved as the class of each object I'm creating is a baseline package-specific (which I'm suspecting is the problem here).
foo <- data.frame(Date=seq.Date(as.Date("1957-01-01"), by = "day",
length.out = ncol(milk$spectra)),
Visits=milk$spectra[1,],
Old_baseline_visits=milk$spectra[1,], row.names = NULL)
foo.t <- t(foo$Visits)
#the lines above were copied from https://stackoverflow.com/questions/37346967/r-packagebaseline-application-to-sample-dataset to make a reproducible dataset
df <- expand.grid(lambda=seq(1,10,1), p=seq(0.01,0.1,0.01))
baselinediff <- list()
for(i in 1:nrow(df)){
thislambda <- df[i,]$lambda
thisp <- df[i,]$p
thisplot <- baseline(foo.t, lambda=thislambda, p=thisp, maxit=20, method='als')
print(paste0("lambda = ", thislambda))
print(paste0("p = ", thisp))
print(paste0("index = ", i))
baselinediff[[i]] <- plot(thisplot)
jpeg(file = paste(baselinediff[[i]], '.jpeg', sep = ''))
dev.off()
}
I know that I would be able to extract corrected spectra using baseline.als but I just want to save the plot images with the red baseline so that I can see how well the baselines are getting drawn. Any baseline users out there that can help?
I suggest you change your loop in the following way:
for(i in 1:nrow(df)){
thislambda <- df[i,]$lambda
thisp <- df[i,]$p
thisplot <- baseline(foo.t, lambda=thislambda, p=thisp, maxit=20, method='als')
print(paste0("lambda = ", thislambda))
print(paste0("p = ", thisp))
print(paste0("index = ", i))
baselinediff[[i]] <- thisplot
jpeg(file = paste('baseline', i, '.jpeg', sep = ''))
plot(baselinediff[[i]])
dev.off()
}
Note that this does not try to capture the already plotted element (thisplot) inside of the list. Instead, the plotting is done after you call the jpeg command. This solves your export issue. Another problem was the naming of the file. If you call baselinediff[[i]] inside of paste, you apparently end up with an error. So I switched it to a simpler name. To plot your resulting list, call:
lapply(baselinediff, plot)
If you are determined on storing the already plotted element, the capture.plotfunction from the imager package might be a good start.

Can't store the result of pie() function R

I have a problem trying to store the result of my pie() function in a variable, it appears that it sets it to NULL whereas the plot is displayed, I don't understand why.
I want to store it in order to write it as an HTML file after.
Here is my code:
for(i in seq(1,13)){
values <- c(stat_pcs_region[ i,"pop_agriculteurs"], stat_pcs_region[i,"pop_commercant"], stat_pcs_region[i,"pop_cadres"],
stat_pcs_region[i,"pop_profIntermediaire"], stat_pcs_region[i,"pop_employes"], stat_pcs_region[i,"pop_ouvriers"],
stat_pcs_region[i,"pop_retraites"], stat_pcs_region[i,"pop_chomage"])
labels <- c("Agriculteurs", "Commercants, artisans et chef d entreprise", "Cadres", "Professions intermediares",
"Employes", "Ouvriers", "Retraites", "Chomeurs")
percentage <- round(values/sum(values)*100)
labels <- paste(percentage, "% de", labels)
p <- pie(values, labels, col = rainbow(9))
saveWidget(p, file = paste("C:/Users/henri/Downloads/Rapports_appli_geo/Pie_charts_regions/piechartPCS_reg", i, ".html", sep = ""))
}
Thanks in advance for your help

country-labels on spplot()

I'd like to add name-labels for regions on an spplot().
Example:
load(url('http://gadm.org/data/rda/FRA_adm0.RData'))
FR <- gadm
FR <- spChFIDs(FR, paste("FR", rownames(FR), sep = "_"))
load(url('http://gadm.org/data/rda/CHE_adm0.RData'))
SW <- gadm
SW <- spChFIDs(SW, paste("SW", rownames(SW), sep = "_"))
load(url('http://gadm.org/data/rda/DEU_adm0.RData'))
GE <- gadm
GE <- spChFIDs(GE, paste("GE", rownames(GE), sep = "_"))
df <- rbind(FR, SW, GE)
## working
plot(df)
text(getSpPPolygonsLabptSlots(df), labels = c("FR", "SW", "GE"))
## not working
spplot(df[1-2,])
text((getSpPPolygonsLabptSlots(df), labels = c("FR", "SW"))
The second one probably doesn't work because of lattice!?
However, I need the spplot-functionality.
How would I get the labels on the plot?
Standard way of adding some text is using the function ltext of lattice, but the coordinates given there are always absolute. In essence, you can't really rescale the figure after adding the text. Eg :
data(meuse.grid)
gridded(meuse.grid)=~x+y
meuse.grid$g = factor(sample(letters[1:5], 3103, replace=TRUE),levels=letters[1:10])
meuse.grid$f = factor(sample(letters[6:10], 3103, replace=TRUE),levels=letters[1:10])
spplot(meuse.grid, c("f","g"))
ltext(100,200,"Horror")
Produces these figures (before and after scaling)
You can use a custom panel function, using the coordinates within each panel :
myPanel <- function(x,y,xx,yy,labels,...){
panel.xyplot(x,y,...)
ltext(xx,yy,labels)
}
xyplot(1:10 ~ 1:10,data=quakes,panel=myPanel,
xx=(1:5),yy=(1:5)+0.5,labels=letters[1:5])
(run it for yourself to see how it looks)
This trick you can use within the spplot function as well, although you really have to check whatever plotting function you use. In the help files on spplot you find the possible options (polygonsplot, gridplot and pointsplot), so you have to check whether any of them is doing what you want. Continuing with the gridplot above, this becomes :
myPanel <- function(x,y,z,subscripts,xx,yy,labels,...){
panel.gridplot(x,y,z,subscripts,...)
ltext(xx,yy,labels)
}
# I just chose some coordinates
spplot(meuse.grid, c("f","g"),panel=myPanel,xx=180000,yy=331000,label="Hooray")
which gives a rescalable result, where the text is added in each panel :
Thank you, Gavin Simpson!
I finally found a way.
In the hope it helps others in the future, I post my solution:
sp.label <- function(x, label) {
list("sp.text", coordinates(x), label)
}
ISO.sp.label <- function(x) {
sp.label(x, row.names(x["ISO"]))
}
make.ISO.sp.label <- function(x) {
do.call("list", ISO.sp.label(x))
}
spplot(df['ISO'], sp.layout = make.ISO.sp.label(df))

Resources