## How to identify all possible permutations of a time series according to order of permutation

Question

I am trying to figure out a way to translate a financial time series into a symbolic time series that account for all "meaningful" permutations according to a given order (in R):

Example:

Given a Time Series: `ts= c(1,2,3,4,5)`

If Order=2 I would like to extract the following patterns:
1) 1 1 `(ts[i]==ts[i+1])`
2) 1 2 `(ts[i]<ts[i+1])`
3) 2 1 `(ts[i]>ts[i+1])`

(pattern 2 2 is redundant since equality is accounted for via pattern 1 1)

If Order=3 I would like to extract the following patterns:
1) 1 2 3 `(ts[i]<ts[i+1]<ts[i+2])`
2) 1 2 2 `(ts[i]<ts[i+1]==ts[i+2])`
3) 1 2 1 `(ts[i]<ts[i+1]>ts[i+2])`
4) 2 2 3 `(ts[i]==ts[i+1]<ts[i+2])`
5) 2 2 2 `(ts[i]==ts[i+1]==ts[i+2])`
6) 2 2 1 `(ts[i]==ts[i+1]>ts[i+2])`
7) 3 2 1 `(ts[i]>ts[i+1]>ts[i+2])`
8) 3 2 2 `(ts[i]>ts[i+1]==ts[i+2])`
9) 3 2 3 `(ts[i]>ts[i+1]<ts[i+2])`

What I am looking for is a scalable (in terms of Order being 2,3,4,5 and so on) and automated (function-wise) way to do this.

I am striving with packages such as "permute", "gtools", "combinat" but to no avail. I think what I seek is a special case of permutations. Can anyone help me with this problem?

My quest started from reading papers on "Permutation Entropy", a Google-scholar search shall provide you with relevant bibliography for anyone further interested.

Show source

## Answers to How to identify all possible permutations of a time series according to order of permutation ( 1 )

1. Try this:

``````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
``````

When order = 3:

``````rollapply(ts, 3, rank, ties='min')

[,1] [,2] [,3]
[1,]    1    3    2
[2,]    2    1    3
[3,]    1    2    3
[4,]    1    3    1
[5,]    3    2    1
[6,]    3    1    1
[7,]    2    2    1
``````

That's not quite what you want but it is close. The main issue is seen in the first two rows where you don't wish to distinguish the ranks of the first and third values when both are higher or lower than the middle observation. Here is a fix.

``````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
``````