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 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 update(): # if delta_bar.df[-1]['open'] != 0: df = delta_bar.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 ) # Удаляем колонку с датой и временем, т.к. дата у нас теперь в индексе print(df) # pick columns for our three data sources: candlesticks and TD candlesticks = df['open close high low'.split()] deltabarsec = df['open close delta_time_sec'.split()] delta = df['open close delta'.split()] maxvolcluster = df['max_vol_cluster'] if not plots: # first time we create the plots global ax plots.append(fplt.candlestick_ochl(candlesticks)) plots.append(fplt.volume_ocv(deltabarsec, ax=ax2)) plots.append(fplt.volume_ocv(delta, ax=ax3)) plots.append(fplt.plot(maxvolcluster, 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 __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 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 __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 update(): # load data limit = 500 start = int(time.time()*1000) - (500-2)*60*1000 url = 'https://api.bitfinex.com/v2/candles/trade:1m:tBTCUSD/hist?limit=%i&sort=1&start=%i' % (limit, start) table = requests.get(url).json() df = pd.DataFrame(table, columns='time open close high low volume'.split()) # calculate indicator 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)
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)
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()] ax.reset() # remove previous plots axo.reset() # remove previous plots fplt.candlestick_ochl(price) fplt.plot(ma20, legend='MA-20') fplt.plot(ma50, legend='MA-50') 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 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 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 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 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 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 update(self): table = self.exchange.get_kline(self.timeframe) table.reverse() try: df = pd.DataFrame( table, columns='time open high low close volume currency_volume'. split()) df = df.astype({ 'time': 'datetime64[ns]', 'open': 'float64', 'high': 'float64', 'low': 'float64', 'close': 'float64', 'volume': 'float64', 'currency_volume': 'float64' }) except: df = pd.DataFrame( table, columns='time open high low close volume'.split()) df = df.astype({ 'time': 'datetime64[ns]', 'open': 'float64', 'high': 'float64', 'low': 'float64', 'close': 'float64', 'volume': 'float64' }) candlesticks = df['time open close high low'.split()] volumes = df['time open close volume'.split()] result = self.indicators.MACD(12, 26, 9) dif = result['DIF'] dea = result['DEA'] macd = result['MACD'] if not plots: # first time we create the plots global ax, ax2, ax3 plots.append(fplt.candlestick_ochl(candlesticks)) plots.append(fplt.volume_ocv(volumes, ax=ax2)) plots.append(fplt.plot(dif, ax=ax3, legend="DIF")) plots.append(fplt.plot(dea, ax=ax3, legend="DEA")) plots.append(fplt.plot(macd, ax=ax3, legend="MACD")) 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(dif) plots[3].update_data(dea) plots[4].update_data(macd)
def update(self): table = self.exchange.get_kline(self.timeframe) table.reverse() try: df = pd.DataFrame( table, columns='time open high low close volume currency_volume'. split()) df = df.astype({ 'time': 'datetime64[ns]', 'open': 'float64', 'high': 'float64', 'low': 'float64', 'close': 'float64', 'volume': 'float64', 'currency_volume': 'float64' }) except: df = pd.DataFrame( table, columns='time open high low close volume'.split()) df = df.astype({ 'time': 'datetime64[ns]', 'open': 'float64', 'high': 'float64', 'low': 'float64', 'close': 'float64', 'volume': 'float64' }) candlesticks = df['time open close high low'.split()] volumes = df['time open close volume'.split()] boll = self.indicators.BOLL(20) upperband = boll['upperband'] middleband = boll['middleband'] lowerband = boll['lowerband'] if not plots: # first time we create the plots global ax, ax2 plots.append(fplt.candlestick_ochl(candlesticks)) plots.append(fplt.volume_ocv(volumes, ax=ax2)) plots.append(fplt.plot(upperband, legend="UPPERBAND")) 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)
def update(self): table = self.exchange.get_kline(self.timeframe) table.reverse() try: df = pd.DataFrame( table, columns='time open high low close volume currency_volume'. split()) df = df.astype({ 'time': 'datetime64[ns]', 'open': 'float64', 'high': 'float64', 'low': 'float64', 'close': 'float64', 'volume': 'float64', 'currency_volume': 'float64' }) except: df = pd.DataFrame( table, columns='time open high low close volume'.split()) df = df.astype({ 'time': 'datetime64[ns]', 'open': 'float64', 'high': 'float64', 'low': 'float64', 'close': 'float64', 'volume': 'float64' }) candlesticks = df['time open close high low'.split()] volumes = df['time open close volume'.split()] ma = self.indicators.MA(20, 30) ma1 = ma[0] ma2 = ma[1] if not plots: # first time we create the plots global ax, ax2 plots.append(fplt.candlestick_ochl(candlesticks)) plots.append(fplt.volume_ocv(volumes, ax=ax2)) plots.append(fplt.plot(ma1, legend="MA20")) plots.append(fplt.plot(ma2, legend="MA30")) 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(ma1) plots[3].update_data(ma2)
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 update(): # load data limit = 500 start = int(time.time() * 1000) - (500 - 2) * 60 * 1000 url = 'https://api.bitfinex.com/v2/candles/trade:1m:tBTCUSD/hist?limit=%i&sort=1&start=%i' % ( limit, start) table = requests.get(url).json() df = pd.DataFrame(table, columns='time open close high low volume'.split()) # 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()] 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())) else: # every time after we just update the data sources on each plot plots[0].update_data(candlesticks) plots[1].update_data(volumes)
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)
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 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'],
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) fplt.bar(btc.Close.resample('Y').last().pct_change().dropna() * 100, ax=ax4) # calculate monthly returns, display as a 4x3 heatmap months = btc['Adj Close'].resample( 'M').last().pct_change().dropna().to_frame() * 100 months.index = mnames = months.index.month_name().to_list()
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' # 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
'''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()
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()
def plot_bars(bars: pd.DataFrame): ax1, ax2 = fplt.create_plot('Prices+Vol', rows=2) fplt.candlestick_ochl( bars[['price_open', 'price_close', 'price_high', 'price_low']], ax=ax1) fplt.volume_ocv(bars[['price_open', 'price_close', 'volume_sum']], ax=ax2) fplt.show()
df['wpr_2'] = talib.WILLR(df['high'].values, df['low'].values, df['close'].values, timeperiod=96) df['line'] = -50 # Добавляю колонку с линией для индикаторов print(df) # создаем 4 окна ax, ax2, ax3, ax4 = fplt.create_plot(symbol, rows=4) # рисуем свечной график в основном окне candles = df[['open', 'close', 'high', 'low']] fplt.candlestick_ochl(candles, ax=ax) # рисуем график времени дельты свечи delta_time = df[['open', 'close', 'delta_time']] fplt.volume_ocv(delta_time, ax=ax2) # рисуем график количества тиков ticks = df[['open', 'close', 'ticks']] fplt.volume_ocv(ticks, ax=ax3) # WPR df[['wpr_1']].plot(ax=ax4, legend='WPR14', color='#008800') df[['wpr_2']].plot(ax=ax4, legend='WPR96', color='#EF5350') df[['line' ]].plot(ax=ax4, color='#000000') # Построение центральной линии для индикаторов fplt.show()
"""A PandasDataSource object can be created to pass as argument in candlestick_ochl() function.""" import pandas_datareader as pdr import finplot as fplt # Getting timeseries k = pdr.DataReader('AAPL', data_source='yahoo', start='2020-01-01') # Setting PandasDataSource objects for OCHL & volume price = fplt.PandasDataSource(k[['Open', 'Adj Close', 'High', 'Low']]) volume = fplt.PandasDataSource(k[['Open', 'Close', 'Volume']]) # Setting Graph window with 2 axes ax, ax2 = fplt.create_plot(title='Aaple Inc', rows=2) # Setting overlay on first axis axo = ax.overlay() # plotting candlestick chart fplt.candlestick_ochl(price) # fplt.volume_ocv(volume, ax=axo) # plotting volume on overlay. fplt.volume_ocv(volume, ax=ax2) # plotting volume on second axis. # Adding text on top left corner fplt.add_text(ax=ax, pos=(k.index[1], k.High[-1]), s='Aaple Inc') fplt.show()