3 votos

¿Cómo se calcula la RSI?

He escrito un código en python que creo que calcula el RSI. Escribí el código basado en lo que vi en stockcharts.com se encuentra aquí

Aquí está el código:

def getRSI(close, n=14):
    """
    Computes the Relative Strength Index of a trend
    :param close: closing prices
    :param n: lookback period
    :return: a np array containing the RSI for all periods spanning 
closing price data
    """

# compute a vector for change between daily closing prices
change = np.zeros(len(close))
for i in range(1, len(close)):
    change[i] = close[i-1] - close[i]

# compute a vector of gains and losses
gain = np.zeros(len(close))
loss = np.zeros(len(close))

for i in range(1, len(close)):
    if change[i] >= 0:
        gain[i] = change[i]
    else:
        loss[i] = math.fabs(change[i])

avg_gain = np.zeros(len(close))
avg_loss = np.zeros(len(close))

avg_gain[n] = np.average(gain[0:n])
avg_loss[n] = np.average(loss[0:n])

for i in range(n, len(close)):
    avg_gain[i] = (avg_gain[i-1]*(n-1) + gain[i])/n
    avg_loss[i] = (avg_loss[i-1]*(n-1) + loss[i])/n

RS = np.zeros(len(close))
for i in range(n, len(close)):
    RS[i] = avg_gain[i]/avg_loss[i]

RSI = np.zeros(len(close))
for i in range(n, len(close)):
    RSI[i] = 100 - (100/(1+RS[i]))

return RSI

Intenté calcular el RSI de COP para los precios a partir del 26 de noviembre de 2006 hasta el 26 de noviembre de 2018. Pero la curva que obtengo es completamente diferente a la que veo en Yahoo Finance o incluso en StockCharts. ¿Qué estoy haciendo mal?

5voto

dmuir Puntos 146

He corregido tu código para que funcione como debería. Este código podría limpiarse mucho. Sólo he ajustado su código existente para que sea capaz de entenderlo. He añadido algunos comentarios precedidos por ## en las líneas que fueron cambiadas. Vea abajo.

import numpy as np
from math import fabs

def getRSI(close, n=14):

    # compute a vector for change between daily closing prices
    change = np.zeros(len(close))
    for i in range(1, len(close)):        
        change[i] = close[i] - close[i-1] ##Reversed the order of these.

    # compute a vector of gains and losses
    gain = np.zeros(len(close))
    loss = np.zeros(len(close))

    for i in range(1, len(close)):
        if change[i] >= 0:
            gain[i] = change[i]
            loss[i] = 0.00 ##Each array element needs a value.
        else:
            gain[i] = 0.00 ##Each array element needs a value.
            loss[i] = fabs(change[i])

    avg_gain = np.zeros(len(close) - n) ##Array length was wrong.
    avg_loss = np.zeros(len(close) - n) ##Array length was wrong.

    avg_gain[0] = np.average(gain[1:n+1]) ##First array element has a different calculation.
    avg_loss[0] = np.average(loss[1:n+1]) ##First array element has a different calculation.

    for i in range(1, len(close) - n): ##Loop counter was wrong.
        avg_gain[i] = (avg_gain[i-1]*(n-1) + gain[i+n])/n ##Indexes were wrong.
        avg_loss[i] = (avg_loss[i-1]*(n-1) + loss[i+n])/n ##Indexes were wrong.

    RS = np.zeros(len(close) - n) ##Array length was wrong.
    for i in range(0, len(close) - n): ##Loop counter was wrong.
        RS[i] = avg_gain[i]/avg_loss[i]

    RSI = np.zeros(len(close) - n) ##Array length was wrong.
    for i in range(0, len(close) - n): ##Loop counter was wrong.
        if avg_loss[i] == 0: ##This was missing. Could throw an error without it.
            RSI[i] = 100
        else:
            RSI[i] = 100 - (100/(1+RS[i]))

    return RSI

Finanhelp.com

FinanHelp es una comunidad para personas con conocimientos de economía y finanzas, o quiere aprender. Puedes hacer tus propias preguntas o resolver las de los demás.

Powered by:

X