def __init__(self, pipe, init_data, init_sym, tech_indicators, fps=10): super().__init__() self.plots = [] self.tech_indicators = tech_indicators self.data, self.watched_sym = init_data, init_sym self.ax, self.ax2 = fplt.create_plot('Live Stock Trader', init_zoom_periods=500, maximize=False, rows=2) self.live_data = None self.update_data() self.fps = fps self.plots = [ fplt.candlestick_ochl(self.live_data[0], ax=self.ax), fplt.volume_ocv(self.live_data[1], ax=self.ax.overlay()), fplt.plot(self.live_data[2], ax=self.ax, legend='VWAP') ] self.plots.extend([ fplt.plot(ti_d, ax=self.ax2, legend=t) for t, ti_d in zip(tech_indicators, self.live_data[3:]) ]) fplt.timer_callback( self.step, 1 / fps) # update (using synchronous rest call) every N seconds self.pipe = pipe
def show_day_plot(): #self.fecha = instance.text #print (self.fecha) temp = lol #temp = pd.date_range(start=temp['time'][self.fechas[0]], end=temp['time'][self.fechas[1]], freq='D') #print (type(self.fechas[0])) #print (self.fechas[0],self.fechas[1]) datex = fechas[3] desde = fechas[1] + timedelta(hours=5) hasta = desde + timedelta(hours=24) temp = lol[(lol.time > desde) & (lol.time <= hasta)] print(temp) print('mierdaaa') #print (emp['time'][self.fecha]) #temp = self.get_frac_df(temp,) ax, ax2, ax3 = fplt.create_plot('NASDAQ', rows=3) candle_src = fplt.PandasDataSource( temp[['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') #subprocess.Popen(['python','ploter.py']) #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( temp[['time', 'open', 'close', 'volume']]) fplt.volume_ocv(volume_src, ax=ax3) fplt.show()
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 worker(sym, inter, ops, csvlock, plots): def drawplot(): url = 'https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=%s&interval=%s&apikey=%s&datatype=csv&outputsize=%s'%(sym, inter, APIKEY, ops) res = rq.get(url) with open(sym+'temp.csv', 'wb') as f: for chunk in res.iter_content(): f.write(chunk) try: data = pd.read_csv(sym+'temp.csv', parse_dates=['timestamp'], index_col='timestamp').sort_index() except: return # if API does not respond with valid data. update_csv(sym, data) candles = data[['open','close','high','low']] volumes = data[['open','close','volume']] if len(plots) == 0: plots.append(fplt.volume_ocv(volumes, ax=ax2)) plots.append(fplt.candlestick_ochl(candles, ax=ax)) else: plots[0].update_data(volumes) plots[1].update_data(candles) #==============================================# ax, ax2 = fplt.create_plot(sym+' Stock Time Series - '+inter+' - '+ops, rows=2) drawplot() fplt.timer_callback(drawplot, 3600.0) # draw the graphs every 60 mins (3600 secs) fplt.show()
def init_chart(self): canvas = QtWidgets.QGraphicsView() ax = fplt.create_plot(init_zoom_periods=10) print(type(ax)) canvas.axs = [ax] self._ui.centralLayout.addWidget(ax.vb.win, 1, 0, 1, 2) canvas.show()
def __init__(self): super().__init__() self.setWindowTitle("QGraphicsView") layout = QGridLayout() self.setLayout(layout) self.resize(800, 300) self.ws = BinanceFutureWebsocket() plots = {} fplt.y_pad = 0.07 # pad some extra (for control panel) fplt.max_zoom_points = 7 fplt.autoviewrestore() self.ax, self.ax_rsi = fplt.create_plot('Complicated Binance Futures Example', rows=2, init_zoom_periods=3000) self.axo = self.ax.overlay() layout.addWidget(self.ax.vb.win, 0, 0) self.ax_rsi.hide() self.ax_rsi.vb.setBackgroundColor(None) # don't use odd background color self.ax.set_visible(xaxis=True) self.symbol = "BTCUSDT" self.interval = "1m" self.change_asset() fplt.timer_callback(self.realtime_update_plot, 1) # update every second fplt.show(qt_exec=False)
def __init__(self, platform, symbol, time_frame): self.__platform = platform self.__symbol = symbol self.__time_frame = time_frame self.__market = MARKET(self.__platform, self.__symbol, self.__time_frame) # pull some data self.__indicators = INDICATORS(self.__platform, self.__symbol, self.__time_frame) self.__kline = platform.get_kline(self.__time_frame) self.__kline.reverse() # format it in pandas try: # dataframe有7列的情况 self.__df = pd.DataFrame(self.__kline, columns=[ 'time', 'open', 'high', 'low', 'close', 'volume', 'currency_volume' ]) self.__df = self.__df.astype({ 'time': 'datetime64[ns]', 'open': 'float64', 'close': 'float64', 'high': 'float64', 'low': 'float64', 'volume': 'float64', 'currency_volume': 'float64' }) except: # dataframe只有6列的情况,如okex的现货k线数据 self.__df = pd.DataFrame( self.__kline, columns=['time', 'open', 'high', 'low', 'close', 'volume']) self.__df = self.__df.astype({ 'time': 'datetime64[ns]', 'open': 'float64', 'close': 'float64', 'high': 'float64', 'low': 'float64', 'volume': 'float64' }) # create three plot 创建三层图纸,第一层画k线,第二层画成交量,第三层画一些适宜于副图显示的指标 fplt.foreground = '#FFFFFF' # 前景色 fplt.background = '#333333' # 背景色 fplt.odd_plot_background = '#333333' # 第二层图纸的背景色 fplt.cross_hair_color = "#FFFFFF" # 准星的颜色 self.__ax, self.__ax2, self.__ax3 = fplt.create_plot(symbol, rows=3) # plot candle sticks candles = self.__df[['time', 'open', 'close', 'high', 'low']] fplt.candlestick_ochl(candles, ax=self.__ax) # overlay volume on the plot volumes = self.__df[['time', 'open', 'close', 'volume']] fplt.volume_ocv(volumes, ax=self.__ax2) fplt.add_legend("VOLUME", self.__ax2) # 增加"VOLUME"图例
def __init__(self, data_host): self.plots = [] self.data_host = data_host symbol = data_host.request['symbol'] fplt.create_plot(f"{symbol}", init_zoom_periods=75, maximize=True) self.update_plot() def upd(): try: if self.data_host.changed: self.update_plot() self.data_host.changed = False except Exception as ex: print(ex) fplt.timer_callback(upd, 0.1) # update in 10 Hz #fplt.autoviewrestore() fplt.show()
def plotter(): # getting the selections selection = assetListBox.curselection()[0] asset = asset_dict[assetListBox.get(selection)] currency = denomination_dict[opMenuVar.get()] periods = periodEntryVar.get() if currency is None: # No currency is selected. synthetic_asset = pd.DataFrame( mt5.copy_rates_from_pos( asset, mt5.TIMEFRAME_H1, 1, periods)).drop(columns=['spread', 'real_volume']) synthetic_asset['time'] = pd.to_datetime(synthetic_asset['time'], unit='s') synthetic_asset.set_index(keys=['time'], inplace=True) else: # Cross-currency is selected synthetic_asset = synthesize(asset, currency, periods) synthetic_asset.dropna(inplace=True) # Calculaating Simple Moving averages synthetic_asset['SMA 1'] = synthetic_asset['close'].rolling( sma1boxVar.get()).mean() synthetic_asset['SMA 2'] = synthetic_asset['close'].rolling( sma2boxVar.get()).mean() # Calculating Standard-deviation. synthetic_asset['pct_change'] = synthetic_asset['close'].pct_change() * 100 synthetic_asset['std-dev'] = synthetic_asset['pct_change'].ewm( stddevVar.get()).std() candle_stick_data = fplt.PandasDataSource( synthetic_asset[['open', 'close', 'high', 'low']]) ax, ax2 = fplt.create_plot(title=f'{asset}/{currency}', rows=2) candle_plot = fplt.candlestick_ochl(candle_stick_data, ax=ax) # Plotting SMAs sma1 = fplt.plot(synthetic_asset['SMA 1'], legend=f'{sma1boxVar.get()} SMA', ax=ax) sma2 = fplt.plot(synthetic_asset['SMA 2'], legend=f'{sma2boxVar.get()} SMA', ax=ax) # Plotting Std-dev stdDevPlot = fplt.plot(synthetic_asset['std-dev'], legend=f'Std Dev {stddevVar.get()}', ax=ax2) fplt.add_text(pos=(synthetic_asset.index[-1], synthetic_asset['std-dev'].iloc[-1]), s=f"{synthetic_asset['std-dev'].iloc[-1].round(3)}", ax=ax2) fplt.show()
def plot_kline(kline): """ 回测结束时绘制k线图 :param kline: 回测时传入指定的k线数据 :return: """ kline = kline # kline.reverse() # format it in pandas try: # dataframe有7列的情况 df = pd.DataFrame(kline, columns=[ 'time', 'open', 'high', 'low', 'close', 'volume', 'currency_volume' ]) df = df.astype({ 'time': 'datetime64[ns]', 'open': 'float64', 'close': 'float64', 'high': 'float64', 'low': 'float64', 'volume': 'float64', 'currency_volume': 'float64' }) except: # dataframe只有6列的情况,如okex的现货k线数据 df = pd.DataFrame( kline, columns=['time', 'open', 'high', 'low', 'close', 'volume']) df = df.astype({ 'time': 'datetime64[ns]', 'open': 'float64', 'close': 'float64', 'high': 'float64', 'low': 'float64', 'volume': 'float64' }) # create three plot 创建三层图纸,第一层画k线,第二层画成交量,第三层画一些适宜于副图显示的指标 fplt.foreground = '#FFFFFF' # 前景色 fplt.background = '#333333' # 背景色 fplt.odd_plot_background = '#333333' # 第二层图纸的背景色 fplt.cross_hair_color = "#FFFFFF" # 准星的颜色 ax, ax2 = fplt.create_plot("KLINE", rows=2) # plot candle sticks candles = df[['time', 'open', 'close', 'high', 'low']] fplt.candlestick_ochl(candles, ax=ax) # overlay volume on the plot volumes = df[['time', 'open', 'close', 'volume']] fplt.volume_ocv(volumes, ax=ax2) fplt.add_legend("VOLUME", ax2) # 增加"VOLUME"图例 fplt.show()
def plotter(): # getting the selections selection = assetListBox.curselection()[0] asset = asset_dict[assetListBox.get(selection)] currency = denomination_dict[opMenuVar.get()] periods = periodEntryVar.get() synthetic_asset = synthesize(asset, currency, periods) synthetic_asset.dropna(inplace=True) candle_stick_data = fplt.PandasDataSource( synthetic_asset[['open', 'close', 'high', 'low']]) ax = fplt.create_plot(title=f'{asset}/{currency}', rows=1) candle_plot = fplt.candlestick_ochl(candle_stick_data, ax=ax)
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 drawCandleStickChart(timestamp, openVal, high, low, closeVal, volume, exchange, symbol): # create two plots ax = fplt.create_plot(exchange + '-' + symbol, rows=1) # plot candle sticks candles = [timestamp, openVal, closeVal, high, low] fplt.candlestick_ochl(candles, ax=ax) # # put an MA on the close price # fplt.plot(timestamp, closeVal.rolling(25).mean(), ax=ax, legend='ma-25') # overlay volume on the top plot volumes = [timestamp, openVal, closeVal, volume] fplt.volume_ocv(volumes, ax=ax.overlay()) # restore view (X-position and zoom) if we ever run this example again fplt.autoviewrestore() # we're done fplt.show()
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 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()
for window in windows: ma = df['high'].rolling(window).max() # volatility box top mi = df['low'].rolling(window).min() # volatility box bottom} c = ma - mi # volatility box center vol = c / ma # volatility diff = vol.diff() volatility.append(vol) volatility_diff.append(diff) #volatility = volatility.rolling(60*6).mean() #open_price_position_relative_to_volatility_box = (df['open']-df['low'])/center #%% Plot # create two plots ax, ax2, ax3 = fplt.create_plot(symbol, rows=3) # 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(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
win.setWindowTitle('TradingView wannabe') layout = QGridLayout() win.setLayout(layout) win.showMaximized() combo = QComboBox() combo.setEditable(True) [ combo.addItem(i) for i in 'SPY ^AXJO GC=F GLD ^TNX BTC-USD ETH-USD XRP-USD'.split() ] layout.addWidget(combo, 0, 0, 1, 1) info = QLabel() layout.addWidget(info, 0, 1, 1, 1) ax = fplt.create_plot(init_zoom_periods=100) cross_hair_color = '#000000' ax.crosshair = fplt.FinCrossHair(ax, color=cross_hair_color) win.axs = [ax] # finplot requres this property axo = ax.overlay() layout.addWidget(ax.vb.win, 1, 0, 1, 2) # Data downloading @lru_cache(maxsize=15) def download(symbol): return yf.download(symbol, '2019-01-01') @lru_cache(maxsize=100) def get_name(symbol):
plots.append(fplt.plot(middleband, legend="MIDDLEBAND")) plots.append(fplt.plot(lowerband, legend="LOWERBAND")) else: # every time after we just update the data sources on each plot plots[0].update_data(candlesticks) plots[1].update_data(volumes) plots[2].update_data(upperband) plots[3].update_data(middleband) plots[4].update_data(lowerband) if __name__ == "__main__": try: kline = Kline() plots = [] fplt.foreground = '#FFFFFF' # 前景色 fplt.background = '#333333' # 背景色 fplt.odd_plot_background = '#333333' # 第二层图纸的背景色 fplt.cross_hair_color = "#FFFFFF" # 准星的颜色 ax, ax2 = fplt.create_plot('Realtime kline', init_zoom_periods=100, maximize=False, rows=2) fplt.add_legend("VOLUME", ax2) # 增加"VOLUME"图例 kline.update() fplt.timer_callback( kline.update, 5.0) # update (using synchronous rest call) every N seconds fplt.show() except: logger.error()
l = losses[i] = ni * v + m * l rs = gains / losses df['rsi'] = 100 - (100 / (1 + rs)) df.rsi.plot(ax=ax, legend='RSI') fplt.set_y_range(0, 100, ax=ax) fplt.add_band(30, 70, ax=ax) def plot_vma(df, ax): df.volume.rolling(20).mean().plot(ax=ax, color='#c0c030') symbol = 'XBTUSD' df = download_price_history(symbol=symbol) ax, axv, ax2, ax3, ax4 = fplt.create_plot( 'BitMEX %s heikin-ashi price history' % symbol, rows=5) ax.set_visible(xgrid=True, ygrid=True) # price chart plot_heikin_ashi(df, ax) plot_bollinger_bands(df, ax) plot_ema(df, ax) # volume chart plot_heikin_ashi_volume(df, axv) plot_vma(df, ax=axv) # some more charts plot_accumulation_distribution(df, ax2) plot_on_balance_volume(df, ax3) plot_rsi(df, ax4)
from io import StringIO from time import time # load data and convert date end_t = int(time()) start_t = end_t - 12 * 30 * 24 * 60 * 60 # twelve months symbol = 'SPY' 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) 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'
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()
df = yf.download('GOOG', start_day.isoformat(), now.isoformat(), interval='90m') dfms = yf.download('MSFT', start_day.isoformat(), now.isoformat(), interval='90m') # resample to daily candles, i.e. five 90-minute candles per business day dfd = df.Open.resample('D').first().to_frame() dfd['Close'] = df.Close.resample('D').last() dfd['High'] = df.High.resample('D').max() dfd['Low'] = df.Low.resample('D').min() ax, ax2 = fplt.create_plot('Alphabet Inc.', rows=2, maximize=False) ax2.disable_x_index() # second plot is not timebased # plot down-sampled daily candles first 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
tdup,tddn = td_sequential(df['close']) df['tdup'] = [('%i'%i if 0<i<10 else '') for i in tdup] df['tddn'] = [('%i'%i if 0<i<10 else '') for i in tddn] # pick columns for our three data sources: candlesticks and TD sequencial labels for up/down candlesticks = df['time open close high low'.split()] volumes = df['time open close volume'.split()] td_up_labels = df['time high tdup'.split()] td_dn_labels = df['time low tddn'.split()] if not plots: # first time we create the plots global ax plots.append(fplt.candlestick_ochl(candlesticks)) plots.append(fplt.volume_ocv(volumes, ax=ax.overlay())) plots.append(fplt.labels(td_up_labels, color='#009900')) plots.append(fplt.labels(td_dn_labels, color='#990000', anchor=(0.5,0))) else: # every time after we just update the data sources on each plot plots[0].update_data(candlesticks) plots[1].update_data(volumes) plots[2].update_data(td_up_labels) plots[3].update_data(td_dn_labels) plots = [] ax = fplt.create_plot('Realtime Bitcoin/Dollar 1m TD Sequential (BitFinex REST)', init_zoom_periods=100, maximize=False) update() fplt.timer_callback(update, 5.0) # update (using synchronous rest call) every N seconds fplt.show()
'''Plot quote table (in millions). We're using lables on top of a heatmap to create sort of a table.''' ax.set_visible(yaxis=False) # Y axis is useless on our table def skip_y_crosshair_info(x, y, xt, yt): # we don't want any Y crosshair info on the table return xt, '' fplt.add_crosshair_info(skip_y_crosshair_info, ax=ax) fplt.set_y_range(0, 2, ax) # 0-1 for bid row, 1-2 for ask row # add two columns for table cell colors quotes[1] = -quotes['askSize'] * 0.5 / quotes['askSize'].max() + 0.5 quotes[0] = +quotes['bidSize'] * 0.5 / quotes['bidSize'].max() + 0.5 ts = [int(t.timestamp()) for t in quotes.index] colmap = fplt.ColorMap([0.0, 0.5, 1.0], [[200, 80, 60], [200, 190, 100], [40, 170, 30]]) # traffic light colors fplt.heatmap(quotes[[1, 0]], colmap=colmap, colcurve=lambda x: x, ax=ax) # linear color mapping fplt.labels(ts, [1.5]*count, ['%.1f'%(v/1e6) for v in quotes['askSize']], ax=ax2, anchor=(0.5, 0.5)) fplt.labels(ts, [0.5]*count, ['%.1f'%(v/1e6) for v in quotes['bidSize']], ax=ax2, anchor=(0.5, 0.5)) prices, quotes = download_resample() fplt.max_zoom_points = 5 fplt.right_margin_candles = 0 ax,ax2 = fplt.create_plot(f'BitMEX {downsample}m quote bubble plot + quote table', rows=2, maximize=False) fplt.windows[0].ci.layout.setRowStretchFactor(0, 10) # make primary plot large, and implicitly table small candles = fplt.candlestick_ochl(prices[['Open','Close','High','Low']], ax=ax) candles.colors.update(dict(bear_body='#fa8')) # bright red, to make bubbles visible fplt.volume_ocv(prices[['Open','Close','Volume']], ax=ax.overlay()) plot_quote_bubbles(quotes, ax=ax) plot_quote_table(quotes, ax=ax2) fplt.show()
#!/usr/bin/env python3 import finplot as fplt import pandas as pd import requests # download, extract times and candles url = 'https://www.tensorcharts.com/tensor/bitmex/XBTUSD/heatmapCandles/15min' data = requests.get(url).json() times = pd.to_datetime([e['T'] for e in data]) candles = [(e['open'],e['close'],e['high'],e['low']) for e in data] df_candles = pd.DataFrame(index=times, data=candles) # extract volume heatmap as a PRICE x VOLUME matrix orderbooks = [(e['heatmapOrderBook'] or []) for e in data] prices = sorted(set(prc for ob in orderbooks for prc in ob[::2])) vol_matrix = [[0]*len(prices) for _ in range(len(times))] for i,orderbook in enumerate(orderbooks): for price,volume in zip(orderbook[::2],orderbook[1::2]): j = prices.index(price) vol_matrix[i][j] = volume df_volume_heatmap = pd.DataFrame(index=times, columns=prices, data=vol_matrix) # plot fplt.create_plot('BitMEX BTC 15m orderbook heatmap') fplt.candlestick_ochl(df_candles) fplt.heatmap(df_volume_heatmap, filter_limit=0.1, whiteout=0.1) fplt.show()
#!/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)
basequote = base_asset[[ 'open', 'high', 'low', 'close' ]] * quote_asset[['open', 'high', 'low', 'close']] # averaging volume. basequote['vol'] = ( (base_asset['tick_volume'] + quote_asset['tick_volume']) / 2) basequote.set_index(keys=[base_asset['time']], inplace=True) return basequote symbol1 = input('Enter base symbol: ').upper() symbol2 = input('Enter quote symbol: ').upper() period = int(input('Enter period in Hours: ')) synthetic_asset = synthesize(symbol1, symbol2, period) print(synthetic_asset) candle_stick_data = fplt.PandasDataSource( synthetic_asset[['open', 'close', 'high', 'low']]) volume = fplt.PandasDataSource(synthetic_asset[['open', 'close', 'vol']]) ax = fplt.create_plot(title=f'{symbol1}/{symbol2}', rows=1) axo = ax.overlay() candle_plot = fplt.candlestick_ochl(candle_stick_data, ax=ax) volume_olay = fplt.volume_ocv(volume, ax=axo) fplt.show() mt5.shutdown()
t -= t % (60*interval_mins) c = trade['price'] if t < df['t'].iloc[-1]: # ignore already-recorded trades continue elif t > df['t'].iloc[-1]: # add new candle o = df['c'].iloc[-1] h = c if c>o else o l = o if o<c else c df1 = pd.DataFrame(dict(t=[t], o=[o], c=[c], h=[l], l=[l])) df = pd.concat([df, df1], ignore_index=True, sort=False) else: # update last candle i = df.index.max() df.loc[i,'c'] = c if c > df.loc[i,'h']: df.loc[i,'h'] = c if c < df.loc[i,'l']: df.loc[i,'l'] = c update_plot(df) if __name__ == '__main__': df = pd.DataFrame(price_history()) ws = BitMEXWebsocket(endpoint=baseurl+'/v1', symbol='XBTUSD') ax = fplt.create_plot('Realtime Bitcoin/Dollar 1m (BitMEX websocket)', init_zoom_periods=100, maximize=False) update_plot(df) fplt.timer_callback(update_data, 1.0) # update every second fplt.show()
# define time range start = dt.date.today() - dt.timedelta(days = 365*10) end = dt.datetime.now() stock = 'AAPL' df = yf.download(stock,start, end, interval='1d') # 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']