如何编码和绘制两种交易策略的性能

How to code and plot the performance of two trading strategies

因此,除了名为 SP500.df 的动物园时间序列对象中的无风险利率之外,我还有 SP500 的每月 returns。我想回测两种不同的交易策略并将它们绘制成图表。以累计 return 的形式,或期末 1 美元初始投资的形式。

请注意,我还在两个相应的向量中提取了冬季和夏季 return。称为 Winter_returnssummer_returns.

mkt= returns
rf=无风险利率

这是数据框 SP500.df 的样子:

dput(head(SP500.df, 10))

structure(c(0.0286195, 0.03618317, -0.01363269, 0.02977401, 0.04461314, 
0.0015209, -0.03207303, -0.0079275, 0.01882991, 0.00584478, 0.02372219, 
0.03299206, -0.017908, 0.02540426, 0.04163062, -0.00317315, -0.03732322, 
-0.0109474, 0.0147047, 0.00087712, 0.00608527826274047, 0.00495046849033236, 
0.00503506482970477, 0.00481634688889247, 0.00424210936461577, 
0.00358500724272255, 0.00424210936461577, 0.00480928182207086, 
0.00485872460615713, 0.00487990531586144, 1, 1, 1, 1, 0, 0, 0, 
0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 
0, 0), .Dim = c(10L, 6L), .Dimnames = list(NULL, c("MKT", "CAP", 
"RF", "dummy", "dummyJAN", "adjdummy")), index = structure(c(-36494, 
-36466, -36435, -36405, -36374, -36344, -36313, -36282, -36252, 
-36221), class = "Date"), class = "zoo")

这是一个方法。
定义一个计算函数 calc 并将其应用于列 MKT 以获得策略 1,然后创建所有 returns/rates rates 的向量并将该函数应用于它。该图使用基本 R 图形。

library(zoo)

calc <- function(x, returns) x*cumprod((1 + returns))

strat1 <- calc(1, SP500.df$MKT)
strat1
#> 1870-01-31 1870-02-28 1870-03-31 1870-04-30 1870-05-31 1870-06-30 1870-07-31 
#>   1.028620   1.065838   1.051308   1.082610   1.130908   1.132628   1.096301 
#> 1870-08-31 1870-09-30 1870-10-31 
#>   1.087610   1.108090   1.114567


i_winter <- SP500.df$dummy == 1
rates <- numeric(NROW(SP500.df))
rates[i_winter] <- SP500.df$MKT[i_winter]
rates[!i_winter] <- SP500.df$RF[!i_winter]
strat2 <- calc(1, rates)
strat2
#>  [1] 1.028620 1.065838 1.051308 1.082610 1.087202 1.091100 1.095728 1.100998
#>  [9] 1.106347 1.111746

matplot(cbind(strat1, strat2), pch = 19)
matlines(cbind(strat1, strat2), lty = "solid")
legend("bottomright", legend = c("strategy 1", "strategy 2"), 
       col = 1:2, lty = "solid", pch = 19)

reprex package (v2.0.1)

创建于 2022-02-07

对于 ggplot2 图形,创建一个临时 data.frame 并将其通过管道传输到包 tidyr 的整形函数 pivot_longer。然后将结果通过管道传输到 ggplot.

library(ggplot2)

data.frame(
  date = index(SP500.df),
  strategy1 = strat1,
  strategy2 = strat2
) |> 
  tidyr::pivot_longer(-date) |> 
  ggplot(aes(date, value, color = name)) +
  geom_line() +
  geom_point() +
  scale_color_manual(values = c("black", "red")) +
  theme_bw()

reprex package (v2.0.1)

创建于 2022-02-07