Python Forum

Full Version: RSI not Working
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello everyone! In need of help to figure out what's not working with below code. The idea is to calculate a stock RSI by pulling data from Yahoo finance. Thanks for helping.
import time
import datetime
import numpy as np
import yfinance as yf
# Get the data for the stock AAPL
data = yf.download('TSLA','2019-01-01','2019-12-31')

def rsiFunc(prices, n=14):
    deltas = np.diff(prices(data['Adj Close']))
    seed = deltas[:n+1]
    up = seed[seed>=0].sum()/n
    down = -seed[seed<0].sum()/n
    rs = up/down
    rsi = 0
    rsi = np.zeros_like(prices)
    rsi[:n] = 100. - 100./(1.+rs)

    for i in range(n, len(prices)):
        delta = deltas[i-1] # cause the diff is 1 shorter

        if delta>0:
            upval = delta
            downval = 0.
        else:
            upval = 0.
            downval = -delta

        up = (up*(n-1) + upval)/n
        down = (down*(n-1) + downval)/n

        rs = up/down
        rsi[i] = 100. - 100./(1.+rs)

    return rsi
print(rsi)
After running, getting error message:
Error:
Traceback (most recent call last): File "C:/Users/.../Desktop/rsi.py", line 35, in <module> print(rsi) NameError: name 'rsi' is not defined
That variable is local to the function. Perhaps you need to remind yourself how scope works? Besides that, you're not even calling the function anywhere.
Thank you for your feedback and for pointing out to me what I was missing. Below is my reworked code:
import numpy as np
import yfinance as yf
# Get the data for the stock AAPL
data = yf.download('TSLA','2019-12-01','2019-12-31')

def rsiFunc(prices, n):
    deltas = np.diff(prices)
    seed = deltas[:n+1]
    up = seed[seed>=0].sum()/n
    down = -seed[seed<0].sum()/n
    rs = up/down
    rsi = 0
    rsi = np.zeros_like(prices)
    rsi[:n] = 100. - 100./(1.+rs)

    for i in range(n, len(prices)):
        delta = deltas[i-1] # cause the diff is 1 shorter

        if delta>0:
            upval = delta
            downval = 0.
        else:
            upval = 0.
            downval = -delta

        up = (up*(n-1) + upval)/n
        down = (down*(n-1) + downval)/n

        rs = up/down
        rsi[i] = 100. - 100./(1.+rs)

    return rsi
#calling rsiFunc:
if __name__ == "__main__":
    rsi_val = rsiFunc(data['Adj Close'], 10)
    print(rsi_val)
This is what i get:
[output]
[84.80592594 84.80592594 84.80592594 84.80592594 84.80592594 84.80592594
 84.80592594 84.80592594 84.80592594 84.80592594 89.18678822 86.18786921
 88.59227928 90.06948866 90.26877071 91.86402956 92.47075679 93.01675838
 92.28493787 74.13806357 75.38320234]
[/output]