def weekday_candlestick(ohlc_data, ax, fmt='%b %d', freq=7, **kwargs): """ Wrapper function for matplotlib.finance.candlestick_ohlc that artificially spaces data to avoid gaps from weekends 去除非交易时间的空隙 fmt: 日期格式 freq: 日期显示的间隔 """ freq = int(freq) # Convert data to numpy array ohlc_data_arr = np.array(ohlc_data) ohlc_data_arr2 = np.hstack( [np.arange(ohlc_data_arr[:,0].size)[:,np.newaxis], ohlc_data_arr[:,1:]]) ndays = ohlc_data_arr2[:,0] # array([0, 1, 2, ... n-2, n-1, n]) # Convert matplotlib date numbers to strings based on `fmt` dates = mdates.num2date(ohlc_data_arr[:,0]) date_strings = [] for date in dates: date_strings.append(date.strftime(fmt)) # Plot candlestick chart mpf.candlestick_ohlc(ax, ohlc_data_arr2, **kwargs) # Format x axis ax.set_xticks(ndays[::freq]) ax.set_xticklabels(date_strings[::freq], rotation=45, ha='right') ax.set_xlim(ndays.min(), ndays.max())
def main(): days = readstkData(daylinefilespath, stock_b_code, startdate, enddate) # 日期从dateframe指数下降 daysreshape = days.reset_index() # 转换浮点数 daysreshape['DateTime'] = mdates.date2num(daysreshape['DateTime'].astype( dt.date)) # 整理数据,为了展示K线的阴线和阳线使用matplotlib的蜡烛图 daysreshape.drop('Volume', axis=1, inplace=True) daysreshape = daysreshape.reindex( columns=['DateTime', 'Open', 'High', 'Low', 'Close']) Av1 = movingaverage(daysreshape.Close.values, MA1) Av2 = movingaverage(daysreshape.Close.values, MA2) SP = len(daysreshape.DateTime.values[MA2 - 1:]) fig = plt.figure(facecolor='#07000d', figsize=(15, 10)) ax1 = plt.subplot2grid((6, 4), (1, 0), rowspan=4, colspan=4, axisbg='#07000d') candlestick_ohlc(ax1, daysreshape.values[-SP:], width=.6, colorup='#ff1717', colordown='#53c156') Label1 = str(MA1) + ' SMA' Label2 = str(MA2) + ' SMA' ax1.plot(daysreshape.DateTime.values[-SP:], Av1[-SP:], '#e1edf9', label=Label1, linewidth=1.5) ax1.plot(daysreshape.DateTime.values[-SP:], Av2[-SP:], '#4ee6fd', label=Label2, linewidth=1.5) ax1.grid(True, color='w') ax1.xaxis.set_major_locator(mticker.MaxNLocator(10)) ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d')) ax1.yaxis.label.set_color("w") ax1.spines['bottom'].set_color("#5998ff") ax1.spines['top'].set_color("#5998ff") ax1.spines['left'].set_color("#5998ff") ax1.spines['right'].set_color("#5998ff") ax1.tick_params(axis='y', colors='w') plt.gca().yaxis.set_major_locator(mticker.MaxNLocator(prune='upper')) ax1.tick_params(axis='x', colors='w') plt.ylabel('Stock price and Volume') plt.show()
def prepare(self, chart_data): # 캔버스를 초기화하고 4개의 차트를 그릴 준비 self.fig, self.axes = plt.subplots(nrows=4, ncols=1, facecolor='w', sharex=True) for ax in self.axes: # 보기 어려운 과학적 표기 비활성화 ax.get_xaxis().get_major_formatter().set_scientific(False) ax.get_yaxis().get_major_formatter().set_scientific(False) # 차트 1. 일봉 차트 self.axes[0].set_ylabel('Env.') # y 축 레이블 표시 #거래량 가시화 x = np.arange(len(chart_data)) volume = np.array(chart_data)[:, -1].tolist() self.axes[0].bar(x, volume, color='b', alpha=0.3) #OHLC = open high low close ax = self.axes[0].twinx() ohlc = np.hstack((x.reshape(-1, 1), np.array(chart_data)[:, 1:-1])) candlestick_ohlc(ax, ohlc, colorup='r', colordown='b')
rate_increase_in_vol.append(df.iloc[i]['Volume']-df.iloc[i-1]['Volume']) rate_increase_in_close.append(df.iloc[i]['Close']-df.iloc[i-1]['Close']) i+=1 df['Increase_in_vol']=rate_increase_in_vol df['Increase_in_close']=rate_increase_in_close df['Increase_in_vol'].plot() df['Increase_in_close'].plot() df_ohlc= df['Close'].resample('10D').ohlc() df_volume=df['Volume'].resample('10D').sum() df_ohlc.reset_index(inplace=True) df_ohlc['Date']=df_ohlc['Date'].map(mdates.date2num) ax1=plt.subplot2grid((6,1), (0,0), rowspan=5, colspan=1) ax2=plt.subplot2grid((6,1), (5,0), rowspan=1, colspan=1 , sharex=ax1) ax1.xaxis_date() candlestick_ohlc(ax1,df_ohlc.values, width=2, colorup='g') ax2.fill_between(df_volume.index.map(mdates.date2num),df_volume.values,0) # # df3=df df3.fillna(0, inplace=True) y_df=df3[['Close','Volume']] col_y=y_df.columns y_df=df3[['Close','Volume']] y_df_mod=y_df.drop(['Close','Volume'],axis=1) y_df_mod.column Drop_cols=col_y Drop_cols=Drop_cols.tolist() Drop_cols.append('Date') X_df=df3.drop(Drop_cols,axis=1) X_df.columns
ema60 = df.close.ewm(span=60).mean() # ① 종가의 12주 지수 이동평균 ema130 = df.close.ewm(span=130).mean() # ② 종가의 12주 지수 이동평균 macd = ema60 - ema130 # ③ MACD선 signal = macd.ewm(span=45).mean() # ④ 신호선(MACD의 9주 지수 이동평균) macdhist = macd - signal # ⑤ MACD 히스토그램 df = df.assign(ema130=ema130, ema60=ema60, macd=macd, signal=signal, macdhist=macdhist).dropna() df['number'] = df.index.map(mdates.date2num) # ⑥ ohlc = df[['number','open','high','low','close']] plt.figure(figsize=(9, 7)) p1 = plt.subplot(2, 1, 1) plt.title('Triple Screen Trading - First Screen (아이에스동서)') plt.grid(True) candlestick_ohlc(p1, ohlc.values, width=.6, colorup='red', colordown='blue') # ⑦ p1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m')) plt.plot(df.number, df['ema130'], color='c', label='EMA130') plt.legend(loc='best') p2 = plt.subplot(2, 1, 2) plt.grid(True) p2.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m')) plt.bar(df.number, df['macdhist'], color='m', label='MACD-Hist') plt.plot(df.number, df['macd'], color='b', label='MACD') plt.plot(df.number, df['signal'], 'g--', label='MACD-Signal') plt.legend(loc='best') plt.show()
quotes = [(1312323, 18.00, 190, 100, 99, 5454545)] # print(np.random.randint((10, 50, 2))) dates = np.array([]) volumns = np.array([]) for item in quotes: dates = np.append(dates, item[0]) volumns = np.append(volumns, item[5]) left, width = 0.1, 0.8 rect_vol = [left, 0.1, width, 0.26] rect_main = [left, 0.4, width, 0.5] fig = plt.figure() ax_vol = fig.add_axes(rect_vol) ax_vol.fill_between(dates, volumns, color='y') ax_vol.xaxis_date() plt.setp(ax_vol.get_xticklabels(), rotation=30, horizontalalignment='right') ax_main = fig.add_axes(rect_main) ax_main.axes.get_xaxis().set_visible(False) # 绘制股票K线图 candlestick_ohlc(ax_main, quotes, width=0.6, colorup='r', colordown='g') ax_main.set_title('Stock INTC Price and Volumn') plt.show()
def main(): days = get_data('000001.SZ', start_date, '2020-06-30') data = days.reset_index() data['trade_date'] = mdates.date2num(data['trade_date']) data.drop(['ts_code', 'change', 'pct_chg', 'vol', 'amount', 'pre_close'], axis=1, inplace=True) data = data.reindex(columns=['trade_date', 'open', 'high', 'low', 'close']) ''' data.drop(['ts_code', 'change', 'pct_chg', 'amount', 'pre_close'], axis=1, inplace=True) # data = data.reindex(columns=['Date', 'Open', 'High', 'Low', 'Close','Volume']) show_func(data.head()) ''' Av1 = talib.MA(data.close.values, MA1) Av2 = talib.MA(data.close.values, MA2) # Av1 = movingaverage(data.close.values, MA1) # Av2 = movingaverage(data.close.values, MA2) SP = len(data.trade_date.values[MA2 - 1:]) fig = plt.figure(facecolor='#07000d', figsize=(15, 10)) ax1 = plt.subplot2grid((6, 4), (1, 0), rowspan=4, colspan=4, facecolor='#07000d') mpf.candlestick_ohlc(ax1, data.values[-SP:], width=.6, colorup='#ff1717', colordown='#53c156') # mpf.plot(data) Label1 = str(MA1) + ' SMA' Label2 = str(MA2) + ' SMA' ax1.plot(data.trade_date.values[-SP:], Av1[-SP:], '#e1edf9', label=Label1, linewidth=1.5) ax1.plot(data.trade_date.values[-SP:], Av2[-SP:], '#4ee6fd', label=Label2, linewidth=1.5) ax1.grid(True, color='w') ax1.xaxis.set_major_locator(mticker.MaxNLocator(10)) ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d')) ax1.yaxis.label.set_color("w") ax1.spines['bottom'].set_color("#5998ff") ax1.spines['top'].set_color("#5998ff") ax1.spines['left'].set_color("#5998ff") ax1.spines['right'].set_color("#5998ff") ax1.tick_params(axis='y', colors='w') plt.gca().yaxis.set_major_locator(mticker.MaxNLocator(prune='upper')) ax1.tick_params(axis='x', colors='w') plt.ylabel('Stock price and Volume') # 绘制成交量图 volumeMin = 0 # 先通过twinx来表达和ax1公用一个x轴 ax1v = ax1.twinx() # 通过fill——between这个函数来表达准备把这个数据全部弄成某个颜色 ax1v.fill_between(data.trade_date.values[-SP:], volumeMin, days.vol.values[-SP:], facecolor='#00ffe8', alpha=.4) ax1v.axes.yaxis.set_ticklabels([]) ax1v.grid(False) ###Edit this to 3, so it's a bit larger ax1v.set_ylim(0, 3 * days.vol.values.max()) ax1v.spines['bottom'].set_color("#5998ff") ax1v.spines['top'].set_color("#5998ff") ax1v.spines['left'].set_color("#5998ff") ax1v.spines['right'].set_color("#5998ff") ax1v.tick_params(axis='x', colors='w') ax1v.tick_params(axis='y', colors='w') # 我们画一下RSI图 # plot an RSI indicator on top maLeg = plt.legend(loc=9, ncol=2, prop={'size': 7}, fancybox=True, borderaxespad=0.) maLeg.get_frame().set_alpha(0.4) textEd = pylab.gca().get_legend().get_texts() pylab.setp(textEd[0:5], color='w') ax0 = plt.subplot2grid((6, 4), (0, 0), sharex=ax1, rowspan=1, colspan=4, facecolor='#07000d') # rsi = rsiFunc(data.Close.values) rsi = talib.RSI(data.close.values) rsiCol = '#c1f9f7' posCol = '#386d13' negCol = '#8f2020' ax0.plot(data.trade_date.values[-SP:], rsi[-SP:], rsiCol, linewidth=1.5) ax0.axhline(70, color=negCol) ax0.axhline(30, color=posCol) ax0.fill_between(data.trade_date.values[-SP:], rsi[-SP:], 70, where=(rsi[-SP:] >= 70), facecolor=negCol, edgecolor=negCol, alpha=0.5) ax0.fill_between(data.trade_date.values[-SP:], rsi[-SP:], 30, where=(rsi[-SP:] <= 30), facecolor=posCol, edgecolor=posCol, alpha=0.5) ax0.set_yticks([30, 70]) ax0.yaxis.label.set_color("w") ax0.spines['bottom'].set_color("#5998ff") ax0.spines['top'].set_color("#5998ff") ax0.spines['left'].set_color("#5998ff") ax0.spines['right'].set_color("#5998ff") ax0.tick_params(axis='y', colors='w') ax0.tick_params(axis='x', colors='w') plt.ylabel('RSI') # MACD图 # plot an MACD indicator on bottom ax2 = plt.subplot2grid((6, 4), (5, 0), sharex=ax1, rowspan=1, colspan=4, facecolor='#07000d') fillcolor = '#00ffe8' nslow = 26 nfast = 12 nema = 9 emaslow, emafast, macd = talib.MACD(data.close.values, fastperiod=nfast, slowperiod=nslow, signalperiod=nema) ax2.plot(data.trade_date.values[-SP:], emaslow[-SP:], color='#4ee6fd', lw=2) ax2.plot(data.trade_date.values[-SP:], emafast[-SP:], color='#e1edf9', lw=1) # bar = np.where(macd,2*macd,0) ''' bar_red = np.where(macd > 0, 2 * macd, 0) # 绘制BAR>0 柱状图 bar_green = np.where(macd < 0, 2 * macd, 0) # 绘制BAR<0 柱状图 show_func(bar_red) ax2.bar(data.trade_date.values[-SP:], bar_red[-SP:], facecolor='red') ax2.bar(data.trade_date.values[-SP:], bar_green[-SP:], facecolor='green') ''' # ax2.bar(data.trade_date.values[-SP:], macd[-SP:],facecolor=fillcolor) ax2.fill_between(data.trade_date.values[-SP:], macd[-SP:] * 2, 0, alpha=0.5, facecolor=fillcolor, edgecolor=fillcolor) # ax2.fill_between(data.trade_date.values[-SP:], macd[-SP:] - ema9[-SP:], 0, alpha=0.5, facecolor=fillcolor,edgecolor=fillcolor) plt.gca().yaxis.set_major_locator(mticker.MaxNLocator(prune='upper')) ax2.spines['bottom'].set_color("#5998ff") ax2.spines['top'].set_color("#5998ff") ax2.spines['left'].set_color("#5998ff") ax2.spines['right'].set_color("#5998ff") ax2.tick_params(axis='x', colors='w') ax2.tick_params(axis='y', colors='w') plt.ylabel('MACD', color='w') ax2.yaxis.set_major_locator(mticker.MaxNLocator(nbins=5, prune='upper')) for label in ax2.xaxis.get_ticklabels(): label.set_rotation(45) # 展示图 plt.ylabel('MACD') plt.show()
def plot_dataframe(df, ticker, name=None, plot=True, starting_date=None): from mplfinance import candlestick_ohlc df = dataframe_utilities.add_indicators(df) if starting_date is not None: df = df.truncate(before=starting_date) # ohlc: open high, low close # df_ohlc = df['5. adjusted close'].resample('10D').ohlc() # df_ohlc = df['4. close'].resample('10D').ohlc() # df_volume = df['6. volume'].resample('10D').sum() df_ohlc = df.resample("D").agg({ '1. open': 'first', '2. high': 'max', '2. low': 'min', '4. close': 'last' }) # df_ohlc = df_resampled.ohlc() df_volume = df['6. volume'].resample("D").sum() df_ohlc.reset_index(inplace=True) df_ohlc.dropna(inplace=True) df_volume.dropna(inplace=True) df_ohlc['date'] = df_ohlc['date'].map(mdates.date2num) df_ohlc.head() fig, (ax1, ax2, ax3, ax4) = plt.subplots(nrows=4, ncols=1, figsize=(19.2, 10.8), dpi=96, sharex=True, gridspec_kw={'height_ratios': [2, 1, 1, 0.5]}) ax1.xaxis_date() candlestick_ohlc(ax1, df_ohlc.values, width=1, colorup='#77d879', colordown='#db3f3f') ax1.set_xlabel('Time') ax1.set_ylabel('Price per Share (USD)') titleAX1 = 'Historic Share Price of ' + ticker ax1.set_title(titleAX1, horizontalalignment='center', verticalalignment='top') ax1.plot(df.index, df['volatility_bbh'], color="yellow", alpha=0.5, linewidth=1, label="Bollinger High") ax1.plot(df.index, df['volatility_bbl'], color="red", alpha=0.5, linewidth=1, label="Bollinger Low") ax1.fill_between(df.index, y1=df['volatility_bbh'], y2=df['volatility_bbl'], color='orange', alpha='0.3') ax1.legend(loc="lower left") ax2.plot(df.index, df['trend_macd'], color='purple', linewidth=0.5, label="MACD") ax2.plot(df.index, df['trend_macd_signal'], color='orange', alpha=0.5, linewidth=1, markersize=1, label="MACD Signal") ax2.set_xlabel('Time') ax2.set_ylabel('Value') ax2.set_ylim([-1, 1]) titleAX2 = 'MACD of ' + ticker ax2.set_title(titleAX2, horizontalalignment='center', verticalalignment='top') ax2.legend(loc="lower left") ax3.set_xlabel('Time') ax3.set_ylabel('Value') titleAX3 = 'Other Indicators of ' + ticker ax3.set_title(titleAX3, horizontalalignment='center', verticalalignment='top') ax3.plot(df.index, df['momentum_rsi'], color='purple', alpha=1, linewidth=1, markersize=1, label="RSI") ax3.plot(df.index, df['momentum_stoch'], color='black', alpha=1, linewidth=1, markersize=1, label="Stochastic %K") ax3.plot(df.index, df['momentum_stoch_signal'], color='red', alpha=1, linewidth=1, markersize=1, label="Stochastic %D") horiz_line_data = np.array([30 for i in range(len(df.index))]) ax3.plot(df.index, horiz_line_data, '--', alpha=0.5, linewidth=0.5, label="RSI Low") horiz_line_data = np.array([70 for i in range(len(df.index))]) ax3.plot(df.index, horiz_line_data, '--', alpha=0.5, linewidth=0.5, label="RSI High") horiz_line_data = np.array([20 for i in range(len(df.index))]) ax3.plot(df.index, horiz_line_data, '--', alpha=0.5, linewidth=0.5, label="Stochastic Low") horiz_line_data = np.array([80 for i in range(len(df.index))]) ax3.plot(df.index, horiz_line_data, '--', alpha=0.5, linewidth=0.5, label="Stochastic High") ax3.legend(loc="lower left") ax4.set_xlabel('Time') ax4.set_ylabel('Number of Shares') titleAX4 = 'Market Share Volume of ' + ticker ax4.set_title(titleAX4, horizontalalignment='center', verticalalignment='top') ax4.fill_between(df_volume.index.map(mdates.date2num), df_volume.values, 0, color="blue") plt.tight_layout() my_dpi = 96 if name is None: name = ticker fig.savefig('./figures/{}.png'.format(name), dpi=my_dpi * 10, bbox_inches='tight') # if starting_date == None: # fig.savefig('./figures/fullhistory/ETF/{}.png'.format(ticker), dpi=my_dpi*10,bbox_inches='tight') if plot: plt.show()
def graph_data(self, istock, MA1, MA2): """ Use this to dynamically pull a stock. """ try: print('Currently Pulling', stock) urlToVisit = 'http://chartapi.finance.yahoo.com/instrument/1.0/'+stock+'/chartdata;type=quote;range=10y/csv' stockFile =[] try: sourceCode = urllib.request.urlopen(urlToVisit).read().decode() splitSource = sourceCode.split('\n') for eachLine in splitSource: splitLine = eachLine.split(',') if len(splitLine)==6: if 'values' not in eachLine: stockFile.append(eachLine) except Exception as e: print(str(e), 'failed to organize pulled data.') except Exception as e: print(str(e), 'failed to pull pricing data') try: date, closep, highp, lowp, openp, volume = np.loadtxt( stockFile, delimiter=',', unpack=True, converters={ 0: self.bytes_per_date_to_num('%Y%m%d')} ) x = 0 y = len(date) newAr = [] while x < y: appendLine = date[x],openp[x],highp[x],lowp[x],closep[x],volume[x] newAr.append(appendLine) x+=1 Av1 = self.moving_average(closep, MA1) Av2 = self.moving_average(closep, MA2) SP = len(date[MA2-1:]) fig = plt.figure(facecolor='#07000d') ax1 = plt.subplot2grid((6,4), (1,0), rowspan=4, colspan=4, axisbg='#07000d') candlestick_ohlc(ax1, newAr[-SP:], width=.6, colorup='#53c156', colordown='#ff1717') Label1 = str(MA1)+' SMA' Label2 = str(MA2)+' SMA' ax1.plot(date[-SP:],Av1[-SP:],'#e1edf9',label=Label1, linewidth=1.5) ax1.plot(date[-SP:],Av2[-SP:],'#4ee6fd',label=Label2, linewidth=1.5) ax1.grid(True, color='w') ax1.xaxis.set_major_locator(mticker.MaxNLocator(10)) ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d')) ax1.yaxis.label.set_color("w") ax1.spines['bottom'].set_color("#5998ff") ax1.spines['top'].set_color("#5998ff") ax1.spines['left'].set_color("#5998ff") ax1.spines['right'].set_color("#5998ff") ax1.tick_params(axis='y', colors='w') plt.gca().yaxis.set_major_locator(mticker.MaxNLocator(prune='upper')) ax1.tick_params(axis='x', colors='w') plt.ylabel('Stock price and Volume') maLeg = plt.legend( loc=9, ncol=2, prop={'size':7}, fancybox=True, borderaxespad=0.0 ) maLeg.get_frame().set_alpha(0.4) textEd = pylab.gca().get_legend().get_texts() pylab.setp(textEd[0:5], color = 'w') volumeMin = 0 ax0 = plt.subplot2grid((6,4), (0,0), sharex=ax1, rowspan=1, colspan=4, axisbg='#07000d') rsi = self.rsi(closep) rsiCol = '#c1f9f7' posCol = '#386d13' negCol = '#8f2020' ax0.plot(date[-SP:], rsi[-SP:], rsiCol, linewidth=1.5) ax0.axhline(70, color=negCol) ax0.axhline(30, color=posCol) ax0.fill_between(date[-SP:], rsi[-SP:], 70, where=(rsi[-SP:]>=70), facecolor=negCol, edgecolor=negCol, alpha=0.5) ax0.fill_between(date[-SP:], rsi[-SP:], 30, where=(rsi[-SP:]<=30), facecolor=posCol, edgecolor=posCol, alpha=0.5) ax0.set_yticks([30,70]) ax0.yaxis.label.set_color("w") ax0.spines['bottom'].set_color("#5998ff") ax0.spines['top'].set_color("#5998ff") ax0.spines['left'].set_color("#5998ff") ax0.spines['right'].set_color("#5998ff") ax0.tick_params(axis='y', colors='w') ax0.tick_params(axis='x', colors='w') plt.ylabel('RSI') ax1v = ax1.twinx() ax1v.fill_between(date[-SP:],volumeMin, volume[-SP:], facecolor='#00ffe8', alpha=.4) ax1v.axes.yaxis.set_ticklabels([]) ax1v.grid(False) ax1v.set_ylim(0, 3*volume.max()) ax1v.spines['bottom'].set_color("#5998ff") ax1v.spines['top'].set_color("#5998ff") ax1v.spines['left'].set_color("#5998ff") ax1v.spines['right'].set_color("#5998ff") ax1v.tick_params(axis='x', colors='w') ax1v.tick_params(axis='y', colors='w') ax2 = plt.subplot2grid( (6, 4), (5, 0), sharex=ax1, rowspan=1, colspan=4, axisbg='#07000d' ) fillcolor = '#00ffe8' # nslow = 26 # nfast = 12 nema = 9 _, _, macd = self.compute_macd(closep) ema9 = self.exp_moving_average(macd, nema) ax2.plot(date[-SP:], macd[-SP:], color='#4ee6fd', lw=2) ax2.plot(date[-SP:], ema9[-SP:], color='#e1edf9', lw=1) ax2.fill_between( date[-SP:], macd[-SP:]-ema9[-SP:], 0, alpha=0.5, facecolor=fillcolor, edgecolor=fillcolor ) plt.gca().yaxis.set_major_locator(mticker.MaxNLocator(prune='upper')) ax2.spines['bottom'].set_color("#5998ff") ax2.spines['top'].set_color("#5998ff") ax2.spines['left'].set_color("#5998ff") ax2.spines['right'].set_color("#5998ff") ax2.tick_params(axis='x', colors='w') ax2.tick_params(axis='y', colors='w') plt.ylabel('MACD', color='w') ax2.yaxis.set_major_locator(mticker.MaxNLocator(nbins=5, prune='upper')) for label in ax2.xaxis.get_ticklabels(): label.set_rotation(45) plt.suptitle(stock.upper(),color='w') plt.setp(ax0.get_xticklabels(), visible=False) plt.setp(ax1.get_xticklabels(), visible=False) ax1.annotate( 'Big news!', (date[510], Av1[510]), xytext=(0.8, 0.9), textcoords='axes fraction', arrowprops=dict(facecolor='white', shrink=0.05), fontsize=14, color = 'w', horizontalalignment='right', verticalalignment='bottom' ) plt.subplots_adjust( left=.09, bottom=.14, right=.94, top=.95, wspace=.20, hspace=0 ) plt.show() fig.savefig('example.png', facecolor=fig.get_facecolor()) except Exception as e: print('main loop', str(e))