Quantmod addMACD() remove line plot - r

I was currently using Quantmod to visualize technical analysis of equity data. When I came across the addMACD() functions for adding MACD graph and it works fine, except when I need to visualize the histogram only instead of the line graph.
addMACD(fast = display$macdFast, slow = display$macdSlow, signal = display$macdSignal, histogram = TRUE)
After reading through the documentation, I cannot figure out a way to remove the line plot of MACD graph. Is is possible to remove line plot while retaining histogram plot for MACD?

I always seem have problems with creating complicated newTA objects with quantmod, but here is an SO example. I find it easier to use rtsplot. That is a plotting package for xts objects but based on the base plots.
Since the macd histogram is nothing but the difference between the macd and the macd signal you can create your own histogram values:
library(quantmod)
goog <- getSymbols("GOOGL", from = "2019-01-01", auto.assign = F)
goog_macd <- MACD(goog$GOOGL.Close)
goog_macd_his <- goog_macd$macd - goog_macd$signal
library(rtsplot)
layout(c(1,1,1,2))
rtsplot(goog, type = "candle")
rtsplot(goog_macd_his , type = "h", lwd = 2)

Related

Plotting multiple csv's on one graph in R

I need to plot two sets of data on one graph, and then use locator() to draw a vertical line at a given date. I have the code below and it works until after the plot function. The lines function is not adding the second dataset to my graph.
Can someone please help me understand what I'm doing incorrectly?
Thank you in advance
LMT <- read.csv("LMT.csv",header = T)
JNJ <- read.csv("JNJ.csv",header = T)
LMT$Date <- as.Date(LMT$Date)
JNJ$Date <- as.Date(JNJ$Date)
plot(y=LMT$Adj.Close, x=LMT$Date, ylim = c(0,500), type = "l")
lines(JNJ$Adj.Close,type = "l")

Represent a colored polygon in ggplot2

I am using the statspat package because I am working on spatial patterns.
I would like to do in ggplot and with colors instead of numbers (because it is not too readable),
the following graph, produced with the plot.quadratest function: Polygone
The numbers that interest me for the intensity of the colors are those at the bottom of each box.
The test object contains the following data:
Test object
I have looked at the help of the function, as well as the code of the function but I still cannot manage it.
Ideally I would like my final figure to look like this (maybe not with the same colors haha):
Final object
Thanks in advance for your help.
Please provide a reproducible example in the future.
The package reprex may be very helpful.
To use ggplot2 for this my best bet would be to convert
spatstat objects to sf and do the plotting that way,
but it may take some time. If you are willing to use base
graphics and spatstat you could do something like:
library(spatstat)
# Data (using a built-in dataset):
X <- unmark(chorley)
plot(X, main = "")
# Test:
test <- quadrat.test(X, nx = 4)
# Default plot:
plot(test, main = "")
# Extract the the `quadratcount` object (regions with observed counts):
counts <- attr(test, "quadratcount")
# Convert to `tess` (raw regions with no numbers)
regions <- as.tess(counts)
# Add residuals as marks to the tessellation:
marks(regions) <- test$residuals
# Plot regions with marks as colors:
plot(regions, do.col = TRUE, main = "")

How to store forest plot in an object to be recalled in R?

Just a little question on how to store and recall forest plot in R. I am creating forest plot using the meta function in R. I may have the need to store the graph and recall in the viewer at a later time. I've tried with this expression:
forest.meta <- forest(meta, [...])
where [...] are the options, but when I type "forest.meta", I get a "null" error rather than the graph again in the viewer.
Where I am wrong?
Thank you in advance for any help.
You get NULL because that's what the function returns, much as base R's plot does. It's not like ggplot where an actual plot object is returned for you to manipulate.
However, all is not lost. Since forest plots using grid graphics, we can grab the contents of the plotting window, store them as a collection of graphical objects, and plot them again later:
library(meta)
data(Olkin1995)
m1 <- metabin(ev.exp, n.exp, ev.cont, n.cont,
data = Olkin1995, subset = c(41, 47, 51, 59),
sm = "RR", method = "I",
studlab = paste(author, year))
forest(m1)
# Now grab the plot
my_plot <- grid::grid.grab()
The plot is now stored as my_plot, so suppose we want to use the plotting window for something else meantime
plot(1:10)
When we're done, we can recall the exact same plot by doing:
grid::grid.newpage()
grid::grid.draw(my_plot)

Quantmod Oscillators

Utilizing the chartSeries function in the quantmod package, I want to modify the RSI oscillator. Given an xts object containing OHLC price data, here is the call that I am using:
chartSeries(plot_report[, 1:4],
name = substr(ticker, 1, nchar(ticker) - 4),
theme = chartTheme('white.mono', grid.col = NA),
TA = c(addRSI(n = 14, maType = "SMA")),
type = "line",
bar.type = 'ohlc',
major.ticks = 'months',
show.grid = FALSE,
log.scale = TRUE)
Generating this chart:
I have four questions:
How can I change the default color of blue to something else? I have tried: c(addRSI(n = 14, maType = "SMA", col = "black")). However, I get the "unused argument" error.
Can I draw horizontal lines in the oscillator panel? Traditional RSI's have a horizontal red line at a y-axis value of 70 and a horizontal green line at a y-axis value of 30 to indicate overbought/oversold levels.
Is it possible to plot another calculation as an oscillator line below the chart? I have some proprietary oscillators that I want to visualize instead of the RSI or any of the indicators in the TTR package.
How can I get involved in improving the quantmod charting functionality; is this project being actively maintained?
You can't. You would need to add ... to the arguments for addRSI and modify the body of the function to use ... appropriately. A work-around is to calculate RSI manually, then call addTA as done in the answer to Change line colors of technical indicators made by R quantmod TTR?.
Use addLines:
getSymbols("SPY"); chartSeries(SPY, TA="addRSI();addLines(h=c(30,70), on=2)")
Use addTA with the object containing your proprietary data.
See quantmod's GitHub page. Yes, it's actively maintained. The last update was pushed to CRAN a couple months ago.

Clearing plotted points in R

I am trying to use the animation package to generate an "evolving" plot of points on a map. The map is generated from shapefiles (from the readShapeSpatial/readShapeLines functions).
The problem is when it's plotted in a for loop, the result is additive, whereas the ideal result is to have it evolve.
Are there ways of using par() that I am missing?
My question is: is there a way to clear just the points ploted from the points function
and not clearing the entire figure thus not having to regraph the shapefiles?
in case someone wants to see code:
# plotting underlying map
newyork <- readShapeSpatial('nycpolygon.shp')
routes <- readShapeLines('nyc.shp')
par(bg="grey25")
plot(newyork, lwd=2, col ="lightgray")
plot(routes,add=TRUE,lwd=0.1,col="lightslategrey")
# plotting points and save to GIF
ani.options(interval=.05)
saveGIF({
par(bg="grey25")
# Begin loop
for (i in 13:44){
infile <-paste("Week",i,".csv",sep='')
mydata <-read.csv(file = infile, header = TRUE, sep=",")
plotvar <- Var$Para
nclr <- 4
plotclr <-brewer.pal(nclr,"RdPu")
class<- classIntervals(plotvar,nclr,style = "pretty")
colcode <- findColours(class,plotclr)
points(Var$Lon,Var$Lat,col=colcode)
}
})
If you can accept a residual shadow or halo of ink, you can over-plot with color ="white" or == to your background choices. We cannot access your shape file but you can try it out by adding this line:
points(Var$Lon, Var$Lat, col="grey25")
It may leave gaps in other previously plotted figures or boundaries, because it's definitely not object-oriented. The lattice and ggplot2 graphics models are more object oriented, so if you want to post a reproducible example, that might be an alternate path to "moving" forward. I seem to remember that the rgl package has animation options in its repetoire.

Resources