Conducting Stock Techinical Analysis with Candlestick, KD, Volume Chart
Stock Price Dataframe with Date, Open, High, Low, Close, Volume.
import matplotlib.pyplot as plt
import mpl_finance as mpf
def plot_candle_vol(df):
# Techinical Indicator
# Calculate the Moving Average
ma10 = talib.SMA(np.array(df['Close']), 10)
ma30 = talib.SMA(np.array(df['Close']), 30)
# Visualization
fig = plt.figure(figsize=(16, 8))
fig, (ax1, ax2) = plt.subplots(nrows=2, sharex=True,
figsize=(12, 8), gridspec_kw={'height_ratios': [3, 2]})
plt.subplots_adjust(hspace=0)
# Candlestick + MA
ax1.set_xticks(range(0, len(df.index), 30))
ax1.set_xticklabels(df.index[::30])
mpf.candlestick2_ochl(ax1, df['Open'],df['Close'], df['High'], df['Low'],
width=0.6, colorup='r', colordown='g', alpha=0.75)
ax1.plot(ma10, label='MA10')
ax1.plot(ma30, label='MA30')
ax1.legend()
ax1.set_xlabel('Date')
ax1.set_ylabel('Price')
ax1.set_title('S&P 500 Index')
## Volume Bar Chart
mpf.volume_overlay(ax2, df['Open'], df['Close'], df['Volume'], colorup='r', colordown='g', width=1, alpha=0.8)
ax2.set_xticks(range(0, len(df.index), 20))
ax2.set_xticklabels(df.index[::20])
ax2.set_ylabel('Volume')
plt.gcf().autofmt_xdate() # Beautify the x-labels
plt.autoscale(axis='x')
import matplotlib.pyplot as plt
import mpl_finance as mpf
def plot_candle_kd_vol(df):
# Format the datetime index
df.index = df.index.format(formatter=lambda x: x.strftime('%Y-%m-%d'))
# Techinical Indicator
# Calculate the Moving Average
sma_10 = talib.SMA(np.array(df['Close']), 10)
sma_30 = talib.SMA(np.array(df['Close']), 30)
# Calculate the KD Indicator
stoch_k, stoch_d = talib.STOCH(df['High'], df['Low'], df['Close'])
# Visualization
fig, (ax1, ax2, ax3) = plt.subplots(nrows=3, sharex=True,
figsize=(12, 8), gridspec_kw={'height_ratios': [5, 1, 3]})
plt.subplots_adjust(hspace=0)
## Candlestick
ax1.set_xticks(range(0, len(df.index), 20))
ax1.set_xticklabels(df.index[::20])
mpf.candlestick2_ochl(ax1, df['Open'], df['Close'], df['High'], df['Low'],
width=0.6, colorup='r', colordown='g', alpha=0.75);
ax1.set_xlabel('Date')
ax1.set_ylabel('Price')
ax1.set_title('S&P 500 Index')
## Candlestick + MA
ax1.plot(sma_10, label='MA10')
ax1.plot(sma_30, label='MA30')
ax1.legend()
## KD Indicator
ax2.plot(df.index, stoch_k, label='K')
ax2.plot(df.index, stoch_d, label='D')
ax2.legend()
ax2.set_ylabel('KD Indicator')
## Volume Bar Chart
mpf.volume_overlay(ax3, df['Open'], df['Close'], df['Volume'], colorup='r', colordown='g', width=1, alpha=0.8)
ax3.set_xticks(range(0, len(df.index), 20))
ax3.set_xticklabels(df.index[::20])
ax3.set_ylabel('Volume')
plt.gcf().autofmt_xdate() # Beautify the x-labels
plt.autoscale(axis='x')