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(): # 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()) df['time'] //= 1000 # convert ms to seconds # 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 the gree datasrc0 = fplt.PandasDataSource(df['time open close high low'.split()]) datasrc1 = fplt.PandasDataSource(df['time high tdup'.split()]) datasrc2 = fplt.PandasDataSource(df['time low tddn'.split()]) if not plots: # first time we create the plots plots.append(fplt.candlestick_ochl(datasrc0, ax=ax)) plots.append(fplt.labels_datasrc(datasrc1, color='#009900', ax=ax)) plots.append( fplt.labels_datasrc(datasrc2, color='#990000', ax=ax, anchor=(0.5, 0))) else: # every time after we just update the data sources on each plot plots[0].update_datasrc(datasrc0) plots[1].update_datasrc(datasrc1) plots[2].update_datasrc(datasrc2)
def plot_heikin_achi(df, ax): df['h_close'] = (df.open + df.close + df.high + df.low) * 0.25 df['h_open'] = (df.open.shift() + df.close.shift()) * 0.5 df['h_high'] = df[['high', 'h_open', 'h_close']].max(axis=1) df['h_low'] = df[['low', 'h_open', 'h_close']].min(axis=1) candle_datasrc = fplt.PandasDataSource( df['time h_open h_close h_high h_low'.split()]) fplt.candlestick_ochl(candle_datasrc, ax=ax)
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 update_plot(df): calc_bollinger_bands(df) datasrc0 = fplt.PandasDataSource(df['t o c h l'.split()]) datasrc1 = fplt.PandasDataSource(df['t bbh'.split()]) datasrc2 = fplt.PandasDataSource(df['t bbl'.split()]) if not plots: candlestick_plot = fplt.candlestick_ochl(datasrc0, ax=ax) plots.append(candlestick_plot) plots.append(fplt.plot_datasrc(datasrc1, color='#4e4ef1', ax=ax)) plots.append(fplt.plot_datasrc(datasrc2, color='#4e4ef1', ax=ax)) # redraw using bitmex colors candlestick_plot.bull_color = '#388d53' candlestick_plot.bull_frame_color = '#205536' candlestick_plot.bull_body_color = '#52b370' candlestick_plot.bear_color = '#d56161' candlestick_plot.bear_frame_color = '#5c1a10' candlestick_plot.bear_body_color = '#e8704f' candlestick_plot.repaint() else: plots[0].update_datasrc(datasrc0) plots[1].update_datasrc(datasrc1) plots[2].update_datasrc(datasrc2)
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 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 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()
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()
"""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()
'H': 'high', 'L': 'low', 'V': 'volume' }) df.to_csv(symbol + '.csv', index=False) else: 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,
def plot_heikin_achi_volume(df, ax): volume_datasrc = fplt.PandasDataSource( df['time h_open h_close volume'.split()]) fplt.volume_ocv(volume_datasrc, ax=ax)
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 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