6

我开始对股票配对(配对交易)进行一些分析,这是我为生成图表而编写的函数(pairs.report - 下面列出)。

我需要在一个图中绘制三个不同的线。我列出的功能可以完成我想要它做的事情,但如果我想要在 x 轴(时间线)上进行精细定制,这将需要一些工作。事实上,它只在 x 轴上打印年份(10 年的数据)或月份(6 个月的数据),没有刻度的格式。

如果我使用 xts 对象,即,如果我使用

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

代替

plot(date, asset2, ...)

我马上得到了一个格式很好的 x 轴(连同网格和框),但是随后使用 points()、text()、lines() 等函数添加到绘图中失败了。我想 points.xts() 和 text.xts() 不会很快出现。

我想要 xts 对象的便利性,但我还需要对我的情节进行细粒度控制。那么我的工作流程应该是什么样的呢?我是否必须坚持基本图形并手动进行所有自定义?或者有没有办法让 xts 为我工作?

我知道 lattice 和 ggplot2,但我现在不想使用它们。这是我提到的功能(欢迎任何改进代码的批评/建议) -

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))
}
4

1 回答 1

4

plot.xts是一个基本绘图函数,这意味着您可以使用points.default()并且lines.default()如果您使用与 plot.xts 使用的相同 x 参数。但这不是必需的。它已经在 xts 和 zoo 包中进行了散列,因为当这些包被加载时,您执行methods(lines)并且方法(点)您会看到这些功能已经可用。points.zoo记录在 ?plot.zoo 页面上。

于 2011-08-11T12:39:53.053 回答