Python - with BIAS & RSI
from pandas_datareader import data as web
from mpl_finance import candlestick_ohlc
from matplotlib import pyplot as plt
from matplotlib import style
import matplotlib.dates as mdates
import yfinance as yf
import datetime as dt
import pandas as pd
import numpy as np
import time
style.use('dark_background')
yf.pdr_override()
ma1 = 5
ma2 = 20
print('Stock Number:')
stock_no = input()
csv_file = '/users/jht/Desktop/python/stockData/'+stock_no+'.csv'
start = dt.datetime(2020, 1, 1)
end = dt.datetime.now()
df = web.get_data_yahoo(stock_no + '.TW', start, end)
df.to_csv(csv_file)
time.sleep(2)
data = pd.read_csv(csv_file, parse_dates=True, index_col='Date')
data.head()
close = data["Close"]
avg = sum(close)/len(close)
top = plt.subplot2grid((21, 9), (0, 0), rowspan=9, colspan=9)#整個畫面共有(21row,9col),其位於(0row,0col),此占各9row&col
bottom = plt.subplot2grid((21, 9), (12, 0), rowspan=3, colspan=9, sharex=top)
bottom1 = plt.subplot2grid((21, 9), (18, 0), rowspan=3, colspan=9, sharex=top)
def bias(ma):
data['MA25'] = data['Close'].rolling(window=ma).mean()
data['BIAS'] = (data['Close'] - data['MA25']) / data['MA25'] * 100
return data['BIAS']
def rsi(price, period=6):
import pandas as pd
closedif = (price - price.shift(1)).dropna()
upprc = pd.Series(0, index=closedif.index)
upprc[closedif > 0] = closedif[closedif > 0]
downprc = pd.Series(0, index=closedif.index)
downprc[closedif < 0] = - closedif[closedif < 0]
rsi = []
for i in range(period, len(upprc) + 1):
up_mean = np.mean(upprc.values[(i - period):i], dtype=np.float32)
up_down = np.mean(downprc.values[(i - period):i], dtype=np.float32)
rsi.append(100 * up_mean / (up_mean + up_down))
rsi = pd.Series(rsi, index=closedif.index[(period - 1):])
return (rsi)
bias = bias(5)
rsi1 = rsi(close, ma1)
rsi1.tail()
rsi2 = rsi(close, ma2)
rsi2.tail()
moving_avg1= close.rolling(ma1).mean()
moving_avg2 = close.rolling(ma2).mean()
data = data.reset_index()
data['Date'] = data['Date'].apply(lambda d: mdates.date2num(d.to_pydatetime()))
candlestick = [tuple(x) for x in data[['Date', 'Open', 'High', 'Low', 'Close']].values]
candlestick_ohlc(top, candlestick, width=0.7, colorup='r', colordown='green', alpha=0.8)
top.plot(moving_avg1, color='orange', linewidth=1, alpha=0.7, label=ma1)
top.plot(moving_avg2, color='b', linewidth=1, alpha=0.7, label=ma2)
top.axhline(avg,color='r', alpha=0.3,label='avg')
top.legend()
top.grid(which='both', alpha=0.3)
top.set_title('Stock No: '+ stock_no,color='y')
top.set_ylabel(str(round(avg,5)),color='r', alpha=0.3)
bottom.plot(rsi1, color='orange', linewidth=1, alpha=0.7)
bottom.plot(rsi2, color='b', linewidth=1, alpha=0.7)
bottom.axhline(70, color='gray', alpha=0.3)
bottom.axhline(30, color='gray', alpha=0.3)
bottom.set_ylim(-10, 110)
bottom.set_title('RSI')
bottom1.plot(bias)
bottom1.axhline(0, color='r', alpha=0.3)
bottom1.set_title('BIAS(price vs MA5)')
plt.xlabel('Design by Eve',color='gray',fontsize='7', alpha=0.8)
plt.show()
Comments
Post a Comment