def _get_view(self): return [] assert len(self.live_data.items()) <= 4 extras = ['vwap'] if self.tech_indicators: extras.extend(self.tech_indicators) # tech_indicators s = mpf.make_mpf_style(base_mpf_style='classic', rc={'figure.facecolor': 'lightgray'}) for i, t in enumerate(self.live_data.keys(), start=1): ax2 = fig.add_subplot(2, 2, i, style=s) df = self.live_data[t].set_index('timestamp') ap = [mpf.make_addplot(df[t], ylabel=t) for t in extras] mpf.plot( df, type='candle', # addplot=ap, ax=ax2, # panel_ratios=(4, 1), # volume_panel=1, axtitle=t) np_img = self.fig2data(fig) return np_img
def graphMACD(self, df1, tree, compTicker): cols = list(df1.columns) tree['columns'] = cols for i in cols: tree.column(i, anchor='w') tree.heading(i, text=i, anchor='w') df1_rows = df1.to_numpy().tolist() print(df1_rows) for row in df1_rows: tree.insert('', 'end', values=row) subplots = [ mplFin.make_addplot(df1['MACD'], color='g', panel=1), mplFin.make_addplot(df1['EMA9'], color='b', panel=1) ] mplFin.plot(df1, type='candle', style='charles', title='MACD', ylabel='Price $', addplot=subplots)
def _render_price(self, current_step, net_worth, dates, step_range): self.price_ax.clear() self.volume_ax.clear() # Format the data price_range = self.df.iloc[step_range].copy() price_range.loc[:, 'index'] = pd.to_datetime(price_range['index']) price_range.set_index('index', inplace=True) #last_date = self.df['index'].values[current_step] last_date = self.net_worth_ax.get_xticks()[-2] last_close = self.df['close'].values[current_step] last_high = self.df['high'].values[current_step] # Print the current price to the price axis self.price_ax.annotate('{0:.2f}'.format(last_close), (last_date, last_close), xytext=(last_date, last_high), bbox=dict(boxstyle='round', fc='w', ec='k', lw=1), color="black", fontsize="small") # Plot price using mplfinance candlesticks after scaling axis otherwise, the scaling would be visible each frame mpf.plot(price_range, type='candle', style='charles', ax=self.price_ax, volume=self.volume_ax)
def candle_stick_daily(ticker, start_date=(datetime.now() - timedelta(days=60)).strftime("%Y%m%d"), end_date=datetime.now().strftime("%Y%m%d")): start_date = datetime.strptime(str(start_date), '%Y%m%d').strftime('%Y-%m-%d') end_date = datetime.strptime(str(end_date), '%Y%m%d').strftime('%Y-%m-%d') tkr = yf.Ticker(ticker) stock = tkr.history(interval="1d", start=start_date, end=end_date) stock.drop(columns=['Dividends', 'Stock Splits'], inplace=True) """ Open High Low Close Volume Date 2021-01-20 858.739990 859.500000 837.280029 850.450012 25665900 2021-01-21 855.000000 855.719971 841.419983 844.989990 20521100 2021-01-22 834.309998 848.000000 828.619995 846.640015 20066500 2021-01-25 855.000000 900.400024 838.820007 880.799988 41173400 2021-01-26 891.380005 895.900024 871.599976 883.090027 23131600 """ print(f"plotting chart for {ticker} ...") # print(stock.head(5)) fig_d = mpf.figure(style="yahoo") ax1_d = fig_d.add_subplot(1,1,1) mpf.plot(stock, ax=ax1_d, type='candle') mpf.show() pass
def _send_stock(stock_name: str, user_time_input_str: str, update, context): # volume = true ticker = yf.Ticker(stock_name) data_fetch_functions = { UserTimeInput.NOW: lambda: ticker.history(period="90m", interval="2m"), UserTimeInput.DAY: lambda: ticker.history(period="1d", interval="15m"), UserTimeInput.WEEK: lambda: ticker.history(period="1wk", interval="90m"), UserTimeInput.MONTH: lambda: ticker.history(period="1mo", interval="1d"), UserTimeInput.QUARTER: lambda: ticker.history(period="3mo", interval="1d"), UserTimeInput.YEAR: lambda: ticker.history(period="1y", interval="1d"), } user_time_input_str = user_time_input_str.upper() members = UserTimeInput.__members__ if user_time_input_str in members: user_time_input = members[user_time_input_str] df = data_fetch_functions[user_time_input]() if df.shape[0] == 0: # No data found for specified stock or time update.message.reply_text( f"Hmm, na.. {stock_name} kenn i leider ned.") else: image_path = "./images/finance.png" mpf.plot(df, type="candle", style="yahoo", title=f"{stock_name} {user_time_input.name}", savefig=image_path) context.bot.send_photo(chat_id=update.message.chat_id, photo=open(image_path, "rb")) else: # Wrong time specification update.message.reply_text( "Sorry, aber des Zeitintervall sogt ma goa nix.\nZur Not hätt i a /help Kommando." )
def show_stock_chart3(df, title='', figpath=None): # 日付で昇順ソース df_sort = df.sort_index() # MACDを追加 df_macd = add_macd(df_sort) # RSIを追加 df_rsi = add_rsi(df_macd) print('==========') print(df_rsi) # MACDとRSIのプロット作成 add_plot = [ mpf.make_addplot(df_rsi['MACD'], color='m', panel=1, secondary_y=False), mpf.make_addplot(df_rsi['Signal'], color='c', panel=1, secondary_y=False), mpf.make_addplot(df_rsi['Hist'], type='bar', color='g', panel=1, secondary_y=True), mpf.make_addplot(df_rsi['RSI'], panel=2) ] # ローソク足チャートを表示 mpf.plot(df_rsi, type='candle', mav=(5, 25, 75), volume=True, addplot=add_plot, volume_panel=3, savefig=figpath)
def test_pnf03(bolldata): df = bolldata fname = base + '03.png' tname = os.path.join(tdir, fname) rname = os.path.join(refd, fname) mpf.plot(df, type='pnf', pnf_params=dict(box_size='atr', atr_length=2), volume=True, savefig=tname) tsize = os.path.getsize(tname) print(glob.glob(tname), '[', tsize, 'bytes', ']') rsize = os.path.getsize(rname) print(glob.glob(rname), '[', rsize, 'bytes', ']') result = compare_images(rname, tname, tol=IMGCOMP_TOLERANCE) if result is not None: print('result=', result) assert result is None
def make_candlestick_mplfinance(df, save_png: str) -> None: """ mplfinanceを使ってローソク足画像作成する ※論文では出来高入れない方が精度良さそうだったから出来高は入れない """ import sys current_dir = pathlib.Path(__file__).resolve().parent sys.path.append(str(current_dir) + "/../GitHub/mplfinance/src") import mplfinance as mpf kwargs = dict( type="candle", figratio=(1.5, 1.5), figscale=1, title="", ylabel="", ylabel_lower="", ) mc = mpf.make_marketcolors(up="#00ff00", down="#ff00ff", inherit=True) s = mpf.make_mpf_style(base_mpf_style="nightclouds", marketcolors=mc, gridstyle="") mpf.plot( df, **kwargs, style=s, is_not_set_visible=True, savefig=save_png, )
def plot_profitline(stock_data, profit_ratio, title='', output=os.path.join(_test_path, 'profitline.jpg')): stock_data['close'] = profit_ratio stock_profitline = stock_data.set_index("date") stock_profitline.index = pd.to_datetime(stock_profitline.index) stock_profitline = stock_profitline.astype(float) kwargs = dict(type='line', volume=False, ylabel='Return Rate', figratio=(11, 8), figscale=0.85) style = mpf.make_mpf_style(base_mpf_style='yahoo', rc={'font.size':8}) fig, axes = mpf.plot(stock_profitline, **kwargs, style=style, scale_padding={'left': 0.1, 'top': 1, 'right': 1, 'bottom': 1}, returnfig=True) axes[0].yaxis.set_major_formatter(matplotlib.ticker.PercentFormatter(xmax=1.0)) axes[0].set_title(title) fig.savefig(output, dpi=300) plt.close(fig)
def show_graph(my_indicator): #my_indicator.get_indicator() #action = my_indicator.get_action() #profit = my_indicator.get_performance() #print('Rendimento: {:.2f}%'.format(profit*100)) marcador_venda = my_indicator.get_sell_markers() marcador_compra = my_indicator.get_buy_markers() apds = [ mpf.make_addplot(my_indicator._indicator), mpf.make_addplot(marcador_compra, scatter=True, markersize=200, marker='^'), mpf.make_addplot(marcador_venda, scatter=True, markersize=200, marker='v'), ] mpf.plot(my_indicator._stock, style='charles', volume=True, addplot=apds)
def collect_info(binance): df_list = {} df_list_test = {} print("collect data") for symbol in const.PAIR_SYMBOLS: if os.path.exists("..\\Data\\" + symbol + "_data.csv"): df_list[symbol] = pd.read_csv("..\\Data\\" + symbol + "_data.csv", index_col=0, parse_dates=True) mpf.plot(df_list[symbol], type='candle') else: df_list[symbol] = make_dataset.make_current_data( binance, symbol, 400, 10) df_list[symbol].to_csv("..\\Data\\" + symbol + "_data.csv") for symbol in const.PAIR_SYMBOLS: base_asset = binance.get_base_asset(symbol) quote_asset = binance.get_quote_asset(symbol) for i in const.BALANCE_SYMBOLS: print(i + " Available : " + binance.get_balance(i)["free"])
def test_addplot11(bolldata): df = bolldata[50:130].copy() fname = base+'11.png' tname = os.path.join(tdir,fname) rname = os.path.join(refd,fname) df.loc[:,'trend'] = 0 df.loc[df['Close'] < df['Open'], 'trend'] = - 1 df.loc[df['Close'] > df['Open'], 'trend'] = 1 ap = mpf.make_addplot(df['trend'],panel=1,type='step',ylabel='simple trend') mpf.plot(df,ylabel='OHLC',addplot=ap,savefig=tname) tsize = os.path.getsize(tname) print(glob.glob(tname),'[',tsize,'bytes',']') rsize = os.path.getsize(rname) print(glob.glob(rname),'[',rsize,'bytes',']') result = compare_images(rname,tname,tol=IMGCOMP_TOLERANCE) if result is not None: print('result=',result) assert result is None
def test_addplot10(bolldata): sdf = bolldata[50:130] fname = base+'10.png' tname = os.path.join(tdir,fname) rname = os.path.join(refd,fname) ap = mpf.make_addplot(sdf,panel=1,type='candle',ylabel='Candle',mav=12) mpf.plot(sdf,mav=10,ylabel='OHLC',addplot=ap,panel_ratios=(1,1),figratio=(1,1),figscale=1.5,savefig=tname) tsize = os.path.getsize(tname) print(glob.glob(tname),'[',tsize,'bytes',']') rsize = os.path.getsize(rname) print(glob.glob(rname),'[',rsize,'bytes',']') # Using 0.9*IMGCOMP_TOLERANCE here because discovered that if # the only difference is the presence or absence of mav lines, # then the default IMGCOMP_TOLERANCE is too linient: result = compare_images(rname,tname,tol=0.9*IMGCOMP_TOLERANCE) if result is not None: print('result=',result) assert result is None
def test_addplot09(bolldata): sdf = bolldata[50:130] fname = base+'09.png' tname = os.path.join(tdir,fname) rname = os.path.join(refd,fname) ap = mpf.make_addplot((sdf['PercentB'])-0.45,panel=1,color='g',type='bar', width=0.75, mav=(7,10,15)) mpf.plot(sdf,addplot=ap,panel_ratios=(1,1),figratio=(1,1),figscale=1.5,savefig=tname) tsize = os.path.getsize(tname) print(glob.glob(tname),'[',tsize,'bytes',']') rsize = os.path.getsize(rname) print(glob.glob(rname),'[',rsize,'bytes',']') # Using 0.9*IMGCOMP_TOLERANCE here because discovered that if # the only difference is the presence or absence of mav lines, # then the default IMGCOMP_TOLERANCE is too linient: result = compare_images(rname,tname,tol=0.9*IMGCOMP_TOLERANCE) if result is not None: print('result=',result) assert result is None
def candlestick(self, date_range=None, resample=None, volume=False, **kwargs): """ Create a candlestick plot for the OHLC data with optional aggregation, subset of the date range, and volume. Parameters: - date_range: String or `slice()` of dates to pass to `loc[]`, if `None` the plot will be for the full range of the data. - resample: The offset to use for resampling the data, if desired. - volume: Whether to show a bar plot for volume traded under the candlesticks - kwargs: Additional keyword arguments to pass down to `mplfinance.plot()` Note: `mplfinance.plot()` doesn't return anything. To save your plot, pass in `savefig=file.png`. """ if not date_range: date_range = slice(self.data.index.min(), self.data.index.max()) plot_data = self.data.loc[date_range] if resample: agg_dict = { 'open': 'first', 'close': 'last', 'high': 'max', 'low': 'min', 'volume': 'sum' } plot_data = plot_data.resample(resample).agg({ col: agg_dict[col] for col in plot_data.columns if col in agg_dict }) mpf.plot(plot_data, type='candle', volume=volume, **kwargs)
def chart(df, type='candle', vol=False, MA=False, log=False): name = df['symbol'].iloc[0] if log: df.Close = np.log(df.Close) df.Open = np.log(df.Open) df.High = np.log(df.High) df.Low = np.log(df.Low) if MA: mpf.plot(df, type=type, style='charles', volume=vol, mav=MA, figratio=(20, 10), title='Chart: ' + name, ylabel='price') else: mpf.plot(df, type=type, style='charles', volume=vol, figratio=(20, 10), title='Chart: ' + name, ylabel='price')
def make_chart(ticker, tmp_data, date, idx, pattern, isbull, base_path): program_start_time = datetime.today().strftime("%Y%m%d%H%M%S") #-2 와 3숫자를 변할수 있다. 특정 차트 패턴이 나오고 앞으로 2일 뒤로 3일을 더해서 이미지를 뽑는다. # 저 간격을 줄일수도 있고 늘릴수도 있다. nei_data = tmp_data.iloc[tmp_data.index.get_loc(date) - 2:tmp_data.index.get_loc(date) + 3] mc = mpf.make_marketcolors(up='r', down='b') s = mpf.make_mpf_style(marketcolors=mc) flag = "" if (isbull == "bull"): flag = "BULL" else: flag = "BEAR" path = f'{base_path}/{pattern}_{flag}/' if not os.path.isdir(path): os.mkdir(path) savefig = dict(fname=f'{path}/{program_start_time}_{ticker}_{pattern}_{flag}_{idx}.png',\ dpi=50,pad_inches=0,bbox_inches='tight') #matplotlib 함수 mpf.plot(nei_data, axisoff=True, type='candle', style=s, savefig=savefig)
async def intra(ctx, sym: str): """Get a chart for the stocks movement since market open.""" symbol = s.find_symbols(sym)[0] df = s.intra_reply(symbol) if df.empty: await ctx.send("Invalid symbol please see `/help` for usage details.") return buf = io.BytesIO() mpf.plot( df, type="renko", title=f"\n${symbol.upper()}", volume=True, style="yahoo", mav=20, savefig=dict(fname=buf, dpi=400, bbox_inches="tight"), ) buf.seek(0) caption = ( f"\nIntraday chart for ${symbol.upper()} from {df.first_valid_index().strftime('%I:%M')} to" + f" {df.last_valid_index().strftime('%I:%M')} ET on" + f" {datetime.date.today().strftime('%d, %b %Y')}" ) await ctx.send( content=caption, file=discord.File( buf, filename=f"{symbol.upper()}:{datetime.date.today().strftime('%d%b%Y')}.png", ), ) await ctx.send(f"{s.price_reply([symbol])[symbol]}")
def plot_stock_sig(pddatas, datals, sigs): "datas标准数据,sigs(trade_sig,up_buy,up_sell,down_buy,down_sell)" # https://blog.csdn.net/weixin_42524945/article/details/112187912 # https://blog.csdn.net/xingbuxing_py/article/details/109379080 # 1. 添加额外线 # add_plot = mpf.make_addplot(datal[['High', 'MidValue', 'Low']]) # 2. 添加额外点 tadd_plot = [mpf.make_addplot(datal) for datal in datals] add_plot = [ mpf.make_addplot(sigs["sig"], scatter=True, markersize=100, marker='o', color='y'), mpf.make_addplot(sigs["ub"], scatter=True, markersize=100, marker='^', color='r'), mpf.make_addplot(sigs["us"], scatter=True, markersize=100, marker='v', color='g'), mpf.make_addplot(sigs["db"], scatter=True, markersize=100, marker='^', color='#ff8080'), mpf.make_addplot(sigs["ds"], scatter=True, markersize=100, marker='v', color='#80ff80'), ] mpf.plot(pddatas, type='candle', addplot=tadd_plot + add_plot)
def return_img(window_back, dpi=50, rcparams={}): buf = io.BytesIO() save = dict(fname=buf, dpi=dpi) s = mpf.make_mpf_style(gridstyle='', rc=rcparams) fig, _ = mpf.plot(window_back, type='candle', volume=False, savefig=save, style=s, returnfig=True) img = get_img_from_fig(fig, dpi=dpi) img = (255.0 - img[40:282, 95:431, :]) / 255.0 #inverted image and normalized #img = crop_image(img) return img
def test_renko02(bolldata): df = bolldata fname = base + '02.png' tname = os.path.join(tdir, fname) rname = os.path.join(refd, fname) mpf.plot(df, type='renko', renko_params=dict(brick_size=4), volume=True, savefig=tname) tsize = os.path.getsize(tname) print(glob.glob(tname), '[', tsize, 'bytes', ']') rsize = os.path.getsize(rname) print(glob.glob(rname), '[', rsize, 'bytes', ']') result = compare_images(rname, tname, tol=IMGCOMP_TOLERANCE) if result is not None: print('result=', result) assert result is None
def animate(ival): if (20+ival) > len(df): print('no more data to plot') ani.event_source.interval *= 3 if ani.event_source.interval > 12000: exit() return data = df.iloc[0:(30+ival)] exp12 = data['Close'].ewm(span=12, adjust=False).mean() exp26 = data['Close'].ewm(span=26, adjust=False).mean() macd = exp12 - exp26 signal = macd.ewm(span=9, adjust=False).mean() histogram = macd - signal apds = [mpf.make_addplot(exp12,color='lime',ax=ax_emav), mpf.make_addplot(exp26,color='c',ax=ax_emav), mpf.make_addplot(histogram,type='bar',width=0.7, color='dimgray',alpha=1,ax=ax_hisg), mpf.make_addplot(macd,color='fuchsia',ax=ax_macd), mpf.make_addplot(signal,color='b',ax=ax_sign), ] for ax in axes: ax.clear() mpf.plot(data,type='candle',addplot=apds,ax=ax_main,volume=ax_volu)
def stock(stock_id): stock_id = str(stock_id) + ".TW" # Yahoo Finance 的 代號為台灣的代號 + .TW data = yf.Ticker(stock_id) # 抓取資料 # 1mo = 1個月,max 可以把所有期間的資料都下載 ohlc = data.history(period="36mo") print(ohlc) data = pd.DataFrame(ohlc) data.to_csv("./" + '/stock.csv', header=True) ohlc = ohlc.loc[:, ["Open", "High", "Low", "Close", "Volume"]] # 選擇製圖需要欄位(開高低收量) # 調整圖表標示顏色 mc = fplt.make_marketcolors( up='tab:red', down='tab:green', # 上漲為紅,下跌為綠 wick={ 'up': 'red', 'down': 'green' }, # 影線上漲為紅,下跌為綠 volume='tab:green', # 交易量顏色 ) s = fplt.make_mpf_style(marketcolors=mc) # 定義圖表風格 fplt.plot( ohlc, # 開高低收量的資料 type='candle', # 類型為蠟燭圖,也就是 K 線圖 style=s, # 套用圖表風格 title=stock_id, # 設定圖表標題 ylabel='Price ($)', # 設定 Y 軸標題 volume=True, savefig='bar_chart.png', # 儲存檔案 )
def stonks(sym): try: plt.style.use('dark_background') today = datetime.today() past_date = today - dateutil.relativedelta.relativedelta(months=3) df = web.DataReader(sym, 'yahoo', past_date, today).reset_index() print(df) df.set_index('Date', inplace=True, drop=False) df = df[[ 'Date', 'Open', 'High', 'Low', 'Close', 'Adj Close', 'Volume' ]] df['Date'] = pd.to_datetime(df['Date']) df['Date'] = df['Date'].map(mpdates.date2num) mplfinance.plot(df, type='candle', title=sym.upper() + " " + str(past_date.strftime("%b %Y")) + " to " + str(today.strftime("%b %Y")), volume=True, savefig='.\send_stock\\' + sym + '.png') except Exception as e: return e
def plot_d(pdata, sma9, sma20, sma50, sma200, lowerbb, upperbb, numofdays, ticker, defining_ma): sma9dict = mpf.make_addplot(sma9['data'][-numofdays:], color='#c87cff', width=1) sma20dict = mpf.make_addplot(sma20['data'][-numofdays:], color='#f28c06', width=1) sma50dict = mpf.make_addplot(sma50['data'][-numofdays:], color='#3a7821', width=1) sma200dict = mpf.make_addplot(sma200['data'][-numofdays:], color='#483e8b', width=1) lowerbbdict = mpf.make_addplot(lowerbb['data'][-numofdays:], color='#b90c0c', width=1) upperbbdict = mpf.make_addplot(upperbb['data'][-numofdays:], color='#b90c0c', width=1) mpf.plot( pdata[-numofdays:], type='candle', style='charles', addplot=[ sma9dict, sma20dict, sma50dict, sma200dict, lowerbbdict, upperbbdict ], # figscale=.9, tight_layout=False, ylabel='', savefig= f'''/Users/mike/Desktop/ib_insync-MovingAverageChartGen/9-200SMA_{today_date}/{ticker}_{defining_ma}_{today_date}.pdf''' ) chartFilePath = f'''/Users/mike/Desktop/ib_insync-MovingAverageChartGen/9-200SMA_{today_date}/{ticker}_{defining_ma}_{today_date}.pdf''' chartFileTitle = f'''{ticker}_{defining_ma}_{today_date}.pdf'''
def draw(date): # target_stock = '0050' #設定要繪製走勢圖的股票 # df = pd.read_csv(f'./data/{target_stock}.csv', parse_dates=True, index_col=1) #讀取目標股票csv檔的位置 d = date[:6] # print(dir) df = pd.read_csv('tx5_data/' + d + '/' + date + '.txt') print(df) df.index = pd.DatetimeIndex(df['Time']) # df.rename(columns={'Time': 'dates'}, inplace=True) # df.rename(columns={'Open': 'opens'}, inplace=True) # df.rename(columns={'High': 'highs'}, inplace=True) # df.rename(columns={'Low': 'lows'}, inplace=True) # df.rename(columns={'Close': 'closes'}, inplace=True) # df.rename(columns={'Volume': 'volumes'}, inplace=True) # print(df) # 這裡針對資料表做一下修正,因為交易量(Turnover)在mplfinance中須被改為Volume才能被認出來 mc = mpf.make_marketcolors(up='r', down='g', inherit=True) s = mpf.make_mpf_style(base_mpf_style='yahoo', marketcolors=mc) # 針對線圖的外觀微調,將上漲設定為紅色,下跌設定為綠色,符合台股表示習慣 # 接著把自訂的marketcolors放到自訂的style中,而這個改動是基於預設的yahoo外觀 kwargs = dict(type='candle', mav=(5, 10, 20), volume=True, figratio=(10, 5), figscale=1, title=date, style=s) # 設定可變參數kwargs,並在變數中填上繪圖時會用到的設定值 mpf.plot(df, **kwargs)
def test_figratio_bounds(bolldata): df = bolldata buf = io.BytesIO() mpf.plot(df, volume=True, figratio=(10, 5), savefig=buf) with pytest.raises(ValueError) as ex: mpf.plot(df, volume=True, figratio=(11, 2), savefig=buf) assert '"figratio" (aspect ratio) must be between' in str(ex.value) with pytest.raises(ValueError) as ex: mpf.plot(df, volume=True, figratio=(10, 51), savefig=buf) assert '"figratio" (aspect ratio) must be between' in str(ex.value)
def plot_candlestick(df, title, savefig): # Generate log plot. Currently it's not supported by mplf.plot, # so we do it overselves. kwargs = dict(type='candle', mav=(200), volume=True) fig, axlist = mplf.plot(df, ylabel='Price', title=title, returnfig=True, **kwargs, style='yahoo') ax1 = axlist[0] ax1_minor_yticks = ax1.get_yticks(True) # save the original ticks because the log ticks are sparse ax1_major_yticks = ax1.get_yticks(False) ax1.set_yscale('log') ax1.set_yticks(ax1_major_yticks, True) ax1.set_yticks(ax1_minor_yticks, False) ax1.yaxis.set_major_formatter(ticker.FuncFormatter(format_price)) ax1.yaxis.set_minor_formatter(ticker.FuncFormatter(format_price)) ax1.autoscale() plt.savefig(savefig) plt.close('all')
def plot_data(self, ticker, stockName, data): ''' mc = mpf.make_marketcolors( up='tab:green',down='tab:red', edge='green', wick={'up':'green','down':'red'}, volume='tab:green', ) s = mpf.make_mpf_style(marketcolors=mc) ''' data['MA50'] = data['Close'].ewm(span=50).mean() data['MA200'] = data['Close'].ewm(span=200).mean() bollingerFrame = self.bollingerBands(data) bbands = bollingerFrame[['MA20', 'upperB', 'lowerB']] apd = mpf.make_addplot(bbands, linestyle='dashed', width=0.6, color='white') apd1 = mpf.make_addplot(data['MA50']) apd2 = mpf.make_addplot(data['MA200']) #Moving averages MA_short = 50 MA_long = 200 fig, ax = mpf.plot(data, title="{} ({})".format(stockName, ticker), figscale=2.0, type='candle', style='nightclouds', ylabel="Price", volume=True, addplot=[apd1, apd2, apd], returnfig=True) fig.legend([ 'MAV{}'.format(MA_short), 'MAV{}'.format(MA_long), 'Bollinger Bands', ], frameon=False) plt.show() return
def test_addplot24(bolldata): df = bolldata fname = base + '18.png' tname = os.path.join(tdir, fname) rname = os.path.join(refd, fname) tcdf = df[['LowerB', 'UpperB']] # DataFrame with two columns low_signal = percentB_belowzero(df['PercentB'], df['Close']) high_signal = percentB_aboveone(df['PercentB'], df['Close']) import math new_low_signal = [x * 20. * math.sin(x) for x in low_signal] apds = [ mpf.make_addplot(tcdf, linestyle='dashdot'), mpf.make_addplot(new_low_signal, scatter=True, markersize=200, marker='^'), mpf.make_addplot(high_signal, scatter=True, markersize=200, marker='v'), mpf.make_addplot((df['PercentB']), panel='lower', color='g', linestyle='dotted') ] fig_axis = mpf.plot(df, addplot=apds, figscale=1.5, volume=True, style='default', savefig=tname) #plt.close(fig_axis[0]) tsize = os.path.getsize(tname) print(glob.glob(tname), '[', tsize, 'bytes', ']') rsize = os.path.getsize(rname) print(glob.glob(rname), '[', rsize, 'bytes', ']') result = compare_images(rname, tname, tol=IMGCOMP_TOLERANCE) if result is not None: print('result=', result) assert result is None