Add dots, legends, and text to stories using xts objects

I'm starting to analyze pairs of pairs a bit (trading in pairs), and here is the function that I wrote to create a chart (par.report - below).

I need to build three different lines in one plot. The function I listed does what I want, but it will take a bit of work if I want to fine tune the x axis (time line). Be that as it may, it only prints years (for 10 years of data) or months (for 6 months of data) along the x axis without formatting for ticks.

If I use an xts object, that is, if I use

plot(xts-object-with-date-asset1-asset2, ...)

instead

plot(date, asset2, ...)

I get a beautifully formatted x axis right away (along with the grid and field), but subsequent additions to the graph using functions like points (), text (), lines () fail. I believe points.xts () and text.xts () are not coming out anytime soon.

I would like the convenience of xts objects, but I also need fine-grained control over my plot. So what should be my workflow? Do I have to adhere to the basic graphics and do all the settings manually? Or is there a way I can get xts to work for me?

I know about the grate and ggplot2, but I do not want to use them now. Here is the function I mention (any criticism / suggestions for improving the code are welcome) -

library(xts)

pairs.report <- function(asset1, asset2, dataset) {

#create data structures
attach(dataset)
datasetlm <- lm(formula = asset1 ~ asset2 + 0, data = dataset)
beta = coef(datasetlm)[1]

#add extra space to right margin of plot within frame
par(mar=c(5, 4, 4, 4) + 0.1)

# Plot first set of data and draw its axis
ylim <- c(min(asset2,asset1), max(asset2,asset1))
plot(date, 
     asset2,  
     axes=T, 
     ylim=ylim, 
     xlab="Timeline", 
     ylab="asset2 and asset1 equity", 
     type="l", 
     col="red", 
     main="Comparison between asset2 and asset1")
lines(date, asset1, col="green")
box()
grid(lwd=3)

# Allow a second plot on the same graph
par(new=T)

# Plot the second plot and 
ylim <- c(min(asset1-beta*asset2), max(asset1-beta*asset2))
plot(date, 
     asset1-beta*asset2, 
     xlab="", ylab="", 
     ylim=ylim, 
     axes=F, 
     type="l", 
     col="blue")

#put axis scale on right
axis(side=4, 
     ylim=ylim, 
     col="blue",
     col.axis="blue")
mtext("Residual Spread",side=4,col="blue",line=2.5)

abline(h=mean(asset1-beta*asset2))
}
+5
source share
1

plot.xts - , , points.default() lines.default(), x, plot.xts. . xts zoo, , methods(lines) (), , . points.zoo "plot.zoo".

+3

All Articles