import yfinance as yf
import numpy as np
import matplotlib.pyplot as plt
from statsmodels.graphics.tsaplots import plot_acf, plot_pacf
from statsmodels.tsa.arima.model import ARIMA as arima
import ta
import seaborn as sb
import pandas as pd
from datetime import datetime as dt
from datetime import timedelta
Download stock prices from Yahoo Finance
= dt.now()
end_time = end_time - timedelta(days=365*2)
start_time = 'SPY, MSFT, META, NVDA, AMD'
tickers = yf.download(tickers, start = start_time, end = end_time) popular5
[*********************100%%**********************] 5 of 5 completed
Calculate indicators Bollinger Bands & RSI, buy/sell
points, and visualize
def calculate_indicators(historical_close):
= historical_close.rolling(20).mean()
historical_close_ma20 = historical_close.rolling(20).std()
std = historical_close_ma20 + 2* std
upper = historical_close_ma20 - 2*std
lower = ta.momentum.rsi(historical_close, 14)
rsi14 # put indicators in a dataframe
= pd.concat([historical_close, upper, lower, rsi14], axis=1)
df = ['close','upper','lower','rsi']
df.columns 'signal']='no action'
df['close'] < df['lower']) & (df['rsi']<30), 'signal'] = 'buy'
df.loc[(df[>df.upper) & (df.rsi > 70), 'signal'] = 'sell'
df.loc[(df.close# print(df.query('signal == "buy"').shape[0])
# print(df.query('signal == "sell"').shape[0])
# visualize
= plt.figure(figsize = (15,6))
fig = fig.add_axes([0.1,0.1,0.9,0.9])
ax = 'daily close')
ax.plot(historical_close.index, historical_close.values, label
ax.plot(historical_close_ma20.index, historical_close_ma20.values)='upper Bollinger')
ax.plot(upper.index, upper.values, label='lower Bollinger')
ax.plot(lower.index, lower.values, label
= ax.twinx()
ax2 =0.3)
ax2.plot(rsi14, alpha=70, ls='--', alpha=0.5, c='r')
ax2.axhline(y=30, ls='--', alpha=0.5, c='g')
ax2.axhline(yf'{symbol} Prices & Indicators', fontsize=25)
ax.set_title('RSI', fontsize=15)
ax2.set_ylabel('Price', fontsize=15)
ax.set_ylabel(=15)
ax.xaxis.set_tick_params(labelsize=15)
ax.yaxis.set_tick_params(labelsize=15)
ax2.yaxis.set_tick_params(labelsize
ax.legend()# draw arrow
= {'buy':'green', 'sell':'red'}
signal_colors # signal_offsets = {'buy':pd.Timedelta(days=-40), 'sell':pd.Timedelta(days=40)}
= {'buy':-20, 'sell':20}
y_offsets = {'buy':pd.Timedelta(days=-40), 'sell':pd.Timedelta(days=40)}
signal_offsets for signal, color in signal_colors.items():
= df[df['signal']==signal]
signal_data ='o', s=90, c=color, label=signal)
ax.scatter(signal_data.index, signal_data.close, marker= signal_data.replace(signal_offsets)
time_deltas = signal_data.close - 1
y_ends for i, row in signal_data.iterrows():
= i
x_end # x_start = x_end + time_deltas['signal'].loc[i]
= x_end + pd.Timedelta(days=-40)
x_start = y_ends[i] + y_offsets[signal]
y_start = y_ends[i]
y_end =(x_end, y_end), xytext=(x_start, y_start), arrowprops=
ax.annotate(signal_data.signal[i], xydict(facecolor=signal_colors[row['signal']], shrink=0.1, lw=2))
Pick a stock
= 'SPY'
symbol = popular5['Close'][symbol]
ts calculate_indicators(ts)
= ts.pct_change()*100
returns 1:], zero=False, auto_ylims=True); plot_pacf(returns[
Calculate returns
=False
position= 1.0
portfolio_value for index, row in df_tsla.iterrows():
if not position and row.signal == 'buy':
= True
position = row.close
entry if position:
if (row.signal == 'sell' or row.close < entry*0.9):
= False
position = row.close
exit *= (exit - entry)/entry + 1
portfolio_value
print(f'return = {portfolio_value}')
return = 3.412705492910159
Pages: 1 2