首页 > 解决方案 > 在 t + 1 秒时搜索时间序列值

问题描述

我有两个时间序列数据集,这是 df1 的示例:

Second_since_midnight  MidPoint        MidPoint2       MidPoint3
34500.041162647        1530.625        1530.555        1530.760
34500.041184315        1530.625        1530.555        1530.760
34500.058515619        1530.620        1530.390        1530.595
34500.069502263        1530.620        1530.390        1530.595
34500.284990991        1530.410        1530.190        1530.395
34500.366234523        1530.410        1530.190        1530.395
34500.366236964        1530.410        1530.185        1530.390
34500.546860111        1529.990        1530.175        1530.175
34500.578238228        1529.855        1530.175        1530.175
34500.890952790        1530.265        1530.190        1530.190
34501.036660390        1530.265        1530.190        1530.190
34501.200413656        1530.265        1530.190        1530.190

df2 是 Second_since_midnight 数据点的时间序列,我需要在 1 秒后搜索 3 个中点:

Second_since_midnight  MidPoint_after_1sec MidPoint2_after_1sec Midpoint3_after_1sec
34500.041124224              -1                     -1                  -1
       ...         

我希望程序输出以下内容,因为 34501.041124224 之后的第一条记录是 df1 中的最后一行,Second_since_midnight 34501.200413656

Second_since_midnight  MidPoint_after_1sec MidPoint2_after_1sec Midpoint3_after_1sec
34500.041124224        1530.265            1530.190             1530.190
       ...

我目前编写以下 R 代码:

    ind_1s = 1

    for(m in 1:nrow(df2)){
        while((df2$Second_since_midnight[m] + 1) > df1$Second_since_midnight[ind_1s] & ind_1s < nrow(df1)) ind_1s = ind_1s + 1
        df2$MidPoint_after_1sec[m] = df1$MidPoint[ind_1s]
        df2$MidPoint2_after_1sec[m] = df1$MidPoint2[ind_1s]
        df2$MidPoint3_after_1sec[m] = df1$MidPoint3[ind_1s]

    }

这非常慢,因为 df2 的平均 nrow 为 30k,而 df1 的平均 nrow 为 1.2m。我想知道我是否可以有一些算法来更快地搜索这个中点。我正在使用 R 但我也可以转换为 Python 或其他语言

标签: rtime-seriestidyversefinance

解决方案


推荐阅读