pandas 实现通达信里的MFI

算法里的关键点: combine()和rolling().sum()方法

combine -- 综合运算, rolling().sum() -- 滚动求和

利用pd.Series的combine()方法, 可以对给定的两个序列执行元素级的操作.

该方法的签名为:
Series.combine(self, other, func, fill_value=nan)

这里的func参数通常是一个lambda表达式:

比如: lambda x1, x2: 1.0 if x1>x2 else 0.0

利用自定义的lambda表达式, 确定资金流的方向(正向/负向资金流)

def mfi(ohlc, n=14):
    u'''
    通达信里的MFI公式:
    TYP := (HIGH + LOW + CLOSE)/3;
    V1:=SUM(IF(TYP>REF(TYP,1),TYP*VOL,0),N)/SUM(IF(TYP<REF(TYP,1),TYP*VOL,0),N);
    MFI:100-(100/(1+V1));
    
    '''
    typ = (ohlc.high + ohlc.low + ohlc.close)/3.    
    lp = typ.shift(1).fillna(method='bfill')
    mf = typ * ohlc.volume
    # positive money flow
    positive = typ.combine(lp, lambda x1,x2: 1.0 if x1>x2 else 0.0)
    negitive = typ.combine(lp, lambda x1,x2: 1.0 if x1<x2 else 0.0)
    pmf = mf * positive
    nmf = mf * negitive
    pmf, nmf = pmf.rolling(n).sum(), nmf.rolling(n).sum()
    # 相对强弱
    rs = pmf/nmf
    out = 100.0 - 100.0/(1+rs)
    return out