R: Get quantmod's chartSeries and AddTA to not show last value - r

When using chartSeries, by default it also shows on the top left of the plot the last value. Is there any way to prevent it from doing it?
When adding a new TA with addTA, you can avoid the last value on the plot by setting the argument legend = "", but only if you're making a new plot for the TA. If the TA is on a previously plotted graphic, it'll show the last value regardless of what you put in the legend argument.
getSymbols ("AAPL", src = "google")
chartSeries(AAPL)
What can I use here to prevent it from printing the last value on the plot?
addTA(EMA(Cl(AAPL)), on = 1, legend = "")
This still prints the last value on the top left of the plot. The weird part is that it doesn't do it if you're plotting on a new plot like this:
addTA(EMA(Cl(AAPL)), legend = "")
Is it like this by default, or is there something I can do to get around it?

The last value is shown by default (yes, annoyingly). You'll likely have to modify the source code to remove the last number showing in addTA.
I don't use addTA, but rather add_TA and chart_Series, because I think they look much better (second generation charts for quantmod). Here is a solution that removes the last number from showing for the add_TA version. But you must be willing to modify the source code.
In add_TA, you'll need to modify approximately lines 56-60 of the source:
Replace the text.exp, which is this:
# this is inside add_TA:
if (is.na(on)) {
plot_object$add_frame(ylim = c(0, 1), asp = 0.15)
plot_object$next_frame()
text.exp <- expression(text(x = c(1, 1 + strwidth(name)),
y = 0.3, labels = c(name, round(last(xdata[xsubset]),
5)), col = c(1, col), adj = c(0, 0), cex = 0.9,
offset = 0, pos = 4))
plot_object$add(text.exp, env = c(lenv, plot_object$Env),
with these modifications:
if (is.na(on)) {
plot_object$add_frame(ylim = c(0, 1), asp = 0.15)
plot_object$next_frame()
text.exp <- expression(text(x = c(strwidth(name)), # <- affects label on the subchart
y = 0.3, labels = name, col = c(col), adj = c(0), cex = 0.9,
offset = 1, pos = 4))
plot_object$add(text.exp, env = c(lenv, plot_object$Env),
expr = TRUE)
...
and assign this modified code to a new variable, called say add_TA.mine:
add_TA.mine <- function (x, order = NULL, on = NA, legend = "auto", yaxis = list(NULL,
NULL), col = 1, taType = NULL, ...)
{
lenv <- new.env()
lenv$name <- deparse(substitute(x))
lenv$plot_ta <- function(x, ta, on, taType, col = col, ...) {
xdata <- x$Env$xdata
....
[all the code for the rest of the function with modifications]....
}
}
plot_object
}
Now, just run the code with the modified function
library(quantmod)
getSymbols("AAPL")
environment(add_TA.mine) <- environment(get("add_TA", envir = asNamespace("quantmod")))
assignInNamespace(x = "add_TA", value = add_TA.mine, ns = "quantmod")
chart_Series(AAPL, subset = "2017")
add_TA(RSI(Cl(AAPL)))
quantmod:::add_TA(RSI(Cl(AAPL)))
You can see the last value is no longer printed:
(You could make the same kinds of changes in the old addTA code (perhaps via chartSeries if you really want to stick to the old plots)
If you're happy with the changes, and want to make them permament in add_TA, you can recompile the quantmod source code yourself with your modifications (i.e. you need to download the quantmod source code and recompile the package) . If you make a mess of things you can always redownload the original quandmod source code again.

Related

dropTA specific indicator by name

Can't figure out how to delete a specified indicator by name from TA list in R quantmod.
require("quantmod")
getSymbols("AAPL", src="yahoo", from = '2018-01-1', to = '2019-01-1')
#my custom indicator
AAPL_sma_50 <- SMA(
Cl(AAPL),
n = 50
)
candleChart(AAPL, up.col = "black", dn.col = "red", theme = "white")
addTA(AAPL_sma_50, on = 1, col = "blue")
addBBands()
listTA()
listTA() output:
[[1]] addVo()
[[2]] addTA(ta = AAPL_sma_50, on = 1, col = "blue")
[[3]] addBBands()
I'm able to do delete built-in with dropTA('addBBands'), but cannot delete custom indicator the same way:
dropTA('AAPL_sma_50')
Error in dropTA("AAPL_sma_50") : nothing to remove
dropTA(2) is not working by index either - it always deletes first element
How I can delete the second custom one only, or how to create it, to be able to delete later by name- e.g. dropTA('myCustomIndicator')
There are a few options to remove TA's from the plot. The trick is to know that when you use addTA(my_indicator), you can not use dropTA(my_indicator). Because you added the TA via addTA(), so you need to call dropTA(ta = "addTA").
Now a few possibilies:
dropTA(all = TRUE) # removes all technical indicators
dropTA(ta = "addBBAnds") # removes the bolinger bands you added via addBBands()
If you added a few custom TA's with addTA, you can specify which version to delete if you now the order.
dropTA(ta = "addTA", occ = 2) # removes the second occurence of the TA you added
dropTA(ta = "addTA", all = TRUE) # removes all TA's added with addTA
This is useful when you have used multiple addEMA or addSMA indicators to the chart.
example with EMA indicators:
library(quantmod)
getSymbols("AAPL", src="yahoo", from = '2018-01-1', to = '2019-01-1')
candleChart(AAPL, up.col = "black", dn.col = "red", theme = "white")
addEMA(Cl(AAPL), n = 13, on = 1)
addEMA(Cl(AAPL), n = 21, on = 1)
addEMA(Cl(AAPL), n = 5, on = 1)
dropTA(ta = "addEMA", occ = 2) # removes the second occurence of the EMA's you added
dropTA(ta = "addEMA", all = TRUE) # removes all (other) EMA's added

Changes in plotting an XTS object

I had produced the following chart, which is created using an xts object.
The code I used was simply
plot(graphTS1$CCLL, type = "l", las = 2, ylab = "(c)\nCC for Investors", xlab = "", main = "Clustering Coefficient at the Investor Level")
I updated my R Studio Package and R version and then by running the same code I got the following chart.
Obviously the two are not the same. Can people help me remove the second Y axis - I do not need that, and remove the automatic heading of 2007-03-01 / 2010-12-01. Numerous attempts of this have failed. I did use zoo.plot but the gridlines and ability and the quarterly marks were removed.
My R version is 3.4.0 (2017-04-21) with the following platform "x86_64-apple-darwin15.6.0". Thanks in advance.
You want to remove the right hand axis. There is an argument in plot.xts(..., yaxis.right = TRUE, ...). So
library('xts')
#> Loading required package: zoo
#>
#> Attaching package: 'zoo'
#> The following objects are masked from 'package:base':
#>
#> as.Date, as.Date.numeric
data(sample_matrix)
sample.xts <- as.xts(sample_matrix, descr='my new xts object')
plot(sample.xts, yaxis.right = FALSE)
does what you want.
I took a stab at solving the second question, removing the label at the top right hand side. Examining the source code for plot.xts() reveals that label is hardcoded into the main title. Even setting main = '' isn't going to remove it. You can work around it by editing plot.xts() and copying it to a new function.
plotxts <- fix("plot.xts")
# In the editor that opens, replace the lines below:
### text.exp <- c(expression(text(xlim[1], 0.5, main, font = 2,
### col = theme$labels, offset = 0, cex = 1.1, pos = 4)),
### expression(text(xlim[2], 0.5, paste(start(xdata[xsubset]),
### end(xdata[xsubset]), sep = " / "), col = theme$labels,
### adj = c(0, 0), pos = 2)))
### cs$add(text.exp, env = cs$Env, expr = TRUE)
# with these lines:
### text.exp <- expression(text(xlim[1], 0.5, main, font = 2,
### col = theme$labels, offset = 0, cex = 1.1, pos = 4))
# Finally, you need to ensure your copy's environment is the xts namespace:
environment(plotxts) <- asNamespace("xts")
plotxts(sample.xts, yaxis.right = FALSE, main = "Main Title")
The second, and perhaps
simpler option is to use a different plot function and modify it to produce the gridlines etc that you want. I will start
with plot.zoo() because it is already handling time series nicely.
zoo::plot.zoo(sample.xts, screens = 1, xlab="", las=2, main="Main Title")
grid() # add the grid
That at least gets the grid on there. I can't test if it will handle the x axis labels the same way without data at the right frequency.
You can now (finally) omit the date range from the plot in xts 0.12.2 on CRAN. Set main.timespan = FALSE.
plot(sample.xts[,1], yaxis.right = FALSE, main = "Main Title", main.timespan = FALSE)

turn off grid lines for R xyplot timeseries

I am plotting a time series with the timePlot function of the open air package of R. The graph has grey grid lines in the background that I would like to turn off but I do not find a way to do it. I would expect something simple such as grid = FALSE, but that is not the case. It appears to be rather complex, requiring the use of extra arguments which are passed to xyplot of the library lattice. I believe the answer lies some where in the par.settings function but all attempts have failed. Does anyone have any suggestions to this issue?
Here is by script:
timeozone <- import(i, date="date", date.format = "%m/%d/%Y", header=TRUE, na.strings="")
ROMO = timePlot(timeozone, pollutant = c("C7", "C9", "C10"), group = TRUE, stack = FALSE,y.relation = "same", date.breaks = 9, lty = c(1,2,3), lwd = c(2, 3, 3), fontsize = 15, cols = c("black", "black"), ylab = "Ozone (ppbv)")
panel = function(x, y) {
panel.grid(h = 0, v = 0)
panel.xyplot(x,y)
}

Weird behaviour than animating lines with rgl and rglwidget

I am trying to follow help and Internet examples to create a very simple animation of a 3d-line in R. This is just a test and my final goal is to use this functionality to visually verify results of some geometrical transformations on 3d-movement data that I am analysing. So basically I need nothing more than a ‘3d-player’ interface that allows for usual interaction (rotation, zoom, play, stop, slide).
I figured out that rgl package does the job and I am able to use it for the sphere/points animation. But now I need to use it on lines and I get very strange results. In the example below there are 4 points and two lines (cyan and red) that connect the same points but the red line is for some reason in the ‘wrong’ place. The animation doesn’t make sense neither. Now, I am thinking may be it is impossible to do >> to animate more than one vertex with more than one attribute? But I don’t see this in documentation and obviously it is possible because line is animated! I spent quite a long time trying to figure out what is going on and will appreciate any help/advise/directions. many thanks
Ps: Tthe code below is a chunk in the markdown file and I am using Rstudio.
require(rgl)
require(rglwidget)
p11=c(0,0,0)
p21=c(50,50,0)
p12=c(50,0,0)
p22=c(10,50,50)
saveopts <- options(rgl.useNULL = TRUE)
did=list()
did[[1]]=plot3d(rbind(p11,p21,p12,p22), type="s", alpha = 1, lwd = 5, col = c('brown','darkgreen','orange','green'))
did[[2]]=spheres3d(c(100,100,100), alpha = 1, lwd = 5, col = "blue",radius=2)
did[[3]]=lines3d(rbind(p11,p21),lwd=8, col='cyan',alpha=.9)
did[[4]]=planes3d(0, 0, 1, 0, alpha=.4, col='green')
did[[5]]=lines3d(rbind(p11,p21),lwd=2, col='red')
aspect3d(1, 1, 1)
did[[6]]=grid3d(c("x-", "z-"),at = NULL,col = "gray",lwd = .5,lty = 1,n = 5)
sceneT = rglwidget(elementId = "plot3dT",width=500, height=300) #%>%
rgl.ids()
rgl.attrib(id=did[[3]],attrib = c(1:length(did[[3]])))
playwidget(sceneT,list(
vertexControl(values = rbind(c(0,0,0,0,0,0),c(50,50,50,50,50,50)),
vertices = 1:6, attributes = "z", objid = did[[4]], param = 1:2,interp =T),
vertexControl(values = r1,
vertices = 1:2, attributes = c('x',"y","z",'x',"y","z"), objid = did[[5]], param = 1:2,interp =T)),
start = 1, stop = 2, step = .1, precision = 3)
options(saveopts)

How to change the color and width of lines with par function in R

I have a question about the par function in R.
I want to change the color and/or width of a line in a graph with par function. (I am using par function because the gaps.plot command below does not allow "col" option to be included. The gaps.plot command is used after the synth command).
So, I used the following command. But I noticed that the lines of the BOX are changed rather than the lines of the GRAPHS.
synth1<-read.csv(file="C:\\Users\\Research\\R\\synthinR_v4.csv",header=TRUE)
attach(synth1)
library("Synth")
dataprep.out34 <- dataprep(foo = synth1, predictors = c("lncdsales", "md1", "md2","md3", "md4", "md5", "md6", "md7", "md8", "md9", "md10", "md11", "yd1", "yd2", "yd3", "yd4", "yd5", "yd6", "yd7", "yd8"), predictors.op = "mean", time.predictors.prior = -13:1, dependent = "lndigital", unit.variable = "artistalbumcode", time.variable = "release", treatment.identifier = 34, controls.identifier = c(1:33, 35:49), time.optimize.ssr = -13:1, time.plot = -13:25)
synth.out34 <- synth(data.prep.obj = dataprep.out34, method = "BFGS")
par(lwd = 2, col="#cccccc")
gaps.plot(synth.res = synth.out34, dataprep.res = dataprep.out34, Ylab = " Log Digital Sales ", Xlab = "Release", Ylim = c(-7, 7) , Main = NA)
Does anyone know how to fix this problem??
Thank you in advance for your willingness to help. I greatly appreciate it!
The col argument to par sets the default plotting colour (i.e. when col is not explicitly specified in plotting calls), but unfortunately col = "black" is hard-coded into the source of gaps.plot.
You can make a modified copy of the function by either (1) viewing the source (F2 in RStudio, or just executing gaps.plot), editing it and assigning it to a new object, or (2) doing something like the following:
gaps.plot2 <- eval(parse(text=gsub('col = "black"', 'col = "red"',
deparse(Synth:::gaps.plot))))
and then using gaps.plot2 as you would use gaps.plot:
gaps.plot2(synth.res = synth.out34, dataprep.res = dataprep.out34,
Ylab = " Log Digital Sales ", Xlab = "Release", Ylim = c(-7, 7) ,
Main = NA)
Alter the lwd similarly. For example to make lines red and have width of 3, use nested gsub calls like this:
gaps.plot2 <- eval(parse(text=gsub('lwd = 2', 'lwd = 3',
gsub('col = "black"', 'col = "red"',
deparse(Synth:::gaps.plot)))))

Resources