def update(txt): df = download(txt) if len(df) < 20: # symbol does not exist return info.setText('Loading symbol name...') price = df['Open Close High Low'.split()] ma20 = df.Close.rolling(20).mean() ma50 = df.Close.rolling(50).mean() volume = df['Open Close Volume'.split()] if not plots: plots.append(fplt.candlestick_ochl(price)) plots.append(fplt.plot(ma20, legend='MA-20')) plots.append(fplt.plot(ma50, legend='MA-50')) plots.append(fplt.volume_ocv(volume, ax=ax.overlay())) else: plots[0].update_data(price) plots[1].update_data(ma20) plots[2].update_data(ma50) plots[3].update_data(volume) Thread(target=lambda: info.setText(get_name(txt))).start( ) # slow, so use thread
def plot_rsi(df, ax): diff = df.close.diff().values gains = diff losses = -diff with np.errstate(invalid='ignore'): gains[(gains < 0) | np.isnan(gains)] = 0.0 losses[(losses <= 0) | np.isnan(losses)] = 1e-10 # we don't want divide by zero/NaN n = 14 m = (n - 1) / n ni = 1 / n g = gains[n] = np.nanmean(gains[:n]) l = losses[n] = np.nanmean(losses[:n]) gains[:n] = losses[:n] = np.nan for i, v in enumerate(gains[n:], n): g = gains[i] = ni * v + m * g for i, v in enumerate(losses[n:], n): l = losses[i] = ni * v + m * l rs = gains / losses df['rsi'] = pd.Series(100 - (100 / (1 + rs))) fplt.plot(df.time, df.rsi, ax=ax, legend='RSI')
def setup_plot(self, plot_title, kbars): import finplot as fplt kbars = kbars.reset_index().rename(columns={'ts': 'time'}) # adopt TWSE style fplt.display_timezone = gettz(self._exchange.brokerage.TIMEZONE) fplt.candle_bull_color = '#ef5350' fplt.candle_bull_body_color = fplt.candle_bull_color fplt.candle_bear_color = '#26a69a' fplt.volume_bull_color = '#f7a9a7' fplt.volume_bull_body_color = fplt.volume_bull_color fplt.volume_bear_color = '#92d2cc' main_ax, rsi_ax, macd_ax = fplt.create_plot(plot_title, rows=3) fplt.candlestick_ochl(kbars[['time', 'open', 'close', 'high', 'low']], ax=main_ax) fplt.volume_ocv(kbars[['time', 'open', 'close', 'volume']], ax=main_ax.overlay()) fplt.plot(kbars['time'], kbars['rsi'], ax=rsi_ax, legend='RSI') fplt.set_y_range(0, 100, ax=rsi_ax) fplt.add_band(self.MIN_RSI, self.MAX_RSI, ax=rsi_ax) fplt.volume_ocv(kbars[['time', 'open', 'close', 'macd_hist']], ax=macd_ax, colorfunc=fplt.strength_colorfilter) fplt.plot(kbars['time'], kbars['macd'], ax=macd_ax, legend='MACD') fplt.plot(kbars['time'], kbars['macd_signal'], ax=macd_ax, legend='Signal') return fplt
def search(self): """ This function displays given stock's history for the period of 4 years. Args: None Returns: None """ try: df = yf.download( self.search_entry.get(), start="2017-01-01", end=datetime.today().strftime("%Y-%m-%d"), ) fplt.candlestick_ochl(df[["Open", "Close", "High", "Low"]]) fplt.plot(df.Close.rolling(50).mean()) fplt.plot(df.Close.rolling(200).mean()) fplt.show() except IndexError: messagebox.showerror("Stock Name Error", "Invalid Stock name")
def show_day(): #lol = df temp = lol #temp = self.get_frac_df(temp,) ax, ax2, ax3 = fplt.create_plot('NASDAQ', rows=3) candle_src = fplt.PandasDataSource( lol[['time', 'open', 'close', 'high', 'low']]) fplt.candlestick_ochl(candle_src, ax=ax) fplt.plot(lol['time'], lol['close'].rolling(25).mean(), ax=ax, color='#0000ff', legend='ma-25') #df['rnd'] = np.random.normal(size=len(df)) #fplt.plot(df['time'], df['rnd'], ax=ax2, color='#992277', legend='stuff') #fplt.set_y_range(ax2, -4.4, +4.4) # fix y-axis range # finally a volume bar chart in our third plot volume_src = fplt.PandasDataSource(lol[['time', 'open', 'close', 'volume']]) fplt.volume_ocv(volume_src, ax=ax3) # we're done fplt.show()
def change_asset(*args, **kwargs): '''Resets and recalculates everything, and plots for the first time.''' # save window zoom position before resetting fplt._savewindata(fplt.windows[0]) symbol = ctrl_panel.symbol.currentText() interval = ctrl_panel.interval.currentText() ws.df = None df = load_price_history(symbol, interval=interval) ws.reconnect(symbol, interval, df) # remove any previous plots ax.reset() axo.reset() ax_rsi.reset() # calculate plot data indicators = ctrl_panel.indicators.currentText().lower() data,price_data = calc_plot_data(df, indicators) # some space for legend ctrl_panel.move(100 if 'clean' in indicators else 200, 0) # plot data global plots plots = {} plots['price'] = fplt.candlestick_ochl(data['price'], ax=ax) plots['volume'] = fplt.volume_ocv(data['volume'], ax=axo) if data['ma50'] is not None: plots['ma50'] = fplt.plot(data['ma50'], legend='MA-50', ax=ax) plots['ma200'] = fplt.plot(data['ma200'], legend='MA-200', ax=ax) plots['vema24'] = fplt.plot(data['vema24'], color=4, legend='V-EMA-24', ax=axo) if data['rsi'] is not None: ax.set_visible(xaxis=False) ax_rsi.show() fplt.set_y_range(0, 100, ax=ax_rsi) fplt.add_band(30, 70, color='#6335', ax=ax_rsi) plots['sar'] = fplt.plot(data['sar'], color='#55a', style='+', width=0.6, legend='SAR', ax=ax) plots['rsi'] = fplt.plot(data['rsi'], legend='RSI', ax=ax_rsi) plots['stoch'] = fplt.plot(data['stoch'], color='#880', legend='Stoch', ax=ax_rsi) plots['stoch_s'] = fplt.plot(data['stoch_s'], color='#650', ax=ax_rsi) else: ax.set_visible(xaxis=True) ax_rsi.hide() # price line ax.price_line = pg.InfiniteLine(angle=0, movable=False, pen=fplt._makepen(fplt.candle_bull_body_color, style='.')) ax.price_line.setPos(price_data['last_close']) ax.price_line.pen.setColor(pg.mkColor(price_data['last_col'])) ax.addItem(ax.price_line, ignoreBounds=True) # restores saved zoom position, if in range fplt.refresh()
def plot(df, x, y, kind, **kwargs): _x = df.index if y is None else df[x] try: _y = df[x].reset_index(drop=True) if y is None else df[y] except: _y = df.reset_index(drop=True) kwargs = dict(kwargs) if 'by' in kwargs: del kwargs['by'] if kind in ('candle', 'candle_ochl', 'candlestick', 'candlestick_ochl', 'volume', 'volume_ocv', 'renko'): if 'candle' in kind: return finplot.candlestick_ochl(df, **kwargs) elif 'volume' in kind: return finplot.volume_ocv(df, **kwargs) elif 'renko' in kind: return finplot.renko(df, **kwargs) elif kind == 'scatter': if 'style' not in kwargs: kwargs['style'] = 'o' return finplot.plot(_x, _y, **kwargs) elif kind == 'bar': return finplot.bar(_x, _y, **kwargs) elif kind in ('barh', 'horiz_time_volume'): return finplot.horiz_time_volume(df, **kwargs) elif kind in ('heatmap'): return finplot.heatmap(df, **kwargs) elif kind in ('labels'): return finplot.labels(df, **kwargs) elif kind in ('hist', 'histogram'): return finplot.hist(df, **kwargs) else: if x is None: _x = df _y = None if 'style' not in kwargs: kwargs['style'] = None return finplot.plot(_x, _y, **kwargs)
def update_plot(): global orderbook calc_bollinger_bands(df) candlesticks = df['t o c h l'.split()] bollband_hi = df['t bbh'.split()] bollband_lo = df['t bbl'.split()] if not plots: # 1st time candlestick_plot = fplt.candlestick_ochl(candlesticks) plots.append(candlestick_plot) plots.append(fplt.plot(bollband_hi, color='#4e4ef1')) plots.append(fplt.plot(bollband_lo, color='#4e4ef1')) fplt.fill_between(plots[1], plots[2], color='#9999fa') # generate dummy orderbook plot, which we update next time x = len(candlesticks)+0.5 y = candlesticks.c.iloc[-1] orderbook = [[x,[(y,1)]]] orderbook_colorfunc = fplt.horizvol_colorfilter([(0,'bull'),(10,'bear')]) orderbook_plot = fplt.horiz_time_volume(orderbook, candle_width=1, draw_body=10, colorfunc=orderbook_colorfunc) plots.append(orderbook_plot) # use bitmex colors candlestick_plot.colors.update(dict( bull_shadow = '#388d53', bull_frame = '#205536', bull_body = '#52b370', bear_shadow = '#d56161', bear_frame = '#5c1a10', bear_body = '#e8704f')) orderbook_plot.colors.update(dict( bull_frame = '#52b370', bull_body = '#bae1c6', bear_frame = '#e8704f', bear_body = '#f6c6b9')) else: # update plots[0].update_data(candlesticks) plots[1].update_data(bollband_hi) plots[2].update_data(bollband_lo) plots[3].update_data(orderbook)
def update_plot(): calc_bollinger_bands(df) candlesticks = df['t o c h l'.split()] bollband_hi = df['t bbh'.split()] bollband_lo = df['t bbl'.split()] if not plots: candlestick_plot = fplt.candlestick_ochl(candlesticks) plots.append(candlestick_plot) plots.append(fplt.plot(bollband_hi, color='#4e4ef1')) plots.append(fplt.plot(bollband_lo, color='#4e4ef1')) fplt.fill_between(plots[1], plots[2], color='#9999fa') # redraw using bitmex colors candlestick_plot.colors.update( dict(bull_shadow='#388d53', bull_frame='#205536', bull_body='#52b370', bear_shadow='#d56161', bear_frame='#5c1a10', bear_body='#e8704f')) candlestick_plot.repaint() else: plots[0].update_data(candlesticks) plots[1].update_data(bollband_hi) plots[2].update_data(bollband_lo)
def plot_price_in_range(df, name, start, end): new_df = get_time_period(df, start, end) ax = fplt.create_plot(name, rows=1) # plot candle stick candles = new_df[['Open', 'Close', 'High', 'Low']] fplt.candlestick_ochl(candles, ax=ax) # moving averages fplt.plot(new_df.Close.rolling(50).mean(), legend='ma50') fplt.plot(new_df.Close.rolling(100).mean(), legend='ma100') fplt.plot(new_df.Close.rolling(150).mean(), legend='ma150') fplt.plot(new_df.Close.rolling(200).mean(), legend='ma200') # overlay volume on the top plot volumes = new_df[['Open', 'Close', 'Volume']] fplt.volume_ocv(volumes, ax=ax.overlay()) fplt.show()
def update(): df = delta_bars.df # Меняем индекс и делаем его типом datetime df = df.set_index( pd.to_datetime(df['date_time'], format='%Y-%m-%d %H:%M:%S')) df = df.drop( 'date_time', 1 ) # Удаляем колонку с датой и временем, т.к. дата у нас теперь в индексе play_sound(df.tail(2)) # Вызов функции звукового сигнала print(df) # pick columns for our three data sources: candlesticks and TD candlesticks = df['open close high low'.split()] deltabarsec = df['open close sec'.split()] delta = df['open close delta'.split()] maxvolcluster = df['max_vol'] if not plots: # first time we create the plots global ax plots.append(fplt.candlestick_ochl(candlesticks, candle_width=0.8)) plots.append(fplt.volume_ocv(deltabarsec, ax=ax2)) fplt.add_legend('Время формирования бара', ax=ax2) plots.append( fplt.volume_ocv(delta, colorfunc=fplt.strength_colorfilter, ax=ax3)) fplt.add_legend('Дельта', ax=ax3) plots.append( fplt.plot(maxvolcluster, legend='Max volume', style='o', color='#00f')) else: # every time after we just update the data sources on each plot plots[0].update_data(candlesticks) plots[1].update_data(deltabarsec) plots[2].update_data(delta) plots[3].update_data(maxvolcluster)
def plot_macd(self, fastperiod, slowperiod, signalperiod, color1=None, color2=None, color3=None): """ 在图上画出MACD指标 :param fastperiod: :param slowperiod: :param signalperiod: :param color1: :param color2: :param color3: :return: """ color1 = color1 if color1 is not None else "#FF0000" # 默认设置为红色 color2 = color2 if color2 is not None else "#00FF00" # 默认设置为绿色 color3 = color3 if color3 is not None else "#0000FF" # 默认设置为蓝色 dif = self.__indicators.MACD(fastperiod, slowperiod, signalperiod)['DIF'] dea = self.__indicators.MACD(fastperiod, slowperiod, signalperiod)["DEA"] macd = self.__indicators.MACD(fastperiod, slowperiod, signalperiod)["MACD"] fplt.plot(self.__df['time'], dif, color=color1, ax=self.__ax3, legend='MACD({}, {}, {})-DIF'.format(fastperiod, slowperiod, signalperiod)) fplt.plot(self.__df['time'], dea, color=color2, ax=self.__ax3, legend='MACD({}, {}, {})-DEA'.format(fastperiod, slowperiod, signalperiod)) fplt.plot(self.__df['time'], macd, color=color3, ax=self.__ax3, legend='MACD({}, {}, {})-MACD'.format( fastperiod, slowperiod, signalperiod))
def plot(txt): # Get data df = download(txt) if len(df) < 20: # symbol does not exist return info.setText('Loading symbol name...') # Cleanup ax.reset() # remove previous plots axo.reset() # remove previous plots # Process result price = df['Open Close High Low'.split()] volume = df['Open Close Volume'.split()] # Indicators emaShort = df.Close.ewm(span=10, min_periods=0, adjust=False, ignore_na=False).mean() emaMedium = df.Close.ewm(span=20, min_periods=0, adjust=False, ignore_na=False).mean() emaLong = df.Close.ewm(span=50, min_periods=0, adjust=False, ignore_na=False).mean() # Plot data fplt.candlestick_ochl(price) fplt.plot(emaShort, legend='EMA-10', color='#00FFFF', width=2) fplt.plot(emaMedium, legend='EMA-20', width=2) fplt.plot(emaLong, legend='EMA-50', color='#FF0000', width=2) fplt.volume_ocv(volume, ax=axo) fplt.refresh() # refresh autoscaling when all plots complete Thread(target=lambda: info.setText(get_name(txt))).start( ) # slow, so use thread
def plt_finplot_show(df, symbol): import finplot as fplt df.reset_index(drop=True, inplace=True) df = df.astype({'date': 'datetime64[ns]'}) ax, ax2 = fplt.create_plot(symbol, rows=2) # plot candle sticks candle_src = fplt.PandasDataSource(df[['date', 'open', 'close', 'high', 'low']]) fplt.candlestick_ochl(candle_src, ax=ax) # put an MA in there fplt.plot(df['date'], df['close'].rolling(25).mean(), ax=ax, color='#0000ff', legend='ma-25') # place some dumb markers hi_wicks = df['high'] - df[['open', 'close']].T.max().T df.loc[(hi_wicks > hi_wicks.quantile(0.99)), 'marker'] = df['close'] fplt.plot(df['date'], df['marker'], ax=ax, color='#000000', style='^', legend='dumb mark') # draw some random crap on our second plot df['rnd'] = np.random.normal(size=len(df)) fplt.plot(df['date'], df['rnd'], ax=ax2, color='#992277', legend='stuff') fplt.set_y_range(ax2, -1.4, +1.7) # fix y-axis range fplt.show()
symbol, start_t, end_t, interval) r = requests.get(url) df = pd.read_csv(StringIO(r.text)) df['Date'] = pd.to_datetime(df['Date']).astype( 'int64') // 1_000_000 # use finplot's internal representation, which is ms ax, ax2 = fplt.create_plot('S&P 500 MACD', rows=2) # plot macd with standard colors first macd = df.Close.ewm(span=12).mean() - df.Close.ewm(span=26).mean() signal = macd.ewm(span=9).mean() df['macd_diff'] = macd - signal fplt.volume_ocv(df[['Date', 'Open', 'Close', 'macd_diff']], ax=ax2, colorfunc=fplt.strength_colorfilter) fplt.plot(macd, ax=ax2, legend='MACD') fplt.plot(signal, ax=ax2, legend='Signal') # change to b/w coloring templates for next plots fplt.candle_bull_color = fplt.candle_bear_color = '#000' fplt.volume_bull_color = fplt.volume_bear_color = '#333' fplt.candle_bull_body_color = fplt.volume_bull_body_color = '#fff' # plot price and volume fplt.candlestick_ochl(df[['Date', 'Open', 'Close', 'High', 'Low']], ax=ax) hover_label = fplt.add_legend('', ax=ax) axo = ax.overlay() fplt.volume_ocv(df[['Date', 'Open', 'Close', 'Volume']], ax=axo) fplt.plot(df.Volume.ewm(span=24).mean(), ax=axo, color=1) #######################################################
def plt_chart(fa_info, save_chart=False, interactive=False): global df global symbol global file_png # load data and convert date symbol, sector, industry, website, num_emp, profile = fa_info return_result = (None, None) end_t = int(time()) start_t = end_t - NUM_OF_MONTHS * 30 * 24 * 60 * 60 # twelve months interval = '1d' url = 'https://query1.finance.yahoo.com/v7/finance/download/%s?period1=%s&period2=%s&interval=%s&events=history' % ( symbol, start_t, end_t, interval) try: r = requests.get(url) df = pd.read_csv(StringIO(r.text)) if df.empty: print(f"[Warn] symbol {symbol} has no data") return return_result if df.shape[0] < MA_SLOW: print( f"[Warn] symbol {symbol} has fewer than {MA_SLOW} data points") return return_result except Exception as ex: print( f"[Error] failed to download quote from Yahoo finance for {symbol}" ) return return_result last_date = str(df.tail(1)['Date'].values[0]).split("T")[0] df['Date'] = pd.to_datetime(df['Date']).astype( 'int64') # use finplot's internal representation, which is ns log_msg = "" if sector: title = f"[{symbol}] {website} - {sector} - {industry} {last_date}" log_msg += title + "\n" + profile else: title = f"[{symbol}] {last_date}" log_msg += title log_msg += "\n=======================================================" print(log_msg) # with open("_finplot-watchlist.log", "a") as f: # f.write(log_msg) # print(__file__) pardir = os.path.dirname(__file__) chart_dir = os.path.join(pardir, "charts", today_str) if not os.path.exists(chart_dir): os.mkdir(chart_dir) file_png = os.path.join(chart_dir, f"{symbol}_{today_str}.png") # print(file_png) ax, ax1, ax2 = fplt.create_plot(title, rows=3) # plot price fplt.candlestick_ochl(df[['Date', 'Open', 'Close', 'High', 'Low']], ax=ax) hover_label = fplt.add_legend(symbol, ax=ax) ma15 = df.Close.ewm(span=MA_FAST).mean() ma50 = df.Close.ewm(span=MA_SLOW).mean() ma200 = df.Close.ewm(span=MA_LONG).mean() fplt.plot(ma15, ax=ax, color=COLOR_IDX["blue"], width=1) fplt.plot(ma50, ax=ax, color=COLOR_IDX["red"], width=2) fplt.plot(ma200, ax=ax, color=COLOR_IDX["green"], width=3) # plot macd with standard colors first macd = ma15 - ma50 signal = macd.ewm(span=MACD_AVG).mean() trend = TREND_FACTOR * (ma50 - ma200) df['macd_diff'] = MACD_FACTOR * (macd - signal) fplt.volume_ocv(df[['Date', 'Open', 'Close', 'macd_diff']], ax=ax1, colorfunc=fplt.strength_colorfilter) fplt.plot(macd, ax=ax1) # fplt.plot(signal, ax=ax1, legend='Signal') fplt.plot(macd, ax=ax1, width=COLOR_IDX["red"]) fplt.plot(signal, ax=ax1, color=COLOR_IDX["black"]) fplt.plot(trend, ax=ax1, width=2, color=COLOR_IDX["blue"]) # # change to b/w coloring templates for next plots # fplt.candle_bull_color = fplt.candle_bear_color = '#000' # fplt.volume_bull_color = fplt.volume_bear_color = '#333' # fplt.candle_bull_body_color = fplt.volume_bull_body_color = '#fff' # plot volume # axo = ax.overlay() vol_factor = 100000 df['Volume'] = df['Volume'] / vol_factor fplt.volume_ocv(df[['Date', 'Open', 'Close', 'Volume']], ax=ax2) fplt.plot(df.Volume.ewm(span=20).mean(), ax=ax2, color=COLOR_IDX["black"], width=2) # if interactive: # fplt.set_time_inspector(update_legend_text, ax=ax, when='hover') # fplt.add_crosshair_info(update_crosshair_text, ax=ax) if save_chart: fplt.timer_callback(save, 0.5, single_shot=True) # wait some until we're rendered # print(chart_info) return_result = (fplt, file_png) return return_result
for iv, vol in zip(volbins, g.volume): price2vol[iv.left] += vol data.append([t, sorted(price2vol.items())]) return data def calc_vwap(period): vwap = pd.Series([], dtype='float64') df['hlc3v'] = df['hlc3'] * df.volume for _, g in df.groupby(pd.Grouper(key='time', freq=period)): i0, i1 = g.index[0], g.index[-1] vwap = vwap.append(g.hlc3v.loc[i0:i1].cumsum() / df.volume.loc[i0:i1].cumsum()) return vwap # download and calculate indicators df = download_price_history( interval_mins=30) # reduce to [15, 5, 1] minutes to increase accuracy time_volume_profile = calc_volume_profile( df, period='W', bins=100) # try fewer/more horizontal bars (graphical resolution only) vwap = calc_vwap(period='W') # try period='D' # plot fplt.create_plot('Binance BTC futures weekly volume profile') fplt.plot(df.time, df.close, legend='Price') fplt.plot(df.time, vwap, style='--', legend='VWAP') fplt.horiz_time_volume(time_volume_profile, draw_va=0.7, draw_poc=1.0) fplt.show()
axo = ax.overlay() ind.df.replace([np.inf, -np.inf], np.nan, inplace=True) ind.df.fillna(0) ind.df['ts'] = ind.df.index.values.astype(np.int64) // 10 ** 9 ind.df.loc[ind.df['fractals_high'] == 0,'fractals_high'] = np.nan ind.df.loc[ind.df['fractals_high'] > 0,'fractals_high'] = ind.df['High']+1 ind.df.loc[ind.df['fractals_low'] == 0,'fractals_low'] = np.nan ind.df.loc[ind.df['fractals_low'] > 0,'fractals_low'] = ind.df['Low']-1 angularation = myutils.angularation(ind.df) ind.df['angularation'] = angularation ind.df.loc[ind.df['angularation'] == True,'angularation'] = ind.df['High']+2 fplt.set_y_range(-10, 10, ax=ax2) fplt.plot(ind.df['fractals_high'], ax=ax, color='#4a5', style='^', legend='fractals_high') fplt.plot(ind.df['angularation'], ax=ax, color='#0f0', style='^', legend='angularation') fplt.plot(ind.df['fractals_low'], ax=ax, color='#f00', style="v", legend='fractals_low') fplt.plot(ind.df[['alligator_jaws']], ax=ax, legend=['alligator_jaws']) fplt.plot(ind.df[['alligator_teeth']], ax=ax, legend=['alligator_teeth']) fplt.plot(ind.df[['alligator_lips']], ax=ax, legend=['alligator_lips']) fplt.volume_ocv(ind.df[['Open','Close','ao']], ax=ax2) fplt.volume_ocv(df[['Open','Close','Volume']], ax=axo) fplt.candlestick_ochl(df[['Open', 'Close', 'High', 'Low']],ax=ax) ####################################################### ## update crosshair and legend when moving the mouse ## hover_label = fplt.add_legend('', ax=ax) def update_legend_text(x, y):
#!/usr/bin/env python3 import finplot as fplt import numpy as np import pandas as pd import yfinance as yf btc = yf.download('BTC-USD', '2014-09-01') ax1, ax2, ax3, ax4, ax5 = fplt.create_plot('Bitcoin/Dollar long term analysis', rows=5, maximize=False) fplt.set_y_scale(ax=ax1, yscale='log') fplt.plot(btc.Close, color='#000', legend='Log price', ax=ax1) btc['ma200'] = btc.Close.rolling(200).mean() btc['ma50'] = btc.Close.rolling(50).mean() fplt.plot(btc.ma200, legend='MA200', ax=ax1) fplt.plot(btc.ma50, legend='MA50', ax=ax1) btc['one'] = 1 fplt.volume_ocv(btc[['ma200', 'ma50', 'one']], candle_width=1, ax=ax1.overlay(scale=0.02)) daily_ret = btc.Close.pct_change() * 100 fplt.plot(daily_ret, width=3, color='#000', legend='Daily returns %', ax=ax2) fplt.add_legend('Daily % returns histogram', ax=ax3) fplt.hist(daily_ret, bins=60, ax=ax3) fplt.add_legend('Yearly returns in %', ax=ax4)
# format it in pandas df = df.reset_index() df = df.drop(columns = ['Adj Close']) df = df.rename(columns={'Date':'time', 'Open':'open', 'Close':'close', 'High':'high', 'Low':'low', 'Volume':'volume'}) df = df.astype({'time':'datetime64[ns]'}) # create two plots ax,ax2 = fplt.create_plot(stock, rows=2) # plot candle sticks candles = df[['time','open','close','high','low']] fplt.candlestick_ochl(candles, ax=ax) # overlay volume on the top plot volumes = df[['time','open','close','volume']] fplt.volume_ocv(volumes, ax=ax.overlay()) # put an MA on the close price fplt.plot(df['time'], df['close'].rolling(25).mean(), ax=ax, legend='ma-25') # place some markers on low wicks lo_wicks = df[['open','close']].T.min() - df['low'] df.loc[(lo_wicks>lo_wicks.quantile(0.99)), 'marker'] = df['low'] fplt.plot(df['time'], df['marker'], ax=ax, color='#4a5', style='^') # draw something random on our second plot fplt.plot(df['time'], np.random.normal(size=len(df)), ax=ax2, color='#927', legend='random') fplt.set_y_range(-1.4, +3.7, ax=ax2) # hard-code y-axis range limitation # we're done fplt.show()
#!/usr/bin/env python3 import finplot as fplt import numpy as np import pandas as pd dates = pd.date_range('01:00', '01:00:01.200', freq='1ms') prices = pd.Series(np.random.random(len(dates))).rolling(30).mean() + 4 fplt.plot(dates, prices, width=3) line = fplt.add_line((dates[100], 4.4), (dates[1100], 4.6), color='#9900ff', interactive=True) ## fplt.remove_primitive(line) text = fplt.add_text((dates[500], 4.6), "I'm here alright!", color='#bb7700') ## fplt.remove_primitive(text) rect = fplt.add_rect((dates[700], 4.5), (dates[850], 4.4), color='#8c8', interactive=True) ## fplt.remove_primitive(rect) def save(): fplt.screenshot(open('screenshot.png', 'wb')) fplt.timer_callback(save, 0.5, single_shot=True) # wait some until we're rendered fplt.show()
def plot_vma(df, ax): fplt.plot(df.time, df.volume.rolling(20).mean(), ax=ax, color='#c0c030')
import finplot as fplt import numpy as np import pandas as pd dates = pd.date_range('01:00', '21:30', freq='1min') prices = pd.Series(np.random.random(len(dates))).rolling(30).mean() + 4 plot = fplt.plot(dates, prices) line = fplt.add_line(plot.ax, (dates[100], 4.4), (dates[1100], 4.6), color='#9900ff', interactive=True) #fplt.remove_line(plot.ax, line) text = fplt.add_text(plot.ax, (dates[500], 4.6), "I'm here alright!", color='#bb7700') #fplt.remove_text(plot.ax, text) fplt.show()
import finplot as fplt import numpy as np import pandas as pd # Creating a randon Datetime index for x-axes. dates = pd.date_range('01:00', '01:00:01.200', freq='1ms') # Creating a random price Series for y-axes prices = pd.Series(np.random.random(len(dates))).rolling(30).mean() + 4 # plotting a line fplt.plot(dates, prices, legend='Nonscence') # Drawing a interactive line line = fplt.add_line((dates[100], 4.4), (dates[1100], 4.6), color='#9900ff', interactive=True) # removing the interactive line # fplt.remove_line(line) # adding an immovable text. text = fplt.add_text(pos=(dates[50], 4.4), s="I'm here alright!", color='#bb7700') # removing the immovable text. # fplt.remove_text(text) # displaying the plot fplt.show()
def plot_bubble_pass(price, price_col, size_col, min_val, max_val, scale, color, ax): price = price.copy() price.loc[(price[size_col]<min_val)|(price[size_col]>max_val), price_col] = np.nan fplt.plot(price[price_col], style='o', width=scale, color=color, ax=ax)
daily_plot = fplt.candlestick_ochl(dfd.dropna(), candle_width=5) daily_plot.colors.update( dict(bull_body='#bfb', bull_shadow='#ada', bear_body='#fbc', bear_shadow='#dab')) daily_plot.x_offset = 3.1 # resample() gets us start of day, offset +1.1 (gap+off center wick) # plot high resolution on top fplt.candlestick_ochl(df[['Open', 'Close', 'High', 'Low']]) # scatter plot correlation between Google and Microsoft stock df['ret_alphabet'] = df.Close.pct_change() df['ret_microsoft'] = dfms.Close.pct_change() dfc = df.dropna().reset_index(drop=True)[['ret_alphabet', 'ret_microsoft']] fplt.plot(dfc, style='o', color=1, ax=ax2) # draw least-square line errfun = lambda arr: [ y - arr[0] * x + arr[1] for x, y in zip(dfc.ret_alphabet, dfc.ret_microsoft) ] line = scipy.optimize.least_squares(errfun, [0.01, 0.01]).x linex = [dfc.ret_alphabet.min(), dfc.ret_alphabet.max()] liney = [linex[0] * line[0] + line[1], linex[1] * line[0] + line[1]] fplt.add_line((linex[0], liney[0]), (linex[1], liney[1]), color='#993', ax=ax2) fplt.add_text((linex[1], liney[1]), 'k=%.2f' % line[0], color='#993', ax=ax2) fplt.add_legend('Alphabet vs. Microsft 90m correlation', ax=ax2) fplt.show()
def plot_ema(df, ax): fplt.plot(df.time, df.close.ewm(span=9).mean(), ax=ax, legend='EMA')
df = pd.read_csv(symbol + '.csv') df = df.astype({'time': 'datetime64[ns]'}) # create three plots ax, ax2, ax3 = fplt.create_plot(symbol, rows=3) # plot candle sticks candle_src = fplt.PandasDataSource(df[['time', 'open', 'close', 'high', 'low']]) fplt.candlestick_ochl(candle_src, ax=ax) # put an MA in there fplt.plot(df['time'], df['close'].rolling(25).mean(), ax=ax, color='#0000ff', legend='ma-25') # place some dumb markers hi_wicks = df['high'] - df[['open', 'close']].T.max().T df.loc[(hi_wicks > hi_wicks.quantile(0.99)), 'marker'] = df['close'] fplt.plot(df['time'], df['marker'], ax=ax, color='#000000', style='^', legend='dumb mark') # draw some random crap on our second plot df['rnd'] = np.random.normal(size=len(df))
fplt.candlestick_ochl(candles, ax=ax) # overlay volume on the top plot volumes = df[['time', 'open', 'close', 'volume']] fplt.volume_ocv(volumes, ax=ax.overlay()) # put an MA on the close price #fplt.plot(df['time'], df['close'].rolling(window).mean(), ax=ax, legend='ma-25') #fplt.plot(df['time'], maxim, ax=ax, legend='maxim') #fplt.plot(df['time'], minim, ax=ax, legend='minim') # draw second plot for i, window in enumerate(windows): if (i < 5): fplt.plot(df['time'], volatility[i], ax=ax2, legend='volatility ' + str(window)) if (i >= 5): fplt.plot(df['time'], volatility[i], ax=ax3, legend='volatility ' + str(window)) #fplt.set_y_range(0, 0.005, ax=ax2) # hard-code y-axis range limitation # draw third plot #fplt.plot(df['time'], volatility_diff, ax=ax3, color='#927', legend='volatility_diff') # draw fourth plot #fplt.plot(df['time'], open_price_position_relative_to_volatility_box, ax=ax4, color='#927', legend='open_price_position_relative_to_volatility_box') # restore view (X-position and zoom) if we ever run this example again
def plot_on_balance_volume(df, ax): obv = df.volume.copy() obv[df.close < df.close.shift()] = -obv obv[df.close == df.close.shift()] = 0 df['obv'] = obv.cumsum() fplt.plot(df.time, df.obv, ax=ax, legend='OBV', color='#008800')