如何重塑我的数据框以在 R 中使用 TTR?

How to reshape my data frame to use TTR in R?

基本上 TTR 允许获取代码的技术指标,数据应该是垂直的,如:

Date         Open   High    Low     Close
2014-05-16  16.83   16.84   16.63   16.71
2014-05-19  16.73   16.93   16.66   16.80
2014-05-20  16.80   16.81   16.58   16.70

但我的数据框是这样的:

   Sdate    Edate   Tickers Open_1  Open_2  Open_3  High_1  High_2  High_3  Low_1   Low_2   Low_3   Close_1 Close_2 Close_3
2014-05-16  2014-07-21  TK  31.6    31.8    32.2    32.4    32.4    33.0    31.1    31.5    32.1    32.1    32.1    32.7 
2014-05-17  2014-07-22  TGP 25.1    24.8    25.0    25.1    25.3    25.8    24.1    24.4    24.9    24.8    25.0    25.6 
2014-05-18  2014-07-23  DNR 3.4     3.5     3.8     3.6     3.8     4.1     3.3     3.5     3.8     3.5     3.7     3.9

如您所见,我有多个代码和时间范围。我检查了 TTR 包,它没有说明如何从中获取水平制作的技术指标和多个代码。我的原始数据有 50 天和数千个代码。要做到这一点,我只知道,我需要为每个代码制作清单,但我很困惑如何做到这一点。我该如何实现?

您可以使用 pivot_longer 获取垂直形状的数据:

out <- tidyr::pivot_longer(df, cols = -c(Sdate,Edate, Tickers), 
             names_to = c('.value', 'num'), 
             names_sep = '_')
out

# A tibble: 9 x 8
#  Sdate      Edate      Tickers num    Open  High   Low Close
#  <chr>      <chr>      <chr>   <chr> <dbl> <dbl> <dbl> <dbl>
#1 2014-05-16 2014-07-21 TK      1      31.6  32.4  31.1  32.1
#2 2014-05-16 2014-07-21 TK      2      31.8  32.4  31.5  32.1
#3 2014-05-16 2014-07-21 TK      3      32.2  33    32.1  32.7
#4 2014-05-17 2014-07-22 TGP     1      25.1  25.1  24.1  24.8
#5 2014-05-17 2014-07-22 TGP     2      24.8  25.3  24.4  25  
#6 2014-05-17 2014-07-22 TGP     3      25    25.8  24.9  25.6
#7 2014-05-18 2014-07-23 DNR     1       3.4   3.6   3.3   3.5
#8 2014-05-18 2014-07-23 DNR     2       3.5   3.8   3.5   3.7
#9 2014-05-18 2014-07-23 DNR     3       3.8   4.1   3.8   3.9

如果您想根据 Ticker 将上述数据拆分为数据框列表,您可以使用 split.

split(out, out$Tickers)

数据

df <- structure(list(Sdate = c("2014-05-16", "2014-05-17", "2014-05-18"
), Edate = c("2014-07-21", "2014-07-22", "2014-07-23"), Tickers = c("TK", 
"TGP", "DNR"), Open_1 = c(31.6, 25.1, 3.4), Open_2 = c(31.8, 
24.8, 3.5), Open_3 = c(32.2, 25, 3.8), High_1 = c(32.4, 25.1, 
3.6), High_2 = c(32.4, 25.3, 3.8), High_3 = c(33, 25.8, 4.1), 
    Low_1 = c(31.1, 24.1, 3.3), Low_2 = c(31.5, 24.4, 3.5), Low_3 = c(32.1, 
    24.9, 3.8), Close_1 = c(32.1, 24.8, 3.5), Close_2 = c(32.1, 
    25, 3.7), Close_3 = c(32.7, 25.6, 3.9)), 
class = "data.frame", row.names = c(NA, -3L))