根据滚动条件创建列

问题描述 投票:0回答:1

我有一个包含 2 种资产价格及其比率 (A/B) 的 Z 分数的数据框,并且正在尝试进行简单的回测,并生成当 Z 分数 < -2 (long ratio) or Z score > +2(空头比率)时进入的配对比率交易的信号,并且当 Z 分数 >= -0.1 或 Z 分数 <= 0.1 respectively.

时展开
(index)     Asset A Asset B  Z Score  Column I need
2023-01-05  33400.0 45.6781 -2.002516  Entry (long)
2023-01-06  34050.0 46.5457 -1.952896
2023-01-09  34800.0 48.0222 -2.157506
2023-01-10  35150.0 48.2774 -1.988247
2023-01-11  35600.0 48.6792 -1.856716
...
2023-02-21  37900.0 50.8524 -0.728916
2023-02-22  36600.0 49.7823 -1.021323
2023-02-23  37850.0 51.6347 -1.071015
2023-02-24  39300.0 50.7727 0.171235   Exit (long)
2023-02-27  38700.0 50.2548 0.050697
2023-02-28  38350.0 49.9594 -0.023634

必须区分是因为>2(空头比率入场)而触发入场,还是因为-2(多头比率入场)触发入场。

对于退出条件,如果由于 Z 分数 > 2(空头比率入场)而有入场,则当 Z 分数为 <= 0.1 and if the entry was triggered by Z score < -2 (long ratio entry) then exit when Z score is >= -0.1 时退出 区分交易是哪种类型的入场和退出非常重要。

此外,一次只能进行一笔交易,这意味着如果之前由于上述条件而触发了入场,则在平仓或平仓之前不能再进行新的入场。

我不确定如何对其进行矢量化,因为我当前正在使用带有位置变量的 for 循环来在迭代每一行时进行跟踪。理想情况下,我需要的列应该只指定多头/空头比率进入和退出

pandas signals rolling-computation
1个回答
0
投票

此问题通常无法矢量化,因为标志的状态取决于先前的状态。例如,仓位 n 可以有一个“多头”标志,但这取决于仓位 n-5 是否也可以进行持续交易,而交易本身可能取决于仓位 n-12 等。

循环是处理这个问题的最佳方法,使用

numba
来编译它并进行高效处理:

from numba import jit

@jit(nopython=True)
def flag(a):
    ratio = None
    out = []
    for x in a:
        if ratio is None:
            if x > 2:
                ratio = 'long'
                out.append('Entry (long)')
            elif x < -2:
                ratio = 'short'
                out.append('Entry (short)')
            else:
                out.append(None)
        else:
            if ratio == 'long' and x <= 0.01:
                out.append('Exit (long)')
                ratio = None
            elif ratio == 'short' and x >= -0.01:
                out.append('Exit (short)')
                ratio = None
            else:
                out.append(None)
    return out
        
df['output'] = flag(df['Z Score'].to_numpy())

输出:

            Asset A  Asset B   Z Score         output
2023-01-05  33400.0  45.6781 -2.002516  Entry (short)
2023-01-06  34050.0  46.5457 -1.952896           None
2023-01-09  34800.0  48.0222 -2.157506           None
2023-01-10  35150.0  48.2774 -1.988247           None
2023-01-11  35600.0  48.6792 -1.856716           None
2023-02-21  37900.0  50.8524 -0.728916           None
2023-02-22  36600.0  49.7823 -1.021323           None
2023-02-23  37850.0  51.6347 -1.071015           None
2023-02-24  39300.0  50.7727  0.171235   Exit (short)
2023-02-27  38700.0  50.2548  0.050697           None
2023-02-28  38350.0  49.9594 -0.023634           None
© www.soinside.com 2019 - 2024. All rights reserved.