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 save_plot(self, plot_title, kbars): fplt = self.setup_plot(plot_title, kbars) with open(f'{plot_title}.png', 'wb') as f: fplt.timer_callback(lambda: fplt.screenshot(f), 1, single_shot=True) fplt.show()
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 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 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() 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 __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 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 getStockHistory(s): stock = Stock.Stock(s) t = stock.history() # print(t.json()) # plt.plot(t.json()['o']) # plt.plot(t.json()['h']) # plt.plot(t.json()['l']) # plt.plot(t.json()['c']) # plt.title(stock.ticker) # plt.show() # df = t.json() # df = pd.read_json(t.json()) # df = pd.DataFrame.from_dict(t.json()) # print(df) # fplt.candlestick_ochl(df[['o', 'c', 'h', 'l']]) # fplt.show() df = f = yfinance.download('XRP') fplt.candlestick_ochl(df[['Open', 'Close', 'High', 'Low']]) 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 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 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()
def plot_price(df): df = df.set_index('time') fplt.candlestick_ochl(df[['open', 'close', 'high', 'low']]) fplt.show()
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 combo.currentTextChanged.connect(update) update(combo.currentText()) fplt.show(qt_exec=False) # prepares plots when they're all setup win.show() app.exec_()
def plotter(): """Takes the input value from widgets and creates a candlestick plot.""" base = (symbolVar.get()).upper() quote = quoteCurrency.get() start_date = startDateCal.get_date() end_date = endDateCal.get_date() interval = intervalVar.get() #______If no symbol entered_______# if len(base) == 0: errorBox() return None else: pass base_ticker = yf.Ticker(base) #_____If symbol is invalid________# try: base_currency = base_ticker.info['currency'] except ImportError: errorBox2() return None else: pass if quote == 'Select' or quote == base_currency: # No currency is selected or base denomination = selected currency. base_ticker = yf.Ticker(base) base_quote = base_ticker.history( start=start_date, end=end_date, interval=interval).drop( columns=['Dividends', 'Stock Splits', 'Volume']) else: # A currency is selected. base_quote = synthesize(base, quote, start_date, end_date, interval) base_quote.dropna(inplace=True) # print(base_quote) # Calculating Simple Moving averages base_quote['SMA 1'] = base_quote['Close'].rolling(sma1Var.get()).mean() base_quote['SMA 2'] = base_quote['Close'].rolling(sma2Var.get()).mean() # print(base_quote) # Calculating Standard-deviation. base_quote['pct_change'] = base_quote['Close'].pct_change() * 100 base_quote['std-dev'] = base_quote['pct_change'].rolling( stdDevVar.get()).std() # print(base_quote) candle_stick_data = fplt.PandasDataSource( base_quote[['Open', 'Close', 'High', 'Low']]) ax, ax2 = fplt.create_plot(title=f"{base}/{quote}", rows=2) candle_plot = fplt.candlestick_ochl(candle_stick_data, ax=ax) # Plotting SMAs sma1 = fplt.plot(base_quote['SMA 1'], legend=f'{sma1Var.get()} SMA', ax=ax) sma2 = fplt.plot(base_quote['SMA 2'], legend=f'{sma2Var.get()} SMA', ax=ax) # Ploting StdDev stdDevPlot = fplt.plot(base_quote['std-dev'], legend=f'{stdDevVar.get()} period std-dev', ax=ax2) fplt.add_text(pos=(base_quote.index[-1], base_quote['std-dev'].iloc[-1]), s=f"{base_quote['std-dev'].iloc[-1].round(2)}%", ax=ax2) fplt.show()
def draw_plot(self, plot_title, kbars): fplt = self.setup_plot(plot_title, kbars) fplt.autoviewrestore() fplt.show()
def plot_signal(kline, buy_signal=None, sell_signal=None, *args): """回测完成后调用此函数绘制k线图与指标""" fplt.foreground = '#FFFFFF' fplt.background = '#333333' fplt.odd_plot_background = '#333333' fplt.cross_hair_color = "#FFFFFF" ax, ax2, ax3 = fplt.create_plot('历史K线图', init_zoom_periods=100, maximize=True, rows=3) fplt.add_legend("K线主图", ax) fplt.add_legend("成交量", ax2) fplt.add_legend("指标副图", ax3) df = pd.DataFrame(kline) df = df[[0, 1, 2, 3, 4, 5]] columns = ['time', 'open', 'high', 'low', 'close', 'volume'] df.columns = columns 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()] fplt.candlestick_ochl(candlesticks) fplt.volume_ocv(volumes, ax=ax2) if args: count = 1 for i in args: indicators = pd.Series(i) fplt.plot(df['time'], indicators, legend="指标{}".format(count), ax=ax3) count += 1 if buy_signal: for i in buy_signal: df.loc[df['high'] == buy_signal[buy_signal.index(i)], "buy_signal"] = df['high'] fplt.plot(df['time'], df['buy_signal'], ax=ax, color="#FF0000", style='^', width=2, legend='买入信号') if sell_signal: for i in sell_signal: df.loc[df['low'] == sell_signal[sell_signal.index(i)], "sell_signal"] = df['low'] fplt.plot(df['time'], df['sell_signal'], ax=ax, color="#00FF00", style='v', width=2, legend='卖出信号') fplt.show()
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()
def show(self): """最后必须调用此函数以显示图像""" fplt.show()
def show(): fplt.show()
df_symbol = pd.DataFrame(read_ticker(file_csv), columns=['Ticker']) df_symbol["HQM Score"] = 0 symbols = df_symbol['Ticker'].tolist() num_symbols = len(symbols) fa_dict = {} fa_results = get_sector_profiles_nodb(symbols) for row in fa_results: fa_dict[row[0]] = row for i in df_symbol.index: if not i % 5: finplot = reload(finplot) print(f"\n========== {i+1} / {num_symbols} =========================\n") symbol = df_symbol.loc[i, "Ticker"] fa_info = fa_dict.get(symbol, [symbol,"N/A","N/A","N/A",0,"N/A",0,0]) file_png, log_msg = plt_chart(fa_info, save_chart=True, interactive=False) if file_png: print(log_msg) generate_html(file_csv, file_png, i) finplot.show() except KeyboardInterrupt: sys.exit()
def main(): app = QtWidgets.QApplication(sys.argv) main = MainWindow() finplot.show(qt_exec=False) main.show() sys.exit(app.exec_())
def show_day_plot(self, instance): aux = int(instance.text.split('-')[0]) #print ('fechaaa') #print (aux) '''TERMINA TUS WEADAS ACA''' #print (self.marketdata) #temp = pd.date_range(start=temp['time'][self.fechas[0]], end=temp['time'][self.fechas[1]], freq='D') #print (self.fechas[0]) #print (self.fechas[0],self.fechas[1]) #datex = self.fechas[3] #print (rt.Singleton.getInstance().result) try: self.marcadores = pd.read_pickle('estrategia1.pkl') self.marketdata['marker'] = self.marcadores['marker'] except: print('mierda') desde = self.fechas[aux] + timedelta(hours=5) hasta = desde + timedelta(hours=24) temp = self.marketdata[(self.marketdata.time > desde) & (self.marketdata.time <= hasta)] #print (temp) #print (temp['time'][self.fecha]) #temp = self.get_frac_df(temp,) #print ('actualizado') #print ('SELECCIONADO') #print (temp) #print (temp.dtypes) '''TODO :MEJORA EL FFT que agrege en la ventana izquierda en matplotlib''' #self.plot_fft(temp,'filtered') ax, ax2 = fplt.create_plot('NASDAQ', rows=2) #,maximize=True) try: '''CANDLESTICK CHARTS''' candle_src = fplt.PandasDataSource( temp[['time', 'open', 'close', 'high', 'low']]) fplt.candlestick_ochl(candle_src, ax=ax, draw_body=True, draw_shadow=True) fplt.plot(temp['time'], temp['sma200'], ax=ax, color='#0000ff', legend='ma-200') fplt.plot(temp['time'], temp['filtered'], ax=ax, color='#ff00ff', legend='filtrado', width=2) try: '''OBTIENE LAS ORDENES DE COMPRA-VENTA''' buys = pd.read_pickle("book_buy.pkl") #sell = pd.read_pickle("book_sell.pkl") '''PROCEDE A PLOTEAR''' print('compras') print(buys) pass except: print("[ ERROR ] Fallo al obtener las ordenes de compra/venta") pass '''VOLUMEN CHARTS''' volume_src = fplt.PandasDataSource( temp[['time', 'open', 'close', 'volume']]) fplt.volume_ocv(volume_src, ax=ax2) # 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(temp['time'], temp['marker'], ax=ax, color='#000000', style='^', legend='dumb mark') #with pd.option_context('display.max_rows', None, 'display.max_columns', None): # more options can be specified also # print (self.marcadores) '''INTERMEDIOS''' #te = np.random.normal(size=len(temp)) #fplt.plot(temp['time'], te, ax=ax2, color='#001177', legend='vortex pos') #fplt.plot(temp['time'], temp['vortex_n'], ax=ax2, color='#ff0000', legend='vortex neg') #fplt.set_y_range(ax2, -4.4, +4.4) # fix y-axis range # draw some random crap on our second plot #temp['rnd'] = np.random.normal(size=len(temp)) #print (temp.vortexn) #fplt.plot(temp['time'], temp['vortexn'], ax=ax3, color='#992277', legend='stuff') #fplt.set_y_range(ax3, -10.4, +10.7) # fix y-axis range # finally a volume bar chart in our third plot fplt.show() #pass except Exception as e: print(e) pass
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()
import pandas_datareader.data as web # from pandas_datareader.yahoo import options import datetime as dt # import matplotlib.pyplot as plt import pandas as pd import finplot as fin assets = { 'Alphabet': 'GOOGL', 'Verizon': 'VZ', 'Amazon': 'AMZN', 'Coca-cola': 'KO', 'JP-Morgan': 'JPM', 'General Electric': 'GE', 'Goldman': 'GS' } start = dt.datetime(2020, 1, 1) end = dt.datetime.now() fb = web.DataReader(assets['Goldman'], 'yahoo', start, end) # print(fb) candles = fb[['Open', 'Close', 'High', 'Low']] fin.create_plot(title='Goldman') fin.candlestick_ochl(candles) fin.show()