递减范围内的乘积之和

时间:2018-08-01 19:05:03

标签: python pandas math vectorization

我正在实现一个小的Python应用程序来衡量交易策略的收益。计算收益的函数需要以下输入:

  • 包含收盘价的熊猫数据框
  • 熊猫的一系列布尔值,表示购买信号
  • 熊猫的一系列布尔信号,代表卖出信号
  • 代表交易费用占初始资本百分比的浮动货币

这是数据的样子:

>>> df.head()
            open  high   low  close  volume
date                                       
2015-01-02  5.34  5.37  5.11   5.21  108469
2015-01-05  5.21  5.26  4.85   4.87  160089
2015-01-06  4.87  4.87  4.55   4.57  316501
2015-01-07  4.63  4.75  4.60   4.67  151117
2015-01-08  4.69  4.89  4.69   4.81  159294
>>> 

>>> buy.head()
2015-01-02     True
2015-01-05    False
2015-01-06    False
2015-01-07    False
2015-01-08    False
dtype: bool
>>>

不考虑费用,这是计算比率的公式:

C是初始资本,ri是一次买卖交易的回报。

可以使用向量化的实现轻松实现:

buy_sell = df[(buy==True)|(sell==True)]
prices = buy_sell.close
diffs = prices - prices.shift()
ratios = diffs / prices.shift()
return ((ratios + 1).product(axis=0))

当需要考虑费用时,我得出以下公式:

enter image description here

f是交易费。

可以很容易地使用循环来实现,但是有没有办法通过矢量化实现来实现?

我不是数学专家,但是依赖于总和的乘积可能会阻止这种情况吗?我尝试过在线查找此属性,但似乎找不到任何东西。也许由于我缺乏技术术语,所以我没有正确地提出问题。

任何对此的感激:)


编辑

从帝斯曼的答案来看,解决方案是对一系列相反的比率执行“累积乘积”。这给了我以下解决方案:

def compute_return(df, buy, sell, fees=0.):

    # Bunch of verifications operation performed on data

    buy_sell = df[(buy==True)|(sell==True)]
    prices = buy_sell.close
    diffs = prices - prices.shift()
    ratios = diffs / prices.shift()

    cum_prod = (ratios + 1)[1:][::-1].cumprod()

    return ((1 - fees) * (ratios + 1).product(axis=0) - fees * cum_prod.sum())

1 个答案:

答案 0 :(得分:1)

我认为这还不错。来自ratios之类的

In [95]: ratios
Out[95]: 
date
2015-01-02         NaN
2015-01-05   -0.065259
2015-01-06   -0.061602
2015-01-07    0.021882
2015-01-08    0.029979
Name: close, dtype: float64

我们拥有(这里我们只关注“新”第二个学期):

def manual(rs):
    return sum(np.prod([1+rs.iloc[j] for j in range(i, len(rs))]) 
               for i in range(2, len(rs)))

def vectorized(rs):
    rev = 1 + rs.iloc[2:].iloc[::-1]
    return rev.cumprod().sum()

也就是说,我们要做的就是从头到尾取反方向上的累计乘积之和。

这给了我

In [109]: manual(ratios)
Out[109]: 3.07017466956023

In [110]: vectorized(ratios)
Out[110]: 3.07017466956023

(我没有过多地担心我们是否应该在此处使用2或1作为偏移量,还是放入f因子-这些都是很容易的更改。)

相关问题