Home > database >  CandleChart with Bollinger bands not rendering
CandleChart with Bollinger bands not rendering

Time:08-20

I have here a MWE (minimum working example), that I fail to run? I can't found my error sadly.

The only thing that the consoler tells me is that there are too many ticks. But I don't understand why as there is only 3 months of data.

import yfinance as yf
from stockstats import StockDataFrame

# Convert to StockDataFrame
# Need to pass a copy of candlestick_data to StockDataFrame.retype
# Otherwise the original candlestick_data will be modified

df = yf.download('SPY',start='2017-04-23', end = '2017-07-01')
stockstats = StockDataFrame.retype(df)

# 5-day exponential moving average on closing price
ema_5 = stockstats["close_5_ema"]
# 20-day exponential moving average on closing price
ema_20 = stockstats["close_20_ema"]
# 50-day exponential moving average on closing price
ema_50 = stockstats["close_50_ema"]

# Upper Bollinger band
boll_ub = stockstats["boll_ub"]
# Lower Bollinger band
boll_lb = stockstats["boll_lb"]

# 7-day Relative Strength Index
rsi_7 = stockstats['rsi_7']
# 14-day Relative Strength Index
rsi_14 = stockstats['rsi_14']


import datetime
import matplotlib.pyplot as plt
from matplotlib.dates import date2num, WeekdayLocator, DayLocator, DateFormatter, MONDAY
from mplfinance.original_flavor import candlestick_ohlc

# Create a new Matplotlib figure
fig, ax = plt.subplots()

# Prepare a candlestick plot
candlestick_ohlc(ax, df.values, width=0.6)

# Plot stock indicators in the same plot
ax.plot(df.index, ema_5, lw=1, label='EMA (5)')
ax.plot(df.index, ema_20, lw=1, label='EMA (20)')
ax.plot(df.index, ema_50, lw=1, label='EMA (50)')
ax.plot(df.index, boll_ub, lw=2, linestyle="--", label='Bollinger upper')
ax.plot(df.index, boll_lb, lw=2, linestyle="--", label='Bollinger lower')
ax.xaxis.set_major_locator(WeekdayLocator(MONDAY)) # major ticks on

# the mondays
ax.xaxis.set_minor_locator(DayLocator()) # minor ticks on the days
ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d'))
ax.xaxis_date() # treat the x data as dates

# rotate all ticks to vertical
plt.setp(ax.get_xticklabels(), rotation=90, horizontalalignment='right')
ax.set_ylabel('Price (US $)') # Set y-axis label

# Limit the x-axis range from 2017-4-23 to 2017-7-1
datemin = datetime.date(2017, 4, 23)
datemax = datetime.date(2017, 7, 1)
ax.set_xlim(datemin, datemax)

plt.legend() # Show figure legend
plt.tight_layout()
plt.show()

CodePudding user response:

Ok i was able to make a workable MWE. For those interested here is the full working example:

import datetime as dt
import matplotlib.pyplot as plt
import matplotlib
import pandas_datareader as pdr
from mplfinance.original_flavor import candlestick_ohlc
import matplotlib.dates as mdates
import matplotlib.ticker as mticker
from stockstats import StockDataFrame


start = dt.datetime(2016,1,1)
end = dt.datetime(2016,3,28)    


df = pdr.data.DataReader('TSLA', 'yahoo', start, end)
df.drop('Adj Close', axis = 1, inplace = True)

stockstats = StockDataFrame.retype(df)
stockstats
# 5-day exponential moving average on closing price
ema_5 = stockstats["close_5_ema"]
ema_5 #pour voir le type de contenu
# 20-day exponential moving average on closing price
ema_20 = stockstats["close_20_ema"]
# 50-day exponential moving average on closing price
ema_50 = stockstats["close_50_ema"]
# Upper Bollinger band
boll_ub = stockstats["boll_ub"]
# Lower Bollinger band
boll_lb = stockstats["boll_lb"]
# 7-day Relative Strength Index
rsi_7 = stockstats['rsi_7']
# 14-day Relative Strength Index
rsi_14 = stockstats['rsi_14']

df.reset_index(inplace=True)
df["Date"] = mdates.date2num(df["Date"].values)
print(df.head())

cols = ['Date', 'open', 'high', 'low', 'close', 'volume']
df2 = df[cols] #reordering columns to OHLC order

fig, ax = plt.subplots()
candlestick_ohlc(ax, df2.values, width=0.4, colorup='#77d879', colordown='#db3f3f')
#on change la taille des polices des axes
matplotlib.rc('font', size=8)

ax.plot(df['Date'], ema_5, lw=1, label='EMA (5)')
ax.plot(df['Date'], ema_5, lw=1, label='EMA (5)')
ax.plot(df['Date'], ema_20, lw=1, label='EMA (20)')
ax.plot(df['Date'], ema_50, lw=1, label='EMA (50)')
ax.plot(df['Date'], boll_ub, lw=2, linestyle="--", label='Bollinger upper')
ax.plot(df['Date'], boll_lb, lw=2, linestyle="--", label='Bollinger lower')

ax.xaxis_date()
ax.grid(True, linestyle='--', linewidth=0.5)
plt.setp(ax.get_xticklabels(), rotation=90, horizontalalignment='right')

#nombre de jours sur l'axe des X
ax.xaxis.set_major_locator(mticker.MaxNLocator(20))
 
ax.set_ylabel('Price (US $)')
plt.title('Simple Trading plot')
plt.legend(loc=0,prop={'size': 7},frameon=False) # Show figure legend
plt.tight_layout()

plt.show()

The result gives:

enter image description here

  • Related