我在 R 中有这段代码:
corr = function(x, y) {
sx = sign(x)
sy = sign(y)
cond_a = sx == sy && sx > 0 && sy >0
cond_b = sx < sy && sx < 0 && sy >0
cond_c = sx > sy && sx > 0 && sy <0
cond_d = sx == sy && sx < 0 && sy < 0
cond_e = sx == 0 || sy == 0
if(cond_a) return('a')
else if(cond_b) return('b')
else if(cond_c) return('c')
else if(cond_d) return('d')
else if(cond_e) return('e')
}
它的作用是与 R 中的 mapply
函数结合使用,以便计算时间序列中存在的所有可能符号模式。在这种情况下,模式的长度为 2,所有可能的元组为:(+,+)(+,-)(-,+)(-,-)
我这样使用 corr
函数:
> with(dt['AAPL'], table(mapply(corr, Return[-1], Return[-length(Return)])) /length(Return)*100)
a b c d e
24.6129416 25.4466058 25.4863041 24.0174672 0.3969829
> dt["AAPL",list(date, Return)]
symbol date Return
1: AAPL 2014-08-29 -0.3499903
2: AAPL 2014-08-28 0.6496702
3: AAPL 2014-08-27 1.0987923
4: AAPL 2014-08-26 -0.5235654
5: AAPL 2014-08-25 -0.2456037
我想将 corr
函数概括为 n
个参数。这意味着对于每个 n
,我都必须写下与所有可能的 n 元组相对应的所有条件。目前我能想到的最好的方法是制作一个 python 脚本来使用循环编写代码字符串,但必须有一种方法可以正确地做到这一点。您是否知道我如何概括复杂的条件编写,也许我可以尝试使用 expand.grid
但如何进行匹配?
最佳答案
我认为你最好使用 rollapply(...)
在zoo
为此打包。由于您似乎正在使用 quantmod
无论如何(加载 xts
和 zoo
),这是一个不使用所有嵌套 if(...)
的解决方案声明。
library(quantmod)
AAPL <- getSymbols("AAPL",auto.assign=FALSE)
AAPL <- AAPL["2007-08::2009-03"] # AAPL during the crash...
Returns <- dailyReturn(AAPL)
get.patterns <- function(ret,n) {
f <- function(x) { # identifies which row of `patterns` matches sign(x)
which(apply(patterns,1,function(row)all(row==sign(x))))
}
returns <- na.omit(ret)
patterns <- expand.grid(rep(list(c(-1,1)),n))
labels <- apply(patterns,1,function(row) paste0("(",paste(row,collapse=","),")"))
result <- rollapply(returns,width=n,f,align="left")
data.frame(100*table(labels[result])/(length(returns)-(n-1)))
}
get.patterns(Returns,n=2)
# Var1 Freq
# 1 (-1,-1) 22.67303
# 2 (-1,1) 26.49165
# 3 (1,-1) 26.73031
# 4 (1,1) 23.15036
get.patterns(Returns,n=3)
# Var1 Freq
# 1 (-1,-1,-1) 9.090909
# 2 (-1,-1,1) 13.397129
# 3 (-1,1,-1) 14.593301
# 4 (-1,1,1) 11.722488
# 5 (1,-1,-1) 13.636364
# 6 (1,-1,1) 13.157895
# 7 (1,1,-1) 12.200957
# 8 (1,1,1) 10.765550
基本思路是创建一个patterns
矩阵 2^n
行和 n 列,其中每行代表一种可能的模式(例如,(1,1)、(-1,1) 等)。然后使用 rollapply(...)
将每日 yield n-wise 传递给此函数并确定 patterns
中的哪一行火柴sign(x)
确切地。然后使用这个行号向量和一个索引到 labels
,其中包含模式的字符表示,然后使用 table(...)
和你一样。
这对于 n 天模式是通用的,但它忽略了任何返回恰好为零的情况,因此 $Freq
列加起来不等于 100。如您所见,这种情况并不经常发生。
有趣的是,即使在崩盘期间,连续两天上涨的可能性(非常小)也高于连续两天下跌的可能性。如果你看plot(Cl(AAPL))
在此期间,您可以看到这是一段相当疯狂的旅程。
关于r - 如何推广这个算法(符号模式匹配计数器)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26193451/