美文网首页量化交易量化交易技术
量化交易中指标RSI的Python代码实现

量化交易中指标RSI的Python代码实现

作者: 北冥Master | 来源:发表于2018-03-27 14:56 被阅读35次

    最近在学习量化交易,需要自己实现RSI指标,参考了TA-LIB的实现方式。
    RSI英文全称:Relative Strength Index
    RSI中文名称:相对强弱指数
    是衡量价格波动的一个重要指标。

    计算公式

    UP_AVG = UP_AMOUNT/PERIODS (周期内上涨数量平均)
    DOWN_AVG = DOWN_AMOUNT/PERIODS(周期内下跌数量平均)
    RS = UP_AVG/DOWN_AVG(相对平均)
    RSI  = 100 - 100 / (1 + RS)  (相对强弱指数)
    

    快速计算公式

    利用前一个UP_AVG, DOWN_AVG快速计算当前UP_AVG, DOWN_AVG

    UP_AVG = (UP_AVG_PREV * (PERIODS - 1) + UP) / PERIODS
    DOWN_AVG = (UP_AVG_PREV * (PERIODS - 1) + DOWN) / PERIODS
    RS = UP_AVG/DOWN_AVG
    RSI  = 100 - 100 / (1 + RS)  
    

    Python代码实现

    def RSI(t, periods=10):
        length = len(t)
        rsies = [np.nan]*length
        #数据长度不超过周期,无法计算;
        if length <= 10:
            return rsies
        #用于快速计算;
        up_avg = 0
        down_avg = 0
    
        #首先计算第一个RSI,用前periods+1个数据,构成periods个价差序列;
        first_t = t[:periods+1]
        for i in range(1, len(first_t)):
            #价格上涨;
            if first_t[i] >= first_t[i-1]:
                up_avg += first_t[i] - first_t[i-1]
            #价格下跌;
            else:
                down_avg += first_t[i-1] - first_t[i]
        up_avg = up_avg / periods
        down_avg = down_avg / periods
        rs = up_avg / down_avg
        rsies[periods] = 100 - 100/(1+rs)
    
        #后面的将使用快速计算;
        for j in range(periods+1, length):
            up = 0
            down = 0
            if t[j] >= t[j-1]:
                up = t[j] - t[j-1]
                down = 0
            else:
                up = 0
                down = t[j-1] - t[j]
            #类似移动平均的计算公式;
            up_avg = (up_avg*(periods - 1) + up)/periods
            down_avg = (down_avg*(periods - 1) + down)/periods
            rs = up_avg/down_avg
            rsies[j] = 100 - 100/(1+rs)
        return rsies  
    

    相关文章

      网友评论

      • 00f5b696ebc8:我也贡献一下用pandas的写法

        def RSI(df, period=14):
        """
        Relative Strength Index
        """
        series = df['close']
        delta = series.diff().dropna()
        u = delta * 0
        d = u.copy()
        u[delta > 0] = delta[delta > 0]
        d[delta < 0] = -delta[delta < 0]
        u[u.index[period - 1]] = np.mean(u[:period]) # first value is sum of avg gains
        u = u.drop(u.index[:(period - 1)])
        d[d.index[period - 1]] = np.mean(d[:period]) # first value is sum of avg losses
        d = d.drop(d.index[:(period - 1)])
        avgGain = u.ewm(com=period - 1, adjust=False).mean()
        avgLoss = d.ewm(com=period - 1, adjust=False).mean()
        rs = avgGain / avgLoss
        result = 100 - 100 / (1 + rs)
        return result
      • IT人故事会:我会持续关注的!

      本文标题:量化交易中指标RSI的Python代码实现

      本文链接:https://www.haomeiwen.com/subject/bwzjcftx.html