Skip to content

Instantly share code, notes, and snippets.

@AlKun25
Created March 31, 2021 07:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AlKun25/c520c4315e6f41acfdba0279cdf82c82 to your computer and use it in GitHub Desktop.
Save AlKun25/c520c4315e6f41acfdba0279cdf82c82 to your computer and use it in GitHub Desktop.
Data visualization of RSI with stock prices
import yfinance as yf
import plotly.graph_objects as go
import plotly.express as px
ge = yf.Ticker('GE')
old = ge.history(start="2020-01-01", end="2021-03-10")
old.reset_index(inplace=True)
def computeRSI (data, time_window):
diff = data.diff(1).dropna() # diff in one field(one day)
#this preservers dimensions off diff values
up_chg = 0 * diff
down_chg = 0 * diff
# up change is equal to the positive difference, otherwise equal to zero
up_chg[diff > 0] = diff[ diff>0 ]
# down change is equal to negative deifference, otherwise equal to zero
down_chg[diff < 0] = diff[ diff < 0 ]
# check pandas documentation for ewm
# https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.ewm.html
# values are related to exponential decay
# we set com=time_window-1 so we get decay alpha=1/time_window
up_chg_avg = up_chg.ewm(com=time_window-1 , min_periods=time_window).mean()
down_chg_avg = down_chg.ewm(com=time_window-1 , min_periods=time_window).mean()
rs = abs(up_chg_avg/down_chg_avg)
rsi = 100 - 100/(1+rs)
return rsi
old['RSI'] = computeRSI(old['Close'], 14)
print(old.head())
print(old.tail())
fig1 = px.line(old, x="Date", y="RSI", title='GE Stock Prices')
fig2 = go.Candlestick(x=old['Date'],open=old['Open'],high=old['High'],low=old['Low'],close=old['Close'])
# fig2.update_layout(title="GE Stock Prices", yaxis_title='GE Stock', )
fig1.add_trace(fig2)
fig1.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment