2023/08/08

python 으로 주봉, 월봉 기준으로 RSI값 계산하기

python을 활용해 해외주식(국내도 물론 가능)의 과거 가격변동 내역과 통계성 수치(rsi, macd, bollinger band 등)를 가져올 수 있다.

통계성 수치들은 공식을 알고 직접 계산도 가능하지만, ta모듈을 사용하면 손쉽게 값을 계산할 수 있다.

rsi값을 계산할때 보통 14일 범위로 해서 일봉 기준으로 계산을 하는데, DataFrame.resample 함수를 사용하면 주봉/월봉 기준으로도 손쉽게 rsi값을 계산할 수 있다.
import yfinance as yf
import pandas as pd
import ta
from datetime import datetime, timezone, timedelta
import os

period = '20y'

# target tickers
stocks = ['AAPL','MSFT','KO','TSLA','MMM']
data = yf.download(stocks, period=period, rounding=True, ignore_tz=True)
df = data['Close']

# make data with 365days
days = [df.index[0] + timedelta(days=i) for i in range((df.index[-1] - df.index[0]).days + 1)]
df_days = pd.DataFrame(days)
df_days.index = days

df = pd.concat([df, df_days], axis=1)
df = df.fillna(method='ffill')[stocks]

# rsi, bollinger band
stat = {}
window, window_dev = 14, 2

for ticker in stocks:
    stat[ticker] = {}
    t = data['Close'][ticker]
    
    # resample weekly, monthly
    t_week = t.resample('W-FRI').last()
    t_month = t.resample('M').last()

    # simple moving average (120d, 200d)
    sma120 = ta.trend.sma_indicator(t, window=120, fillna=True)[-1]
    sma200 = ta.trend.sma_indicator(t, window=200, fillna=True)[-1]

    # normalize sma
    stat[ticker]['SMA120'] = t[-1] / sma120
    stat[ticker]['SMA200'] = t[-1] / sma200

    # dataframe column
    stat[ticker]['RSI'] = ta.momentum.rsi(t)[-1]
    stat[ticker]['RSI.W'] = ta.momentum.rsi(t_week)[-1]
    stat[ticker]['RSI.M'] = ta.momentum.rsi(t_month)[-1]
    stat[ticker]['BB.P'] = ta.volatility.bollinger_pband(t, window, window_dev, True)[-1] * 100
    stat[ticker]['BB.W'] = ta.volatility.bollinger_wband(t, window, window_dev, True)[-1]

df_stat = pd.DataFrame(data=stat)[::-1]
df = pd.concat([df, df_stat]).iloc[::-1].T

# export to excel file
writer = pd.ExcelWriter('price.xlsx', engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet1')
writer.close()

os.startfile("price.xlsx")
  

resample 함수와 인자(파라미터)에 대한 자세한 설명은 여기에서.

https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.resample.html#
https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#dateoffset-objects

댓글 없음:

댓글 쓰기