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()
#!/usr/bin/env python3 import finplot as fplt import numpy as np import pandas as pd dates = pd.date_range('01:00', '01:00:01.200', freq='1ms') prices = pd.Series(np.random.random(len(dates))).rolling(30).mean() + 4 fplt.plot(dates, prices, width=3) line = fplt.add_line((dates[100], 4.4), (dates[1100], 4.6), color='#9900ff', interactive=True) ## fplt.remove_primitive(line) text = fplt.add_text((dates[500], 4.6), "I'm here alright!", color='#bb7700') ## fplt.remove_primitive(text) rect = fplt.add_rect((dates[700], 4.5), (dates[850], 4.4), color='#8c8', interactive=True) ## fplt.remove_primitive(rect) def save(): fplt.screenshot(open('screenshot.png', 'wb')) fplt.timer_callback(save, 0.5, single_shot=True) # wait some until we're rendered fplt.show()
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() mnames = mnames[mnames.index('January'):][:12] mrets = [months.loc[mname].mean()[0] for mname in mnames] hmap = pd.DataFrame(columns=[2, 1, 0], data=np.array(mrets).reshape((3, 4)).T) hmap = hmap.reset_index( ) # use the range index as X-coordinates (if no DateTimeIndex is found, the first column is used as X) colmap = fplt.ColorMap( [0.3, 0.5, 0.7], [[255, 110, 90], [255, 247, 0], [60, 255, 50]]) # traffic light fplt.heatmap(hmap, rect_size=1, colmap=colmap, colcurve=lambda x: x, ax=ax5) for j, mrow in enumerate(np.array(mnames).reshape((3, 4))): for i, month in enumerate(mrow): s = month + ' %+.2f%%' % hmap.loc[i, 2 - j] fplt.add_text((i, 2.5 - j), s, anchor=(0.5, 0.5), ax=ax5) ax5.set_visible(crosshair=False, xaxis=False, yaxis_labels=False) # hide junk for a more pleasing look fplt.show()
import finplot as fplt import numpy as np import pandas as pd # Creating a randon Datetime index for x-axes. dates = pd.date_range('01:00', '01:00:01.200', freq='1ms') # Creating a random price Series for y-axes prices = pd.Series(np.random.random(len(dates))).rolling(30).mean() + 4 # plotting a line fplt.plot(dates, prices, legend='Nonscence') # Drawing a interactive line line = fplt.add_line((dates[100], 4.4), (dates[1100], 4.6), color='#9900ff', interactive=True) # removing the interactive line # fplt.remove_line(line) # adding an immovable text. text = fplt.add_text(pos=(dates[50], 4.4), s="I'm here alright!", color='#bb7700') # removing the immovable text. # fplt.remove_text(text) # displaying the plot fplt.show()
daily_plot = fplt.candlestick_ochl(dfd.dropna(), candle_width=5) daily_plot.colors.update( dict(bull_body='#bfb', bull_shadow='#ada', bear_body='#fbc', bear_shadow='#dab')) daily_plot.x_offset = 3.1 # resample() gets us start of day, offset +1.1 (gap+off center wick) # plot high resolution on top fplt.candlestick_ochl(df[['Open', 'Close', 'High', 'Low']]) # scatter plot correlation between Google and Microsoft stock df['ret_alphabet'] = df.Close.pct_change() df['ret_microsoft'] = dfms.Close.pct_change() dfc = df.dropna().reset_index(drop=True)[['ret_alphabet', 'ret_microsoft']] fplt.plot(dfc, style='o', color=1, ax=ax2) # draw least-square line errfun = lambda arr: [ y - arr[0] * x + arr[1] for x, y in zip(dfc.ret_alphabet, dfc.ret_microsoft) ] line = scipy.optimize.least_squares(errfun, [0.01, 0.01]).x linex = [dfc.ret_alphabet.min(), dfc.ret_alphabet.max()] liney = [linex[0] * line[0] + line[1], linex[1] * line[0] + line[1]] fplt.add_line((linex[0], liney[0]), (linex[1], liney[1]), color='#993', ax=ax2) fplt.add_text((linex[1], liney[1]), 'k=%.2f' % line[0], color='#993', ax=ax2) fplt.add_legend('Alphabet vs. Microsft 90m correlation', ax=ax2) fplt.show()
"""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()
if (e > 40): promedio_anterior = df['close'].iloc[e - 30:e] #print (promedio_anterior) accu = 0 for h in promedio_anterior: accu += h promedio = accu / len(promedio_anterior) print(str(promedio) + " << " + str(df['close'][e])) #print ( ema_14[e] > ema_32[e] , ema_14[e-1] < ema_32[e-1]) #detecta subida if (ema_14[e] > ema_32[e] and ema_14[e - 1] < ema_32[e - 1] and promedio > df['close'][e]): point.append(df['close'][e]) inicio = (df['time'][e], df['close'][e]) text = fplt.add_text((inicio[0], inicio[1]), str(portfolio), color='#bbff00') debe_salir = True #detecta bajada if (debe_salir and ema_14[e] < ema_32[e] and ema_14[e - 1] > ema_32[e - 1]): crossdown.append(df['close'][e]) debe_salir = False fin = (df['time'][e], df['close'][e]) profit = (fin[1] - inicio[1]) / tick_size print("===================================") #print (df['close'][e-4:e] ) print("inicio > " + str(inicio[1])) print("fin > " + str(fin[1])) print("diference >> " + str(fin[1] - inicio[1])) print("ticks >> " + str((fin[1] - inicio[1]) / tick_size))
import pandas as pd mt5.initialize() # symbol = input('Enter the symbol').upper() rates = pd.DataFrame( mt5.copy_rates_from_pos('EURUSD', mt5.TIMEFRAME_H1, 1, 240)).drop(columns=['spread', 'real_volume']) rates['time'] = pd.to_datetime(rates['time'], unit='s') #______Plotting_______# ax, ax2 = fplt.create_plot(title='EURUSD H1', rows=2) axo = ax.overlay() fplt.candlestick_ochl(rates[['time', 'open', 'close', 'high', 'low']], ax=ax) fplt.volume_ocv(rates[['time', 'open', 'close', 'tick_volume']], ax=axo) fplt.plot(rates['close'].ewm(8).mean(), legend='8 EMA', ax=ax) fplt.plot(rates['close'].ewm(24).mean(), legend='24 EMA', ax=ax) roll_std = (rates['close'].rolling(24).std()) * 100 fplt.plot(roll_std, legend='24 std-dev', ax=ax2) fplt.add_text(ax=ax2, pos=(rates['time'].iloc[-1], roll_std[roll_std.index[-1]]), s=str(roll_std[roll_std.index[-1]])) # print(roll_std[roll_std.index[-1]]) fplt.show() mt5.shutdown()
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()