def chart(): df = dataframe() df.index = pd.DatetimeIndex(df['timestamp']) df = df.iloc[::-1] s = mpf.make_mpf_style(base_mpf_style='charles', gridcolor='#555555', gridstyle="--", rc={'axes.edgecolor': 'white', 'font.size': 5}) fig, axlist = mpf.plot(df, type='candle', style=s, title= coin, ylabel = 'Price (€)', volume=True, warn_too_much_data=9999999, returnfig=True) mpf.show(block=True)
def show_adv(self, ftitle="Stock", **kwargs): """ 顯示進階K線圖,K線搭配一主圖指標與兩個副圖指標 使用mplfinance實現之(panel method) 已定義的作圖參數: ti_main = "SMA" / "VWMA" ti_sub1 = "KD" / "MACD" / "STD" / "VIX" / "CVOL" ti_sub2 = "KD" / "MACD" / "STD" / "VIX" / "CVOL" """ self._setrun(**kwargs) # 進行參數驗證與指標計算 dest = Dpath + '\\' + ftitle + ".png" mc = mpf.make_marketcolors(up='r', down='g', inherit=True) ms = mpf.make_mpf_style(base_mpf_style = "yahoo", \ marketcolors = mc, y_on_right = True) # 不支援中文字型,圖表文字需為英文 mfargs = dict(type = "candle", volume = True, \ columns = ("O", "H", "L", "C", "V"), \ show_nontrading = False, returnfig = True, \ figsize = (self.fx, self.fy), \ title = ftitle, style = ms, ylabel = "Price", \ ylabel_lower = "Volume in shares", \ panel_ratios = (1, 1)) aps = [] if "ti_main" in kwargs: tidf = self.val_main.copy() isma = False if kwargs["ti_main"] == "SMA" or kwargs["ti_main"] == "VWMA": isma = True # 主圖技術指標為均線類型 for i in range(0, tidf.shape[1]): aps.append(mpf.make_addplot(tidf.iloc[:, i], \ color = MA_Colors[i])) if isma: # 補均線扣抵記號,配色同均線 aps.append(mpf.make_addplot(self.sig_main.iloc[:, i], \ type = "scatter", \ markersize = 200, \ marker = '^', \ color = MA_Colors[i])) pid = 1 # Panel ID = 0 for candlestick, 1 for volume if "ti_sub1" in kwargs: # pid = 2 pid += 1 ap2 = self._setsubti(self.val_sub1, kwargs["ti_sub1"], pid) for item in ap2: aps.append(item) if "ti_sub2" in kwargs: # pid = 3 (or 2 if ti_sub1 is not assigned) pid += 1 ap3 = self._setsubti(self.val_sub2, kwargs["ti_sub2"], pid) for item in ap3: aps.append(item) if len(aps) > 0: if pid == 2: mfargs["panel_ratios"] = (2, 1, 1) elif pid == 3: mfargs["panel_ratios"] = (3, 1, 1, 1) fig, axes = mpf.plot(self.df, addplot=aps, **mfargs) else: fig, axes = mpf.plot(self.df, **mfargs) mpf.show() fig.savefig(dest) return None
def updateChart(q, x): global timeP global client global ax timeP = x fig, ax, client = main() ani = animation.FuncAnimation(fig, animateFunc, interval=200) mpf.show()
def check(cls, data_grabber: DataGrabber, major_timeframe_in_minutes: int = 60, minor_timeframe_in_minutes: int = 5, show_chart: bool = False, save_chart: bool = False) -> None: df = data_grabber.fetch() if df is None: return df_resampled_into_major_timeframe = cls.resample( df).iloc[-cls.BAR_NUMS_SLIDING_WINDOW:] df = df.iloc[-cls.BAR_NUMS_SLIDING_WINDOW:] zones, levels = ZoneFinder.find_key_zones_and_levels( df_resampled_into_major_timeframe, find_levels_threshold=1, merge_levels_threshold=0.0002, zone_weight_threshold=5) market_name = data_grabber.get_symbols() df_latest = df.tail(3) setup = SetupFinder.current_setup(zones, df_latest) if not setup: return message = f'[{get_now_timestamp_string()}] {market_name} setup: {setup}' image_path = None if show_chart or save_chart: plot_config = dict( df_in_major_timeframe=df_resampled_into_major_timeframe, major_timeframe_in_minutes=major_timeframe_in_minutes, df_in_minor_timeframe=df, minor_timeframe_in_minutes=minor_timeframe_in_minutes, zones=zones, levels=levels, title=market_name, ) ChartPlotter.plot(**plot_config) if save_chart: file_name = f"fig_{market_name}_{setup.replace(' ', '-')}_{get_now_timestamp_string()}.jpg" image_path = LOGS_DIR / file_name plt.savefig(fname=image_path, bbox_inches='tight') if show_chart: mpf.show() if save_chart: if cls.bot_send_image(image_path, message): logging.info(f'Bot sent image: `{image_path}` `{message}`') else: logging.error(f'Failed to send image via bot!') else: if cls.bot_send_message(message): logging.info(f'Bot sent message: `{message}`') else: logging.error(f'Failed to send message via bot!')
def plot(df: pd.DataFrame, title: Optional[str] = None, mav: Optional[Tuple[int]] = None, alines: Optional[dict] = None): color = mpf.make_marketcolors(up='red', down='cyan', inherit=True) style = mpf.make_mpf_style(marketcolors=color) # # 设置外观效果 # plt.rc('font', family='Microsoft YaHei') # 用中文字体,防止中文显示不出来 # plt.rc('figure', fc='k') # 绘图对象背景图 # plt.rc('text', c='#800000') # 文本颜色 # plt.rc('axes', axisbelow=True, xmargin=0, fc='k', ec='#800000', lw=1.5, labelcolor='#800000', # unicode_minus=False) # 坐标轴属性(置底,左边无空隙,背景色,边框色,线宽,文本颜色,中文负号修正) # plt.rc('xtick', c='#d43221') # x轴刻度文字颜色 # plt.rc('ytick', c='#d43221') # y轴刻度文字颜色 # plt.rc('grid', c='#800000', alpha=0.9, ls=':', lw=0.8) # 网格属性(颜色,透明值,线条样式,线宽) # plt.rc('lines', lw=0.8) # 全局线宽 # # # 创建绘图对象和4个坐标轴 # figure = plt.figure(figsize=(16, 8)) # left, width = 0.01, 0.98 # ax1 = figure.add_axes([left, 0.6, width, 0.35]) # left, bottom, width, height # ax2 = figure.add_axes([left, 0.45, width, 0.15], sharex=ax1) # 共享ax1轴 # ax3 = figure.add_axes([left, 0.25, width, 0.2], sharex=ax1) # 共享ax1轴 # ax4 = figure.add_axes([left, 0.05, width, 0.2], sharex=ax1) # 共享ax1轴 # plt.setp(ax1.get_xticklabels(), visible=False) # 使x轴刻度文本不可见,因为共享,不需要显示 # plt.setp(ax2.get_xticklabels(), visible=False) # 使x轴刻度文本不可见,因为共享,不需要显示 # plt.setp(ax3.get_xticklabels(), visible=False) # 使x轴刻度文本不可见,因为共享,不需要显示 # # # 绘制蜡烛图 # mpf.c(ax, data['open'], data['close'], data['high'], data['low'], # width=0.5, colorup='r', colordown='green', # alpha=0.6) kwargs: dict = { 'type': 'candle', 'style': style, 'volume': True, 'figratio': (3, 1), 'figscale': 20, 'savefig': dict(fname= f'D:\\Test_{datetime.now().strftime("%Y-%m-%d_%H-%M-%S")}.png', bbox_inches='tight') } if title: kwargs['title'] = title if mav: kwargs['mav'] = mav if alines: kwargs['alines'] = alines mpf.plot(df, **kwargs) mpf.show()
def candle_stick(ticker, start_date=(datetime.now() - timedelta(days=1)).strftime("%Y%m%d"), end_date=datetime.now().strftime("%Y%m%d")): start_date = datetime.strptime(str(start_date), '%Y%m%d').strftime('%Y-%m-%d') end_date = datetime.strptime(str(end_date), '%Y%m%d').strftime('%Y-%m-%d') tkr = yf.Ticker(ticker) stock = tkr.history(interval="1m", start=start_date, end=end_date) stock.drop(columns=['Dividends', 'Stock Splits'], inplace=True) print(f"plotting chart for {ticker} ...") # print(stock.head(5)) fig_d = mpf.figure(style="yahoo") ax1_d = fig_d.add_subplot(1, 1, 1) mpf.plot(stock, ax=ax1_d, type='candle') mpf.show() pass
def animate(ival): if ival+rn < calc_window: ival = calc_window - rn if (ival+rn) > len(rates): print('no more data to plot') ani.event_source.interval *= 3 if ani.event_source.interval > 12000: exit() return data = rates.iloc[ival:ival+rn] ax1.clear() ax2.clear() mpf.plot(data,ax=ax1,volume=ax2,type='candle') mpf.show()
def plotSpread(ticker1, ticker2, years): fig = mpf.figure(figsize=(15, 10)) axs = fig.add_subplot(1, 1, 1, style='yahoo') endDate = date.today() startDate = endDate - datetime.timedelta(days=years * 365) data1 = pdr.get_data_yahoo(ticker1, start=startDate, end=endDate) data2 = pdr.get_data_yahoo(ticker2, start=startDate, end=endDate) firstPrice = data1['Adj Close'] secondPrice = data2['Adj Close'] df1 = pd.DataFrame({'secondPrice': secondPrice, 'firstPrice': firstPrice}) df1.index = pd.to_datetime(df1.index) state_means = regression(firstPrice, secondPrice) df1['hr'] = -state_means[:, 0] df1['spread'] = df1.secondPrice + (df1.firstPrice * df1.hr) df2 = pd.DataFrame({ 'Open': df1['spread'].shift(periods=1), 'High': df1['spread'], 'Low': df1['spread'], 'Close': df1['spread'], 'Volume': df1['spread'] }) df2 = df2[1:] dt = 1 mu = 0 theta = 1 sigma = np.std(df1['spread']) ts = np.arange(0, len(df1['spread'].values), dt) var = np.array( [sigma**2 / (2 * theta) * (1 - np.exp(-2 * theta * t)) for t in ts]) std = 2 * np.sqrt(var) std = std[-1] upper = mu + std lower = mu - std mpf.plot(df2, type='candle', ax=axs, axtitle=f"Spread for {ticker2} / {ticker1}", hlines=dict(hlines=[mu, upper, lower], linestyle='-.', colors=['b', 'b', 'b']), xrotation=0) mpf.show()
def show_basic(self, ftitle="Stock"): """ 顯示基本K線圖,僅K線與成交量 使用mplfinance實現之 """ dest = Dpath + '\\' + ftitle + ".png" mc = mpf.make_marketcolors(up='r', down='g', inherit=True) ms = mpf.make_mpf_style(base_mpf_style = "yahoo", \ marketcolors = mc) # 不支援中文字型,圖表文字需為英文 mfargs = dict(type = "candle", volume = True, \ columns = ("O", "H", "L", "C", "V"), \ show_nontrading = False, returnfig = True, \ figsize = (self.fx, self.fy), \ title = ftitle, style = ms, ylabel = "Price", \ ylabel_lower = "Volume in shares") fig, axes = mpf.plot(self.df, **mfargs) mpf.show() fig.savefig(dest) return None
def show_graphic_from_finance(archivo, numero_velas, moneda): df = pd.read_csv(archivo, index_col='Datetime') df.index = pd.to_datetime(df.index, utc=True) fig = mpf.figure(style='charles', figsize=(7, 7)) ax1 = fig.add_subplot(2, 1, 1) ax2 = fig.add_subplot(3, 1, 3) def animate(ival): data = update_data_from_finance(archivo, moneda, "5m") print("UPDATED") print(data.index.max()) data_to_print = data.iloc[(len(data) - numero_velas):len(data)] ax1.clear() ax2.clear() mpf.plot(data_to_print, ax=ax1, volume=ax2, type='candle') ani = animation.FuncAnimation(fig, animate, interval=300000) mpf.show()
def show(df): buy, sell = label(df) df['buy'] = buy df['sell'] = sell print(df.head(3)) apd = [ mpf.make_addplot(df['buy'], type="scatter", scatter=True, markersize=20, marker='^'), mpf.make_addplot(df['sell'], type="scatter", scatter=True, markersize=20), ] mpf.plot(df, type="candle", volume=True, addplot=apd, style="sas") mpf.show()
def show_graphic_from_finance_and_predict(cuda): df = pd.read_csv("data/ETH-USD-5m.csv", index_col='Datetime') df.index = pd.to_datetime(df.index, utc=True) fig = mpf.figure(style='charles', figsize=(7, 7)) ax1 = fig.add_subplot(2, 1, 1) ax2 = fig.add_subplot(3, 1, 3) list_models_load = [] list_models = get_list_models() # Cargamos los modelos print('Cargando modelos...') for name, pretrained in list_models: model = AdaptativeNet(pretrained) model.load_state_dict(torch.load('trained_nets/' + name + '.pth')) list_models_load.append((name, model)) print('Modelos cargados') def animate(ival): data = update_data_from_finance("data/ETH-USD-5m.csv", "ETH-USD", "5m") print("UPDATED") print(data.index.max()) data_to_print = data.iloc[(len(data) - 150):len(data)] net_dataset = Net_dataset_show(data_to_print) loader = torch.utils.data.DataLoader(net_dataset, shuffle=True, num_workers=2) with torch.no_grad(): prediction = predict(list_models_load, loader, cuda) print('La prediccion de la proxima vela sera: ' + prediction) ax1.clear() ax2.clear() mpf.plot(data_to_print, ax=ax1, volume=ax2, type='candle') ani = animation.FuncAnimation(fig, animate, interval=300000) mpf.show()
def draw(self): intraday: pd.DataFrame intraday = self.candlestick.loc[:, ['open', 'high', 'low', 'close', 'volume']] intraday.index = pd.to_datetime(self.candlestick['datetime']) color = mpf.make_marketcolors(up='red', down='cyan', inherit=True) style = mpf.make_mpf_style(marketcolors=color) # # 设置外观效果 # plt.rc('font', family='Microsoft YaHei') # 用中文字体,防止中文显示不出来 # plt.rc('figure', fc='k') # 绘图对象背景图 # plt.rc('text', c='#800000') # 文本颜色 # plt.rc('axes', axisbelow=True, xmargin=0, fc='k', ec='#800000', lw=1.5, labelcolor='#800000', # unicode_minus=False) # 坐标轴属性(置底,左边无空隙,背景色,边框色,线宽,文本颜色,中文负号修正) # plt.rc('xtick', c='#d43221') # x轴刻度文字颜色 # plt.rc('ytick', c='#d43221') # y轴刻度文字颜色 # plt.rc('grid', c='#800000', alpha=0.9, ls=':', lw=0.8) # 网格属性(颜色,透明值,线条样式,线宽) # plt.rc('lines', lw=0.8) # 全局线宽 # # # 创建绘图对象和4个坐标轴 # figure = plt.figure(figsize=(16, 8)) # left, width = 0.01, 0.98 # ax1 = figure.add_axes([left, 0.6, width, 0.35]) # left, bottom, width, height # ax2 = figure.add_axes([left, 0.45, width, 0.15], sharex=ax1) # 共享ax1轴 # ax3 = figure.add_axes([left, 0.25, width, 0.2], sharex=ax1) # 共享ax1轴 # ax4 = figure.add_axes([left, 0.05, width, 0.2], sharex=ax1) # 共享ax1轴 # plt.setp(ax1.get_xticklabels(), visible=False) # 使x轴刻度文本不可见,因为共享,不需要显示 # plt.setp(ax2.get_xticklabels(), visible=False) # 使x轴刻度文本不可见,因为共享,不需要显示 # plt.setp(ax3.get_xticklabels(), visible=False) # 使x轴刻度文本不可见,因为共享,不需要显示 # # # 绘制蜡烛图 # mpf.c(ax, data['open'], data['close'], data['high'], data['low'], # width=0.5, colorup='r', colordown='green', # alpha=0.6) mpf.plot(intraday, type='candle', style=style, mav=(5, 10), volume=True) mpf.show()
def candle_stick_daily(ticker, start_date=(datetime.now() - timedelta(days=60)).strftime("%Y%m%d"), end_date=datetime.now().strftime("%Y%m%d")): start_date = datetime.strptime(str(start_date), '%Y%m%d').strftime('%Y-%m-%d') end_date = datetime.strptime(str(end_date), '%Y%m%d').strftime('%Y-%m-%d') tkr = yf.Ticker(ticker) stock = tkr.history(interval="1d", start=start_date, end=end_date) stock.drop(columns=['Dividends', 'Stock Splits'], inplace=True) """ Open High Low Close Volume Date 2021-01-20 858.739990 859.500000 837.280029 850.450012 25665900 2021-01-21 855.000000 855.719971 841.419983 844.989990 20521100 2021-01-22 834.309998 848.000000 828.619995 846.640015 20066500 2021-01-25 855.000000 900.400024 838.820007 880.799988 41173400 2021-01-26 891.380005 895.900024 871.599976 883.090027 23131600 """ print(f"plotting chart for {ticker} ...") # print(stock.head(5)) fig_d = mpf.figure(style="yahoo") ax1_d = fig_d.add_subplot(1,1,1) mpf.plot(stock, ax=ax1_d, type='candle') mpf.show() pass
class Monitor: BAR_NUMS_SLIDING_WINDOW = 50 # Determine and draw S/R by how many bars? @classmethod def bot_send_message(cls, message: str, disable_notification: bool = False) -> bool: SEND_MESSAGE_API_ENDPOINT = f'https://api.telegram.org/bot{os.getenv("TELEGRAM_BOT_TOKEN")}/sendMessage' RETRY_LIMIT = 3 data = { 'chat_id': os.getenv('TELEGRAM_BOT_SEND_MESSAGE_GROUP_ID'), 'text': message, 'disable_notification': disable_notification, } for _ in range(RETRY_LIMIT): response = requests.post(SEND_MESSAGE_API_ENDPOINT, data=data) if response.status_code == 200: return True time.sleep(3) logging.error(f'Failed to send bot message [{message}]!') return False @classmethod def bot_send_image(cls, image_path: str, caption: str = '', disable_notification: bool = False) -> bool: SEND_PHOTO_API_ENDPOINT = f'https://api.telegram.org/bot{os.getenv("TELEGRAM_BOT_TOKEN")}/sendPhoto' RETRY_LIMIT = 3 files = {'photo': open(image_path, 'rb')} data = { 'chat_id': os.getenv('TELEGRAM_BOT_SEND_MESSAGE_GROUP_ID'), 'caption': caption, 'disable_notification': disable_notification, } for _ in range(RETRY_LIMIT): response = requests.post(SEND_PHOTO_API_ENDPOINT, files=files, data=data) if response.status_code == 200: return True time.sleep(3) logging.error(f'Failed to send photo [{caption}]!') return False @classmethod def resample(cls, df: pd.DataFrame, major_timeframe_in_minutes: int = 60) -> pd.DataFrame: RESAMPLE_MAP = { 'Open': 'first', 'High': 'max', 'Low': 'min', 'Close': 'last', } return df.resample(f'{major_timeframe_in_minutes}T').agg( RESAMPLE_MAP).dropna() def check(cls, data_grabber: DataGrabber, major_timeframe_in_minutes: int = 60, minor_timeframe_in_minutes: int = 5, show_chart: bool = False, save_chart: bool = False) -> None: df = data_grabber.fetch() if df is None: return df_resampled_into_major_timeframe = cls.resample( df).iloc[-cls.BAR_NUMS_SLIDING_WINDOW:] df = df.iloc[-cls.BAR_NUMS_SLIDING_WINDOW:] zones, levels = ZoneFinder.find_key_zones_and_levels( df_resampled_into_major_timeframe, find_levels_threshold=1, merge_levels_threshold=0.0002, zone_weight_threshold=5) market_name = data_grabber.get_symbols() df_latest = df.tail(3) setup = SetupFinder.current_setup(zones, df_latest) if not setup: return message = f'[{get_now_timestamp_string()}] {market_name} setup: {setup}' image_path = None if show_chart or save_chart: plot_config = dict( df_in_major_timeframe=df_resampled_into_major_timeframe, major_timeframe_in_minutes=major_timeframe_in_minutes, df_in_minor_timeframe=df, minor_timeframe_in_minutes=minor_timeframe_in_minutes, zones=zones, levels=levels, title=market_name, ) ChartPlotter.plot(**plot_config) if save_chart: file_name = f"fig_{market_name}_{setup.replace(' ', '-')}_{get_now_timestamp_string()}.jpg" image_path = LOGS_DIR / file_name plt.savefig(fname=image_path, bbox_inches='tight') if show_chart: mpf.show() if save_chart: if cls.bot_send_image(image_path, message): logging.info(f'Bot sent image: `{image_path}` `{message}`') else: logging.error(f'Failed to send image via bot!') else: if cls.bot_send_message(message): logging.info(f'Bot sent message: `{message}`') else: logging.error(f'Failed to send message via bot!') @classmethod def run_simulation(cls, df_minor_timeframe_full: pd.DataFrame, start_from_frame_num: int = 0, major_timeframe_in_minutes: int = 60, minor_timeframe_in_minutes: int = 5) -> None: rtapi = RealTimeAPIMock(df_minor_timeframe_full, cls.BAR_NUMS_SLIDING_WINDOW) df = rtapi.initial_fetch() def step_forward_one_frame(): nxt = rtapi.fetch_next() if nxt is None: print('no more data to plot') anim.event_source.interval *= 3 if anim.event_source.interval > 12000: exit() return nonlocal df df = pd.concat([df, nxt]) for _ in range(start_from_frame_num): step_forward_one_frame() df_resampled_into_major_timeframe = cls.resample( df).iloc[-cls.BAR_NUMS_SLIDING_WINDOW:] plot_config = dict( df_in_major_timeframe=df_resampled_into_major_timeframe, major_timeframe_in_minutes=major_timeframe_in_minutes, df_in_minor_timeframe=df.iloc[-cls.BAR_NUMS_SLIDING_WINDOW:], minor_timeframe_in_minutes=minor_timeframe_in_minutes, title='EURUSD', ) fig, ax_major_timeframe, ax_minor_timeframe = ChartPlotter.plot( **plot_config) pause = False def on_click(event): nonlocal pause pause ^= True if pause: anim.event_source.stop() else: anim.event_source.start() fig.canvas.mpl_connect('button_press_event', on_click) def animate(frame_num): print('Frame:', start_from_frame_num + frame_num) ax_major_timeframe.clear() ax_minor_timeframe.clear() step_forward_one_frame() df_resampled_into_major_timeframe = cls.resample( df).iloc[-cls.BAR_NUMS_SLIDING_WINDOW:] zones, levels = ZoneFinder.find_key_zones_and_levels( df_resampled_into_major_timeframe, find_levels_threshold=1, merge_levels_threshold=0.0002, zone_weight_threshold=5) plot_config = dict( df_in_major_timeframe=df_resampled_into_major_timeframe, major_timeframe_in_minutes=major_timeframe_in_minutes, df_in_minor_timeframe=df.iloc[-cls.BAR_NUMS_SLIDING_WINDOW:], minor_timeframe_in_minutes=minor_timeframe_in_minutes, zones=zones, levels=levels, fig=fig, ax_major_timeframe=ax_major_timeframe, ax_minor_timeframe=ax_minor_timeframe, ) ChartPlotter.plot(**plot_config) # plt.pause(0.001) # reduce GUI freeze df_latest = df.tail(3) if setup := SetupFinder.current_setup(zones, df_latest): print(setup) on_click(None) anim = animation.FuncAnimation(fig, animate, interval=100) mpf.show()
def plot_ohlc_all(self, data, block=True, save=False): """ :param data: [{code:code0, df:dataframe0(ohlc)}, {code:code1, df:dataframe1(ohlc)}, ...] :param block: if block is False when plot shows, plot run backend :param save: if save is True, plot is saved, don't show """ if save: if os.path.exists(self._save_path): save_path_names = [] for i in range(len(data)): save_path_name = self._save_path + '\\chart' + f"_{i}" + self._suffix save_path_names.append(save_path_name) mpf.plot(data[i]['df'], style='yahoo', type='candle', title=data[i]['code'], savefig=save_path_name) return save_path_names else: raise Exception('Save path {} does not exist.'.format( self._save_path)) else: page, limit = 0, min(8, len(data)) # page starts 0 max_page = math.ceil(len(data) / limit) fig = mpf.figure(figsize=(12, 9), style='yahoo') fig.subplots_adjust(left=0.03, bottom=0.2, right=0.95, top=0.95, hspace=0.2) axes = [] for i in range(limit): ax = fig.add_subplot(2, 4, i + 1) axes.append(ax) mpf.plot(data[i]['df'], ax=ax, type='candle', axtitle=data[i]['code']) def button_prev(event): nonlocal page, limit, max_page nonlocal data nonlocal axes, axtext page = (page - 1) if page > 0 else max_page - 1 replot_ohlc(data, axes, page, limit, axtext) def button_next(event): nonlocal page, limit, max_page nonlocal data nonlocal axes, axtext page = (page + 1) % max_page replot_ohlc(data, axes, page, limit, axtext) def replot_ohlc(data, axes, page, limit, axtext): axtext.clear() axtext.text(0.4, 0.2, '{:2d} / {:2d}'.format(page + 1, max_page)) for ax in axes: ax.clear() for i, ax in enumerate(axes): idx = i + (page * limit) if idx >= len(data): break mpf.plot(data[idx]['df'], ax=ax, type='candle', axtitle=data[idx]['code']) # make prev or next button axprev = fig.add_axes([0.7, 0.05, 0.1, 0.075]) axnext = fig.add_axes([0.81, 0.05, 0.1, 0.075]) bprev = Button(axprev, '◀') bnext = Button(axnext, '▶') bnext.on_clicked(button_next) bprev.on_clicked(button_prev) # make current page representation axtext = fig.add_axes([0.5, 0.05, 0.1, 0.075]) axtext.text(0.4, 0.2, '{:2d} / {:2d}'.format(page + 1, max_page)) mpf.show(block=block)
def Grafico(indicadorTec, numSubplots1, numSubplots2, vr=None, pi=None, pf=None): """ Permite hacer la gráfica del activo en un periodo de tiempo """ fig = mpf.figure(figsize=(12, 9)) s = mpf.make_mpf_style(base_mpf_style='yahoo', y_on_right=False) if numSubplots1 == 1 and numSubplots2 == 0: ax1 = fig.add_subplot(2, 2, 2, style=s) ax11 = ax1.twinx() ap = mpf.make_addplot(indicadorTec.DataStock['RSI'], ax=ax11, ylabel='RSI') vol = fig.add_subplot(2, 2, 4, sharex=ax1, style=s) mpf.plot(indicadorTec.DataStock, volume=vol, ax=ax1, addplot=ap, xrotation=10, ylabel='Precio', type='candle', axtitle='Gráfica de valor con indicador RSI') elif numSubplots1 == 0 and numSubplots2 == 1: ax2 = fig.add_subplot(2, 2, 2, style=s) ax22 = ax2.twinx() ap = mpf.make_addplot(indicadorTec.DataStock['SMA'], ax=ax22, ylabel='SMA') vol = fig.add_subplot(2, 2, 4, sharex=ax2, style=s) mpf.plot(indicadorTec.DataStock, volume=vol, ax=ax2, addplot=ap, xrotation=10, ylabel='Precio', type='candle', axtitle='Gráfica de valor con indicador SMA') elif numSubplots1 == 1 and numSubplots2 == 1: ax1 = fig.add_subplot(2, 2, 2, style=s) ax11 = ax1.twinx() ap = mpf.make_addplot(indicadorTec.DataStock['RSI'], ax=ax11, ylabel='RSI') mpf.plot(indicadorTec.DataStock, ax=ax1, addplot=ap, xrotation=10, ylabel='Precio', type='candle', axtitle='Gráfica de valor con indicador RSI') ax2 = fig.add_subplot(2, 2, 4, style=s) ax22 = ax2.twinx() ap = mpf.make_addplot(indicadorTec.DataStock['SMA'], ax=ax22, ylabel='SMA') mpf.plot(indicadorTec.DataStock, ax=ax2, addplot=ap, xrotation=10, ylabel='Precio', type='candle', axtitle='Gráfica de valor con indicador SMA') if pi == None and pf == None: axp = fig.add_subplot(2, 2, 1, style=s) volp = fig.add_subplot(2, 2, 3, sharex=axp, style=s) mpf.plot(indicadorTec.DataStock, ax=axp, volume=volp, xrotation=10, ylabel='Precio', type='candle', axtitle='Gráfica del valor (últimos 30 días) ') mpf.show() else: axp = fig.add_subplot(2, 2, 1, style=s) volp = fig.add_subplot(2, 2, 3, sharex=axp, style=s) mpf.plot(indicadorTec.DataStock, ax=axp, volume=volp, xrotation=10, ylabel='Precio', type='candle', axtitle=f'Gráfica del valor (De {pi} a {pf}) ') mpf.show()
def main(): """ Despliega un menú de opciones en la consola del terminal """ ot1 = 0 ValorGrafico = Valor() while ot1 == 0: # Primer while principal para la identificación del código y el país del valor global num_exis num_exis = 0 a = -1 while a != 1 and a != 2 and a != 3: # Bucle que repite la opción de la elección de lista print( "\n\nEste programa realiza recomendaciones de compra o venta de un valor según un análisis técnico con los datos obtenidos de Investing.com\n" ) print("(1) Ver lista de países ") print("(2) Ver lista de valores de todos los países ") print("(3) Ver lista de valores según el país ") a = int(input("\n¿Qué desea hacer?\n")) if a == 1: # Se imprimen todos los países que están registrados en el mercado de valores for i in investpy.get_stock_countries(): print("País {}: {}".format( investpy.get_stock_countries().index(i) + 1, i)) elif a == 2: # Se imprime un panda.DataFrame de todos los valores sin importar el país print(investpy.get_stocks(country=None)) elif a == 3: # Se imprime un panda.DataFrame de todos los valores según el país indicado otra = 1 while otra != 0: try: b = input("Escribe el país de donde quieres buscar:\n") print(investpy.get_stocks(country=b)) otra = 0 except ValueError: # Evita que se ejecute el error ValueError cuando la palabra insertada no se encuentra entre los países de la lista print("Escribe un pais existente\n") ott = 1 while ott != 0: # Permite la opción de salida del primer bucle while principal ot = str(input("¿Desea ver otra lista? Sí(S) o No (N):\n")) if ot == 'S' or ot == 's': ot1 = 0 ott = 0 elif ot == 'N' or ot == 'n': ot1 = 1 ott = 0 else: ott = 1 ot2 = 0 while ot2 == 0: # Segundo while principal para ingresar el país y el valor, o salir del programa a1 = -1 while a1 != 1 and a1 != 2: # Bucle que repite la opción de la elección de continuar con el análisis o salir del programa print( "\nElija si desea realizar un análisis técnico de un valor en el mercado de valores\n" ) print("(1) Analizar un valor ") print("(2) Salir ") a1 = int(input("\n¿Qué desea hacer?\n")) if a1 == 1: # Se ingresa el país y el valor para su análisis técnico otr = 1 while otr != 0: try: print("¿Qué valor deseas ver?\n") pais = input( "Ingresa el país (Segunda columna en la lista de valores)\n" ) stock_valor = input( "Ingresa el código del valor (Séptima columna en la lista de valores)\n" ).upper() p = 0 while p == 0: # Permite la opción de especificar un rango de tiempo p1 = str( input( "¿Desea establecer un rango de tiempo? Sí(S) o No (N):\n" )) if p1 == 'S' or p1 == 's': print( "Escriba el rango de tiempo con el formato (dd/mm/aaaa)" ) pi = str(input("Escriba el día de inicio : ")) pf = str(input("Escriba el día de término: ")) df = extraer(1, stock_valor, pais, pi, pf) print(df) mpf.plot( df, axtitle=f'Gráfica del valor (De {pi} a {pf})', style='yahoo', xrotation=15, type='candle') mpf.show() p = 1 elif p1 == 'N' or p1 == 'n': df = extraer(2, stock_valor, pais) print(df) mpf.plot( df, axtitle='Gráfica del valor (últimos 30 días)', style='yahoo', xrotation=15, type='candle') mpf.show() p = 1 else: p = 0 otr = 0 except ValueError: print("Escribe un país existente\n") elif a1 == 2: # Sale del programa break otq = 0 while otq == 0: z = -1 while z != 1 and z != 2 and z != 3: # Bucle que repite la opción de la elección de indicador print("\n¿Cuál indicador deseas ver?\n") print( "(1) RSI (Relative Strength Index) " ) print( "(2) SMA (Simple Moving Average) " ) print( "(3) Ambos " ) z = int(input("\n¿Qué desea hacer?\n")) indic1 = Indicador_tecnico(df) if z == 1: indic1.RSI() t = "RSI" elif z == 2: indic1.SMA() t = "SMA" elif z == 3: indic1.All() Grafico(indic1, indic1._RSI, indic1._SMA) señ1 = señal(z, stock_valor, pais) if z != 3: print( f"\n\nEl indicador {t} en el valor búrsatil '{señ1[0]}' es de {señ1[1]}, e indica que se recomienda {señ1[2]}.\n\n" ) else: print( f"\n\nCon el valor búrsatil '{señ1[0]}', con el indicador RSI, el cual es de {señ1[1]}, recomienda {señ1[2]}; mientras que el indicador SMA, el cual es de {señ1[3]}, recomienda {señ1[4]}.\n\n" ) ott2 = 1 while ott2 != 0: # Permite la opción de salida del bucle while otp = str(input( "¿Desea ver otro indicador? Sí(S) o No (N):\n")).upper() if otp == 'S': otq = 0 ott2 = 0 elif otp == 'N': otq = 1 ott2 = 0 else: ott2 = 1 ValorGrafico.agregar_valor(stock_valor, indic1) otw = 0 while otw == 0: ddd = 1 while ddd != 0: # Permite la opción de salida del bucle while otp5 = str( input( "¿Desea ver algún valor registrado? Sí(S) o No (N):\n") ).upper() if otp5 == 'S': otw = 0 ddd = 0 elif otp5 == 'N': otw = 1 ddd = 0 break else: ddd = 1 if otp5 == 'S': valReg = str( input( "Escriba el símbolo del valor registrado que quiere buscar: " )).upper() VR = ValorGrafico.mostrar_valor(valReg) elif otp5 == 'N': break Grafico(VR[0], VR[1], VR[2]) if VR[1] == 1 and VR[2] == 0: t1 = "RSI" z1 = 1 elif VR[1] == 0 and VR[2] == 1: t1 = "SMA" z1 = 2 elif VR[1] == 1 and VR[2] == 1: z1 = 3 señ2 = señal(z1, valReg, pais) if z1 != 3: print( f"\n\nEl indicador {t1} en el valor búrsatil '{señ2[0]}' es de {señ2[1]}, e indica que se recomienda {señ2[2]}.\n\n" ) else: print( f"\n\nCon el valor búrsatil '{señ2[0]}', con el indicador RSI, el cual es de {señ2[1]}, recomienda {señ2[2]}; mientras que el indicador SMA, el cual es de {señ2[3]}, recomienda {señ2[4]}.\n\n" ) ott2 = 1 while ott2 != 0: # Permite la opción de salida del bucle while otp7 = str( input( "¿Desea ver otro valor registrado? Sí(S) o No (N):\n")) if otp7 == 'S' or otp7 == 's': otw = 0 ott2 = 0 elif otp7 == 'N' or otp7 == 'n': otw = 1 ott2 = 0 break else: ott2 = 1 valReg = str( input( "Escriba el símbolo del valor registrado que quiere buscar: " )).upper() ValorGrafico.mostrar_valor(valReg) VR1 = ValorGrafico.mostrar_valor(valReg) Grafico(VR1[0], VR1[1], VR1[2]) if VR1[1] == 1 and VR1[2] == 0: t2 = "RSI" z2 = 1 elif VR1[1] == 0 and VR1[2] == 1: t2 = "SMA" z2 = 2 elif VR1[1] == 1 and VR1[2] == 1: z2 = 3 señ3 = señal(z2, valReg, pais) if z2 != 3: print( f"\n\nEl indicador {t2} en el valor búrsatil '{señ3[0]}' es de {señ3[1]}, e indica que se recomienda {señ3[2]}.\n\n" ) else: print( f"\n\nCon el valor búrsatil '{señ3[0]}', con el indicador RSI, el cual es de {señ3[1]}, recomienda {señ3[2]}; mientras que el indicador SMA, el cual es de {señ3[3]}, recomienda {señ3[4]}.\n\n" ) ott3 = 1 while ott3 != 0: # Permite la opción de salida del segundo bucle while principal otp3 = str(input("¿Desea ver otro valor? Sí(S) o No (N):\n")) if otp3 == 'S' or otp3 == 's': ot2 = 0 ott3 = 0 elif otp3 == 'N' or otp3 == 'n': ot2 = 1 ott3 = 0 else: ott3 = 1
def showStockData(stockData, stockName): #marketcolor mc = mpf.make_marketcolors(up="red", down="green", edge="i", wick="i", volume="in", inherit=True) #style #mpf.available_styles() #['binance', # 'blueskies', # 'brasil', # 'charles', # 'checkers', # 'classic', # 'default', # 'mike', # 'nightclouds', # 'sas', # 'starsandstripes', # 'yahoo'] s = mpf.make_mpf_style(gridaxis='both', base_mpf_style='blueskies', gridstyle='-.', y_on_right=False, marketcolors=mc) # 设置基本参数 # type:绘制图形的类型,有candle, renko, ohlc, line等 # 此处选择candle,即K线图 # mav(moving average):均线类型,此处设置7,30,60日线 # volume:布尔类型,设置是否显示成交量,默认False # title:设置标题 # y_label_lower:设置成交量图一栏的标题 # figratio:设置图形纵横比 # figscale:设置图形尺寸(数值越大图像质量越高) symbol = stockName.replace(".csv", "") kwargs = dict(type='candle', mav=(5), volume=True, title='\nStock %s ' % (symbol), ylabel='OHLC Candles', ylabel_lower='Trade volume', figscale=1.25, figratio=(16, 5)) #figratio=(10, 6), #figscale=4) #calculate above and below percentB #low_signal = percentB_below(stockData) #high_signal = percentB_above(stockData) #Days = int(Days) Days = 60 apds = [ mpf.make_addplot(stockData['Lower'][-Days:], color='b', width=0.75, ylabel='Lower'), mpf.make_addplot(stockData['Upper'][-Days:], color='b', width=0.75), mpf.make_addplot(stockData['MA_20'][-Days:], color='b', width=0.75), #mpf.make_addplot( low_signal[-Days:],color='g',markersize=200,marker='^',type='scatter' ), #mpf.make_addplot( high_signal[-Days:],color='g',markersize=200,marker='x',type='scatter' ), mpf.make_addplot(stockData['Bbandwidth'][-Days:], color='r', panel=3, width=0.75, ylabel="BD"), mpf.make_addplot(stockData['percentB'][-Days:], color='r', panel=2, width=0.75, ylabel="%B"), #mpf.make_addplot(stockData['RSI'][-Days:], color='g', panel=4, ylabel="RSI") ] #add legend which doesn't available in current mplfinance library fig, axes = mpf.plot(stockData[-Days:], **kwargs, style=s, show_nontrading=False, addplot=apds, returnfig=True, update_width_config=dict(candle_linewidth=2)) #fig, axes = mpf.plot(stockData[-Days:], **kwargs,style=s,show_nontrading= False,addplot=apds,returnfig=True) #configure chart legend and title #axes[0].legend(['MA_5'],['MA_20'],['Upper'],['Lower']) #_, axs = plt.subplots(nrows=2,ncols=2,figsize=(7,5)) #todo_list: #回測系統 #加入其他技術分析 #考慮網頁化? #2020-10-25 #優化視窗 鼠標可顯示該位置的價格 數值等等... mpf.show()
histogram = macd - signal apds = [ mpf.make_addplot(exp12, color='lime'), mpf.make_addplot(exp26, color='c'), mpf.make_addplot(histogram, type='bar', width=0.7, panel=1, color='dimgray', alpha=1, secondary_y=False), mpf.make_addplot(macd, panel=1, color='fuchsia', secondary_y=True), mpf.make_addplot(signal, panel=1, color='b', secondary_y=True), ] fig, axlist = mpf.plot(df, type='candle', addplot=apds, figscale=1.1, figratio=(8, 5), title='\nMACD', style='blueskies', volume=True, volume_panel=2, panel_ratios=(6, 3, 2), returnfig=True) multi = MultiCursor(fig.canvas, axlist, color='r', lw=1.2) mpf.show()
def draw_k(code, date, a, title='', h=False): if len(a) == 0: return d = stock.data.loc[code] ds = stock.data.loc[2330].loc[name.DATE].tolist() ds.index(date) d = d.iloc[:, ds.index(date):90 + ds.index(date)].dropna(axis=1) ds = d.loc[name.DATE].tolist() if a[-1][0] > d.columns[-1]: return n = np.full(d.shape[1], np.nan) dsd = d.loc[name.DATE].tolist() for v in a: n[dsd.index(v[1])] = d.loc[name.CLOSE][v[0]] * 0.99 apd = mpf.make_addplot(n[::-1], type='scatter', markersize=100, marker='^') dd = pd.DataFrame({ name.DATE: pd.to_datetime(d.loc[name.DATE].iloc[::-1]).tolist(), name.OPEN: d.loc[name.OPEN].iloc[::-1].tolist(), name.CLOSE: d.loc[name.CLOSE].iloc[::-1].tolist(), name.HIGH: d.loc[name.HIGH].iloc[::-1].tolist(), name.LOW: d.loc[name.LOW].iloc[::-1].tolist(), name.VOLUME: d.loc[name.VOLUME].iloc[::-1].tolist(), }) fig, axlist = mpf.plot(dd.set_index(name.DATE), type='candle', addplot=apd, ylabel=f"{code} {date} {title}", returnfig=True) if h: ds = d.loc[name.DATE].tolist() y = d.iloc[:, ds.index(a[0][1]):ds.index(a[1][1]) + 1] c = y.loc[name.CLOSE] o = y.loc[name.OPEN] if c.max() > o.max(): axlist[0].axhline(y=c.max()) else: axlist[0].axhline(y=o.max()) if c.min() > o.min(): axlist[0].axhline(y=c.min()) else: axlist[0].axhline(y=o.min()) fig.set_tight_layout(False) for ax in axlist: ax.yaxis.set_major_locator( k.PriceLocator(dd[name.HIGH].max(), dd[name.LOW].min())) ax.yaxis.set_major_formatter(k.PriceFormatter()) ax.xaxis.set_major_locator(k.DateLocator(ds)) ax.xaxis.set_major_formatter(k.DateFormatter()) mpf.show()
def run(pickle_file=PICKLE_FILE): ani = animation.FuncAnimation(fig, analysis, fargs=[pickle_file]) mpf.show()
def plot_data(self): #generated_data = [] #for i in range(int(self.n_windows / self.batch_size)): Z_ = next(self.random_series) d = self.synthetic_data(Z_) R_ = next(self.real_series_iter) print('Este es el real') print(R_) real_data = np.array(R_) print(real_data.shape) generated_data = np.array(d) print(generated_data.shape) print(len(generated_data)) generated_data = (self.scaler.inverse_transform( generated_data.reshape(-1, self.n_seq)).reshape( -1, self.seq_len, self.n_seq)) real_data = (self.scaler.inverse_transform( real_data.reshape(-1, self.n_seq)).reshape(-1, self.seq_len, self.n_seq)) for i in range(3): # print(' sequence:{}'.format(i)) generated = generated_data[i, :, :] real = real_data[i, :, :] # print(generated) # numpy_data = np.array([[1, 2], [3, 4]]) base = datetime.datetime(2020, 11, 20) arr = np.array( [base + datetime.timedelta(minutes=j) for j in range(20)]) didx = pd.DatetimeIndex(data=arr, tz='America/New_York') gen_df = pd.DataFrame( data=generated, index=didx, columns=["Open", "High", "Low", "Close", "Volume"]) print(gen_df) real_df = pd.DataFrame( data=real, index=didx, columns=["Open", "High", "Low", "Close", "Volume"]) # mpf.plot(real_dat, type='candle',mav=(3,6,9),volume=True) fig = mpf.figure(style='yahoo', figsize=(14, 16)) ax1 = fig.add_subplot(2, 2, 1) ax2 = fig.add_subplot(2, 2, 2) av1 = fig.add_subplot(3, 2, 5, sharex=ax1) av2 = fig.add_subplot(3, 2, 6, sharex=ax2) mpf.plot(gen_df, type='candle', ax=ax1, volume=av1, mav=(10, 20), axtitle='generated data') mpf.plot(real_df, type='candle', ax=ax2, volume=av2, mav=(10, 20), axtitle='real data') mpf.show()