R 如何根据排列顺序识别时间序列的所有可能排列
我试图找出一种方法,将金融时间序列转换为符号时间序列,根据给定的顺序(在R中)解释所有“有意义”的排列: 例如: 给定一个时间序列:R 如何根据排列顺序识别时间序列的所有可能排列,r,algorithm,time-series,permutation,combinatorics,R,Algorithm,Time Series,Permutation,Combinatorics,我试图找出一种方法,将金融时间序列转换为符号时间序列,根据给定的顺序(在R中)解释所有“有意义”的排列: 例如: 给定一个时间序列:ts=c(1,2,3,4,5) 如果Order=2,我想提取以下模式: 1) 1 1(ts[i]==ts[i+1]) 2) 12(ts[i]ts[i+1]) (模式2是冗余的,因为相等是通过模式1说明的) 如果Order=3,我想提取以下模式: 1) 1 2 3(ts[i]ts[i+1]==ts[i+2]) 9) 3.2.3(ts[i]>ts[i+1]试试这个: l
ts=c(1,2,3,4,5)
如果Order=2,我想提取以下模式:
1) 1 1
(ts[i]==ts[i+1])
2) 12
(ts[i]ts[i+1])
(模式2是冗余的,因为相等是通过模式1说明的)
如果Order=3,我想提取以下模式:
1) 1 2 3
(ts[i]ts[i+1]==ts[i+2])
9) 3.2.3
(ts[i]>ts[i+1]试试这个:
library(zoo)
ts <- c(1,3,2,4,5,4,3,3,2)
rollapply(ts, 2, rank, ties='min')
[,1] [,2]
[1,] 1 2
[2,] 2 1
[3,] 1 2
[4,] 1 2
[5,] 2 1
[6,] 2 1
[7,] 1 1
[8,] 2 1
这并不是您想要的,但很接近。主要问题出现在前两行中,您不希望区分第一个值和第三个值的秩,因为这两个值都高于或低于中间值。这里有一个修复方法
z <- rollapply(ts, 3, rank, ties='min')
lohilo <- z[,1] < z[,2] & z[,3] < z[,2]
hilohi <- z[,1] > z[,2] & z[,3] > z[,2]
z[lohilo,] <- rep(c(1,2,1),rep(sum(lohilo),3))
z[hilohi,] <- rep(c(2,1,2),rep(sum(hilohi),3))
z
[,1] [,2] [,3]
[1,] 1 2 1
[2,] 2 1 2
[3,] 1 2 3
[4,] 1 2 1
[5,] 3 2 1
[6,] 3 1 1
[7,] 2 2 1
z在下面的函数中计算时间序列的置换,该函数专门针对置换熵()进行计算:
函数来计算给定时间序列的顺序模式。
#输入(2个参数。空参数无效)
#x=给定时间序列(类型=数值向量)
#尺寸=嵌入尺寸(类型=数值)
#dim的常用值范围为3到7
#输出是大小=(dim)的数字向量!
序数_模式
z <- rollapply(ts, 3, rank, ties='min')
lohilo <- z[,1] < z[,2] & z[,3] < z[,2]
hilohi <- z[,1] > z[,2] & z[,3] > z[,2]
z[lohilo,] <- rep(c(1,2,1),rep(sum(lohilo),3))
z[hilohi,] <- rep(c(2,1,2),rep(sum(hilohi),3))
z
[,1] [,2] [,3]
[1,] 1 2 1
[2,] 2 1 2
[3,] 1 2 3
[4,] 1 2 1
[5,] 3 2 1
[6,] 3 1 1
[7,] 2 2 1
# Function to compute the ordinal patterns for a given time series.
# Input (2 arguments. Null arguments are not vaild)
# x = Given time series (type=numeric vector)
# dim = Embedding dimension (type=numeric)
# Commonly used value of dim ranges from 3 to 7
# Output is a numeric vector of size=(dim)!
ordinal_pattern<-function(x,dim){
# Generate ordinal numbers to assign. For example if dim =3, then
# ordinal number=0,1,2
ordinal_numbers<-seq(0,(dim-1),by=1)
# Compute all possible permutations of the ordinal numbers.
# Maximum size of possible_pattern=dim!
possible_pattern<-(combinat::permn(ordinal_numbers))
# Initialize result. Result is the output.
result<-0
result[1:length(possible_pattern)]<-0
# Loop for computation of ordinal pattern
for(i in 1:(length(x)-(dim-1))){
temp<-x[i:(i+(dim-1))]
tempseq<-seq(0,dim-1,by=1)
tempdata<-data.frame(temp,tempseq)
tempdata<-tempdata[order(temp),]
for(j in 1: length(possible_pattern)){
if (all(possible_pattern[[j]]==tempdata$tempseq)){
result[j]<-result[j]+1
}
}
}
return(result)
}