def display_chart(self): if not len(self.chart): return self.ax.clear() # Axis ticker formatting if len(self.chart) // 30 > len(self.chart_locator) - 1: for index in range( len(self.chart_locator) * 30, len(self.chart), 30): time_format = self.chart.index[index].strftime('%H:%M') self.chart_locator.append(index) self.chart_formatter.append(time_format) self.ax.xaxis.set_major_locator(ticker.FixedLocator( self.chart_locator)) self.ax.xaxis.set_major_formatter( ticker.FixedFormatter(self.chart_formatter)) # Axis yticks & lines max_price = self.chart.High.max() min_price = self.chart.Low.min() if max_price > self.top_price or min_price < self.bottom_price: self.top_price = math.ceil( max_price / self.interval) * self.interval self.bottom_price = math.floor( min_price / self.interval) * self.interval self.interval_prices = np.arange(self.bottom_price, self.top_price + self.interval, self.interval) self.loss_cut_prices = np.arange( self.bottom_price + self.interval - self.loss_cut, self.top_price, self.interval) self.ax.grid(axis='x', alpha=0.5) self.ax.set_yticks(self.interval_prices) for price in self.interval_prices: self.ax.axhline(price, alpha=0.5, linewidth=0.2) for price in self.loss_cut_prices: self.ax.axhline(price, alpha=0.4, linewidth=0.2, color='Gray') # Current Price Annotation current_time = len(self.chart) current_price = self.chart.Close.iloc[-1] if self.chart_item_code[:3] == FUTURES_CODE: formatted_current_price = format(current_price, ',.2f') else: formatted_current_price = format(current_price, ',') # self.ax.text(current_time + 2, current_price, format(current_price, ',')) self.ax.text(current_time + 2, current_price, formatted_current_price) # Draw Chart candlestick2_ohlc(self.ax, self.chart.Open, self.chart.High, self.chart.Low, self.chart.Close, width=0.4, colorup='red', colordown='blue') self.fig.tight_layout() self.canvas.draw()
def k_line(symble, title, last=-30, adjust="qfq", dprint=False): ''' 过去n天个股历史行情均线数据(k线) param: symble: str,股票编号"sh601727" title: str,作图标题 last: int,过去多少天的数据,默认过去30天,例"-30" adjust: str,默认"qfq"前复权,返回复权后数据 dprint: bool,默认false,是否打印原始数据 startday: int,行情查询起始日期(懒得转化,没写功能) endday: int,行情查询起始日期(懒得转化,没写功能) ''' pingan = ak.stock_zh_a_daily(symble, adjust) df3 = pingan.reset_index().iloc[last:, :6] #取过去30天数据 df3 = df3.dropna(how='any').reset_index(drop=True) #去除空值且从零开始编号索引 df3 = df3.sort_values(by='date', ascending=True) print(df3.info()) # 均线数据 df3['5'] = df3.close.rolling(5).mean() df3['10'] = df3.close.rolling(10).mean() df3.tail() #画图 fig, ax = plt.subplots(1, 1, figsize=(8, 3), dpi=200) candlestick2_ohlc(ax, opens=df3['open'].values, highs=df3['high'].values, lows=df3['low'].values, closes=df3['close'].values, width=0.5, colorup="r", colordown="g") # 显示最高点和最低点 ax.text(df3.high.idxmax(), df3.high.max(), s=df3.high.max(), fontsize=8) ax.text(df3.high.idxmin(), df3.high.min() - 2, s=df3.high.min(), fontsize=8) ax.set_facecolor("white") ax.set_title(title) # 画均线 plt.plot(df3['5'].values, alpha=0.5, label='MA5') plt.plot(df3['10'].values, alpha=0.5, label='MA10') ax.legend(facecolor='white', edgecolor='white', fontsize=6) # 修改x轴坐标 plt.xticks(ticks=np.arange(0, len(df3)), labels=df3.date.dt.strftime('%Y-%m-%d').to_numpy()) plt.xticks(rotation=90, size=4) # 修改y轴坐标 ax.yaxis.set_major_formatter(FormatStrFormatter('%.2f')) plt.show()
def draw_candles(self, target_candles): ''' 取得済みチャートを描画 ''' mpf.candlestick2_ohlc(self.__axes[0], opens=target_candles.open.values, highs=target_candles.high.values, lows=target_candles.low.values, closes=target_candles.close.values, width=0.6, colorup='#77d879', colordown='#db3f3f') return {'success': 'チャートを描画', 'time': target_candles.time}
def generate_candlestick(the_opens, the_closes, the_highs, the_lows): fig, ax = plt.subplots() candlestick2_ohlc(ax, the_opens, the_closes, the_highs, the_lows, width=0.6, colorup='g', colordown='r', alpha=0.75) plt.xlabel(f'Days from {amount_data} day mark') plt.ylabel('Candle for each day') plt.title(f'Candlestick chart of {the_stock.upper()}') plt.show()
def days_graph(update, context): global days days = int(update.message.text) ticker = "{}-{}".format(cryptocurrency, forex) currpair = yf.Ticker(ticker) start_date = (dt.datetime.now() - dt.timedelta(days=days - 2)).date() df = currpair.history(period="1d", start=start_date, end=(dt.datetime.now() + dt.timedelta(days=1)).date()) df.reset_index(inplace=True) #change the percentages %m %d %y for the date format. df["Date"] = df["Date"].dt.strftime("%m/%d/%y") #Candlestick fg, ax1 = plt.subplots() candlestick2_ohlc(ax=ax1, opens=df['Open'], highs=df['High'], lows=df['Low'], closes=df['Close'], width=0.4, colorup='#77d879', colordown='#db3f3f') ax1.set_xticks(np.arange(len(df))) ax1.set_xticklabels( df['Date'], fontsize=7, rotation=-45, color='black' ) #the fontsize important if data too big, mag overlap yung date. ax1.tick_params(axis='y', colors='black') plt.title("{} Trend in the Past {} Days".format(cryptocurrency, days)) plt.ylabel("Price in {}".format(forex)) ax1.grid(True) ax1.set_axisbelow(True) #save, send, and delete plt.savefig("candlestick.png") context.bot.send_photo(chat_id=update.effective_chat.id, photo=open("candlestick.png", "rb")) os.remove("candlestick.png") return ConversationHandler.END
def drawChartMarketInfo(self, wgtParent, index, dic): fig = plt.figure(figsize=(20, 10)) ax = fig.add_subplot(111) end = datetime.datetime.now() start = end + datetime.timedelta(days=-90) if index == 'KOSPI': target = '^KS11' value = dic["kospi_value"] elif index == 'KOSDAQ': target = '^KQ11' value = dic["kosdaq_value"] kospi_df = web.DataReader(target, "yahoo", start, end) day_list = [] name_list = [] # 'Date' 인덱스를 컬럼으로 변환 kospi_df.reset_index(inplace=True) for i, day in enumerate(kospi_df.Date): if day.dayofweek == datetime.datetime.today().weekday(): day_list.append(i) name_list.append(day.strftime('%m-%d')) # X축 날짜 표시 ax.xaxis.set_major_locator(ticker.FixedLocator(day_list)) ax.xaxis.set_major_formatter(ticker.FixedFormatter(name_list)) # 그래프 title과 축 이름 지정 ax.set_title(index + ' INDEX : ' + value, fontsize=22) ax.set_xlabel('Date') # 캔들차트 그리기 candlestick2_ohlc(ax, kospi_df['Open'], kospi_df['High'], kospi_df['Low'], kospi_df['Close'], width=0.5, colorup='r', colordown='b') ax.legend() ax.grid(True, axis='y', linestyle='--') canvas = FigureCanvas(fig) vbxIndexes = QVBoxLayout(wgtParent) vbxIndexes.addWidget(canvas) canvas.draw()
def drawChart(self): df = self.dataset #이동 평균선을 그리기 위해 n일간의 값의 산술평균 df['MA5'] = df['Close'].rolling(5).mean() df['MA10'] = df['Close'].rolling(10).mean() df['MA20'] = df['Close'].rolling(20).mean() df = df[-30:] #인덱스 설정 dateindex = df.Date.astype('str') df = df[[ 'Open', 'High', 'Low', 'Close', 'Volume', 'MA5', 'MA10', 'MA20' ]] fig = plt.figure(figsize=(20, 10)) ax = fig.add_subplot(111) ax.plot(dateindex, df['MA5'], label='MA5', linewidth=0.7) ax.plot(dateindex, df['MA10'], label='MA10', linewidth=0.7) ax.plot(dateindex, df['MA20'], label='MA20', linewidth=0.7) # x축을 60도로 회전 plt.xticks(rotation=60) # X축 티커 숫자 30개로 제한 ax.xaxis.set_major_locator(ticker.MultipleLocator(1)) ax.set_title(self.stockCode, fontsize=22) ax.set_ylabel("Price") # ax.set_xlabel('Date') # 차트 저장 candlestick2_ohlc(ax, df['Open'], df['High'], df['Low'], df['Close'], width=0.5, colorup='r', colordown='b') fig1 = plt.gcf() ax.legend() plt.grid() plt.savefig("./static/img/" + self.stockCode + '.png', dpi=300)
def k_plot(self): ''' 画K线图 5、10、20日均线 布林带 ''' df3 = self.MA() name = self.name style.use('ggplot') fig, ax = plt.subplots(1, 1, figsize=(8, 3), dpi=200) candlestick2_ohlc(ax, opens=df3['open'].values, highs=df3['high'].values, lows=df3['low'].values, closes=df3['close'].values, width=0.5, colorup="r", colordown="g") ax.text(df3.high.idxmax() - 20, df3.high.max(), s=df3.high.max(), fontsize=8) ax.text(df3.high.idxmin() - 20, df3.high.min(), s=df3.high.min(), fontsize=8) ax.set_facecolor("white") ax.set_title('%s(%s)' % (name, code_to_name(name))) plt.plot(df3['5'].values, alpha=0.5, label='MA5') plt.plot(df3['10'].values, alpha=0.5, label='MA10') plt.plot(df3['20'].values, alpha=0.5, label='MID(MA20)', color='gray') plt.plot(df3['upper_band'].values, alpha=0.5, label='UPR', color='yellow') plt.plot(df3['lower_band'].values, alpha=0.5, label='DN', color='blue') ax.legend(facecolor='white', edgecolor='white', fontsize=6) plt.xticks(ticks=np.arange(0, len(df3)), labels=df3.date.dt.strftime('%Y-%m-%d').to_numpy()) plt.xticks(rotation=90, size=8) ax.yaxis.set_major_formatter(FormatStrFormatter('%.2f')) plt.show()
def plot_lines(data, plot_time, window1, window2): data_plot = data.iloc[-plot_time:] fig = plt.figure(facecolor='#07000d', figsize=(15, 10)) # 画布 ax = plt.subplot2grid((10, 4), (2, 0), rowspan=4, colspan=4, facecolor='#07000d') ax.grid(True, color='w', axis='y') # 网格 ax.grid(True, axis='x', alpha=0.3) ax.yaxis.label.set_color('w') # 轴 plt.ylabel('Stock Price and Volume', color='w') plt.xticks(ticks=np.arange(0, len(data_plot)), labels=data_plot.date.dt.strftime('%Y-%m-%d').to_numpy(), rotation=80, size=8) ax.yaxis.set_major_formatter(FormatStrFormatter('%.2f')) ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d')) # 横轴-时间 w_spin(ax) w_tick(ax) #kline================================= candlestick2_ohlc(ax, opens=data_plot['open'].values, highs=data_plot['high'].values, lows=data_plot['low'].values, closes=data_plot['close'].values, width=0.5, colorup='red', colordown='lime') #5日10日均线===================================== plot_mat = pd.DataFrame() plot_mat['close'] = data['close'] mov_avg_1 = plot_mat['close'].rolling(window=window1).mean() # x日均线 mov_avg_2 = plot_mat['close'].rolling(window=window2).mean() ax.plot(range(plot_time), mov_avg_1.iloc[-plot_time:], 'lightyellow', label='short_time', linewidth=1.5) ax.plot(range(plot_time), mov_avg_2.iloc[-plot_time:], 'cyan', label='long_time', linewidth=1.5) #成交量图==================================== Volume = data_plot[['date', 'volume']].groupby(by='date').sum().reset_index() ax_1 = ax.twinx() # 共享绘图区域 ax_1.fill_between(range(plot_time), 0, Volume.volume.values, facecolor='#00ffe8', alpha=0.4) ax_1.grid(False) ax_1.set_ylim(0, 4 * Volume.volume.values.max()) w_spin(ax_1) w_tick(ax_1) #涨跌幅图===================================== ax_2 = plt.subplot2grid((10, 4), (0, 0), sharex=ax, rowspan=2, colspan=4, facecolor='#07000d') data_plot2 = data.iloc[-plot_time - 1:] raw_time = datef_p_strf(data_plot, '%Y-%m-%d') daily_return = data_plot2['close'].pct_change().dropna() ax_2.plot(raw_time, daily_return, 'cyan', linewidth=2) plt.ylabel('Rise and Fall', color='w') ax_2.axhline(0.03, color='lightcoral') ax_2.axhline(0, color='lightgreen') ax_2.set_yticks([0, 0.03]) ax_2.fill_between(raw_time, daily_return, 0.03, where=(daily_return >= 0.03),\ facecolors='lightcoral') ax_2.fill_between(raw_time, daily_return, 0, where=(daily_return <= 0),\ facecolors='lightgreen') w_spin(ax_2) ax.tick_params(axis='y', colors='w') #唐奇安通道========================================= ax_3 = plt.subplot2grid((10, 4), (7, 0), sharex=ax, rowspan=4, colspan=4, facecolor='#07000d') data_close = data_plot['close'] data_high = data['high'] data_low = data['low'] upbound = [] downbound = [] for i in range(plot_time): upbound.append(max(data_high.iloc[-plot_time + i - 20:-plot_time + i])) downbound.append(min(data_low.iloc[-plot_time + i - 20:-plot_time + i])) ax_3.plot(raw_time, upbound, 'cyan', linewidth=1) ax_3.plot(raw_time, downbound, 'cyan', linewidth=1) ax_3.plot(raw_time, data_close, 'orange', linewidth=2) w_spin(ax_3) w_tick(ax_3) ax_3.grid(True, color='w', axis='y') # 网格 ax_3.grid(True, axis='x', alpha=0.3) ax_3.tick_params(axis='x', colors='#07000d') plt.ylabel('Dochian Channel', color='w') #======================================== # plt.savefig('dsw_test.jpg') plt.show()
def display_chart(self): chart = self.futures.chart if not len(chart): return self.trader.ax.clear() # Axis ticker formatting if len(chart) // 30 > len(self.chart_locator) - 1: for index in range(len(self.chart_locator) * 30, len(chart), 30): time_format = chart.index[index].strftime('%H:%M') self.chart_locator.append(index) self.chart_formatter.append(time_format) self.trader.ax.xaxis.set_major_locator(ticker.FixedLocator(self.chart_locator)) self.trader.ax.xaxis.set_major_formatter(ticker.FixedFormatter(self.chart_formatter)) # Axis yticks & lines max_price = chart.High.max() min_price = chart.Low.min() if max_price > self.top_price or min_price < self.bottom_price: self.top_price = math.ceil(max_price / self.interval) * self.interval self.bottom_price = math.floor(min_price / self.interval) * self.interval self.interval_prices = numpy.arange(self.bottom_price, self.top_price + self.interval, self.interval) self.loss_cut_prices = numpy.arange(self.bottom_price + self.interval - self.loss_cut, self.top_price, self.interval) self.trader.ax.grid(axis='x', alpha=0.5) self.trader.ax.set_yticks(self.interval_prices) for price in self.interval_prices: self.trader.ax.axhline(price, alpha=0.5, linewidth=0.2) for price in self.loss_cut_prices: self.trader.ax.axhline(price, alpha=0.4, linewidth=0.2, color='Gray') # Current Price Annotation current_time = len(chart) current_price = chart.Close.iloc[-1] self.trader.ax.text(current_time + 0.5, current_price, format(current_price, ',.2f')) # Moving average x = range(0, len(chart)) self.trader.ax.plot(x, chart.MA5, label='MA5', color='Magenta') self.trader.ax.plot(x, chart.MA10, label='MA10', color='RoyalBlue') self.trader.ax.plot(x, chart.MA20, label='MA20', color='Gold') self.trader.ax.legend(loc='best') # Slope x_range = range(len(chart) - 1, len(chart) + 1) self.slope = numpy.polyfit(x_range, chart.MA5[-2:], 1) x = range(len(chart) - 20, len(chart)) y = numpy.poly1d(self.slope) self.trader.ax.plot(x, y(x), color='Sienna') # Set lim x2 = len(chart) x1 = x2 - self.chart_scope if x1 < 0: x1 = 0 elif x1 > x2 - 1: x1 = x2 - 1 y1 = self.get_min_price(x1, x2) - 0.1 y2 = self.get_max_price(x1, x2) + 0.1 self.trader.ax.set_xlim(x1, x2) self.trader.ax.set_ylim(y1, y2) # After price data acquired if self.start_time: self.annotate_chart(current_time, x1, x2, y1, y2) # Draw chart candlestick2_ohlc(self.trader.ax, chart.Open, chart.High, chart.Low, chart.Close, width=0.4, colorup='red', colordown='blue') self.trader.fig.tight_layout() self.trader.canvas.draw()
def showGraph(self, term): self.change_value.emit(ZERO) df = self.df ndf = df.copy() curr = 0 idx = 0 for i, row in df.iterrows(): if idx == 0: curr = i # curr = dt.strptime(row['date'], "%Y.%m.%d") else: timeGap = (dt.strptime(df.loc[curr]['date'], "%Y.%m.%d") - dt.strptime(row['date'], "%Y.%m.%d")).days if abs(timeGap) < term: if row['high'] > df.loc[curr]['high']: ndf.loc[curr, 'high'] = row['high'] if row['low'] > df.loc[curr]['low']: ndf.loc[curr, 'low'] = row['low'] ndf.loc[curr, 'close'] = row['close'] ndf.drop(index=i, inplace=True) else: curr = i idx += 1 self.change_value.emit(TWENTY_FIVE) self.fig.clear() ax = self.fig.add_subplot(111) ax.plot(ndf['date'], ndf['close'].rolling(window=5).mean(), label="5", linewidth=0.7) ax.plot(ndf['date'], ndf['close'].rolling(window=20).mean(), label="20", linewidth=0.7) ax.plot(ndf['date'], ndf['close'].rolling(window=60).mean(), label="60", linewidth=0.7) ax.plot(ndf['date'], ndf['close'].rolling(window=120).mean(), label="120", linewidth=0.7) candlestick2_ohlc(ax, ndf['open'], ndf['high'], ndf['low'], ndf['close'], width=1, colorup='r', colordown='b') self.change_value.emit(FIFTY) self.fig.suptitle("candle") ax.set_xlabel("date") ax.set_ylabel("stock price") # ax.tick_params(axis='x', labelrotation=20) ax.autoscale_view() self.change_value.emit(SEVENTY_FIVE) ax.xaxis.set_major_locator(ticker.MaxNLocator(5)) ax.legend(loc=1) # legend 위치 self.canvas.draw() self.change_value.emit(A_HUNDRED)
def csvCandle(data, inc, name): #CSV version - volume and dates are broken print("-----loading from csv-----", name) plt.figure(inc) data.reset_index(inplace=True) df_volume = data['Adj Close'] plt.xticks(rotation=45) plt.xlabel("Date") plt.ylabel("Price") plt.suptitle(name) ax1 = plt.subplot2grid((6, 1), (0, 0), rowspan=5, colspan=1) ax2 = plt.subplot2grid((6, 1), (5, 0), rowspan=5, colspan=1, sharex=ax1) ax2.set_title('Volume') #date functions cause viewlimit crash due to same datetime reason as resample() issue, dont use #ax1.xaxis_date() #ax1.xaxis.set_major_formatter(mdates.DateFormatter("%Y-%m-%d")) try: candlestick2_ohlc(ax1, data['Open'], data['High'], data['Low'], data['Close'], width=.6, colorup='#00eeff', colordown='#ff0044', alpha=.4) except: print('ERROR candlestick2_ohlc failed') main() #fills volume visual with data ax2.fill_between(data.index, data['Volume'].values, 0) #add spacing between subplots plt.subplots_adjust(hspace=0.7) #formats the y axis ticker to represent dollars formatter = ticker.FormatStrFormatter('$%1.2f') ax1.yaxis.set_major_formatter(formatter) for tick in ax1.yaxis.get_major_ticks(): tick.label1.set_visible(False) tick.label2.set_visible(True) #tick.label2.set_color('green') #sets ticker to the left side ax1.yaxis.tick_left() ax1.yaxis.set_label_position("left") ax1.grid(b=True, which='major', color='grey', linestyle='-', alpha=0.4) #maximizes window #this backend is: TkAgg manager = plt.get_current_fig_manager() manager.resize(*manager.window.maxsize()) return
def pic(df, name, folder_name): Path("/content/"+folder_name+"/").mkdir(parents=True, exist_ok=True) fig = plt.figure() ax_1 = fig.add_subplot(2, 2, 1) candlestick2_ohlc(ax_1, df["Open"], df["High"], df["Low"], df["Close"], width=0.6) plt.savefig("/content/"+folder_name+"/"+name + ".png")
def drawchart_stock(code, wgtParent): # 차트 시작 일자 설정 (조회일로 부터 90일 전) start = datetime.datetime.now() + datetime.timedelta(days=-90) # DB에서 90일치 종목코드에 대한 주가정보 데이터프레임으로 가져오기 conn = sqlite3.connect(dbpath, isolation_level=None) cur = conn.cursor() query = "SELECT * FROM STOCK_PRICE WHERE code = '" + code + "' AND Date >= '" + start.strftime('%Y-%m-%d') + "'" result = cur.execute(query) cols = [column[0] for column in result.description] stock_df = pd.DataFrame.from_records(data=result.fetchall(), columns=cols) stock_df['Date2'] = pd.to_datetime(stock_df['Date']) print(stock_df) # 차트 그리기 fig = plt.figure() ax = fig.add_subplot(111) day_list = [] name_list = [] for i, day in enumerate(stock_df['Date2']): print('[{}] {}'.format(i, day)) # if day.dayofweek == datetime.datetime.today().weekday(): day_list.append(i) name_list.append(day.strftime('%m-%d')) print(pd.DataFrame([day_list, name_list])) # X축 날짜 표시 ax.xaxis.set_major_locator(ticker.FixedLocator(day_list)) ax.xaxis.set_major_formatter(ticker.FixedFormatter(name_list)) plt.xticks(rotation=45) # 그래프 title과 축 이름 지정 ax.set_title(stock_df['Name'].unique()[0], fontsize=22) # ax.set_xlabel('Date') # 캔들차트 그리기 candlestick2_ohlc(ax, stock_df['Open'], stock_df['High'], stock_df['Low'], stock_df['Close'], width=0.5, colorup='r', colordown='b') ax.legend() ax.grid(True, axis='x', linestyle='--') plt.grid() if __name__ == '__main__': plt.show() else: canvas = FigureCanvas(fig) vbxIndexes = QVBoxLayout(wgtParent) vbxIndexes.addWidget(canvas) canvas.draw() # 화면 표시 # canvas = FigureCanvas(fig) # vbxIndexes = QVBoxLayout(wgtParent) # vbxIndexes.addWidget(canvas) # canvas.draw() # commit 및 종료 conn.commit() conn.close() return
def __create(self): # マージン設定 matplotlib.rcParams['axes.xmargin'] = 0.001 # X軸 matplotlib.rcParams['axes.ymargin'] = 0.05 # Y軸 # グラフ設定 self.__fig = plt.figure(figsize=(self.__width, self.__height)) self.__fig.autofmt_xdate() plt.subplots_adjust(wspace=0.0, hspace=0.0) # グラフ間余白 # チャート配置割り grids = { k: self.__yaxis[k]['gridspec'] if k in self.__yaxis.keys() else 1 for k in self.__indicators.keys() } total_grid = sum(grids.values()) #total_grid = len(self.__indicators.keys()) gs = gridspec.GridSpec(total_grid, 1) # X軸列設定 lst_x = range(len(self.__df.index)) ax_idx = 0 grid = 0 ax0 = None for k, g in grids.items(): if grid == 0: # 最上段チャートはタイトル設定 # axis作成 ax = plt.subplot(gs[grid:grid + g, 0]) ax0 = ax # X軸同期のため # タイトル ax.set_title(self.__title['title'], loc=self.__title['loc'], fontsize=self.__title['fontsize']) else: # axis作成 ax = plt.subplot(gs[grid:grid + g, 0], sharex=ax0) # 最上段チャートにX軸同期 # 最下段チャートはX軸目盛り設定 if grid + g == total_grid: ax.xaxis.set_major_locator(ticker.MaxNLocator(10)) if self.__xaxis['col'] in self.__df.columns: xcol = self.__df[self.__xaxis['col']].values else: xcol = self.__df.index.values def mydate(x, pos): try: if self.__xaxis['converter'] == None: return x else: return self.__xaxis['converter'](xcol[int(x)]) except IndexError: return '' ax.xaxis.set_major_formatter(ticker.FuncFormatter(mydate)) else: # x軸目盛り非表示 ax.tick_params(labelbottom=False, bottom=False) # 枠線設定 axis = ['top', 'bottom', 'left', 'right'] line_width = [1, 1, 1, 1] for a, w in zip(axis, line_width): ax.spines[a].set_visible(True) ax.spines[a].set_linewidth(w) ax.spines[a].set_color('dimgray') # 背景色設定 color_idx = ax_idx % len(self.__backcolor) ax.patch.set_facecolor(self.__backcolor[color_idx]) ax.set_axisbelow(True) # グリッドがプロットした点や線の下に隠れる #メモリの長さ,太さ, ラベルサイズの調整 ax.tick_params(direction='out', length=1, width=1, labelsize=10) #ax.ticklabel_format(useOffset=False, style='plain') # オフセットと科学表記を無効 ax.yaxis.set_major_formatter( ticker.ScalarFormatter(useMathText=True)) # Y軸目盛りを10のべき乗表記 # インジケータ設定 has_label = False for indi in self.__indicators[k]: # candlestick if indi['type'] == 'candlestick': mpf.candlestick2_ohlc( ax, opens=self.__df[indi['open']].values, highs=self.__df[indi['high']].values, lows=self.__df[indi['low']].values, closes=self.__df[indi['close']].values, width=indi['width'], colorup=indi['upcolor'], colordown=indi['downcolor']) # line elif indi['type'] == 'line': ax.plot(lst_x, self.__df[indi['y']], color=indi['color'], linewidth=indi['linewidth'], linestyle=indi['linestyle'], label=indi['label']) # bar elif indi['type'] == 'bar': ax.bar(lst_x, self.__df[indi['y']], color=indi['color'], width=indi['width'], label=indi['label']) # mark elif indi['type'] == 'mark': ax.scatter(lst_x, self.__df[indi['y']], marker=indi['marker'], s=indi['size'], c=indi['color']) # band elif indi['type'] == 'band': ax.fill_between( lst_x, self.__df[indi['y1']], self.__df[indi['y2']], where=self.__df[indi['y1']] >= self.__df[indi['y2']], facecolor=indi['upcolor'], alpha=indi['alpha'], interpolate=True) ax.fill_between( lst_x, self.__df[indi['y1']], self.__df[indi['y2']], where=self.__df[indi['y1']] <= self.__df[indi['y2']], facecolor=indi['downcolor'], alpha=indi['alpha'], interpolate=True) ax.plot(lst_x, self.__df[indi['y1']], lst_x, self.__df[indi['y2']], color=indi['linecolor'], linewidth=indi['linewidth'], label=indi['label']) # ラベル設定チェック if indi['type'] != 'candlestick' and indi[ 'label'] != None and len(indi['label']) > 0: has_label = True # X軸グリッド ax.xaxis.grid(self.__xaxis['grid'], which='major', linestyle='dotted', color='lightgray') if k in self.__yaxis.keys(): # Y軸グリッド ax.yaxis.grid(self.__yaxis[k]['grid'], which='major', linestyle='dotted', color='lightgray') # Y軸ラベル ax.set_ylabel(self.__yaxis[k]['title'], fontsize=12, color='dimgray') # 凡例表示 if self.__yaxis[k]['legend'] and has_label: ax.legend() grid += g ax_idx += 1
def get_candle(coin, type, term, min=1): if type == 'd': link = "https://api.upbit.com/v1/candles/days" params = {"count": term, "market": coin} response = requests.get(link, params=params) response = json.loads(response.text) data = [] for r in response: temp_data = { "Date": r["candle_date_time_kst"][5:10], "open": float(r["opening_price"]), "high": float(r["high_price"]), "low": float(r["low_price"]), "close": float(r["trade_price"]), } data.append(temp_data) df = pd.DataFrame(data, columns=['Date', 'open', 'high', 'low', 'close']) df = df[::-1] fig = plt.figure(figsize=(12, 8)) ax = fig.add_subplot(111) ax.set_title(coin, fontsize=22) ax.xaxis.set_major_locator(plt.MaxNLocator(20)) ax.set_xlabel('Date') ax.plot(df['Date'], df['close']) ax.ticklabel_format(axis='y', style='plain') plt.gca().yaxis.set_major_formatter( StrMethodFormatter('{x:,.1f}')) # No decimal places candlestick2_ohlc(ax, df['open'], df['high'], df['low'], df['close'], width=0.5, colorup='r', colordown='b') plt.grid() newdir = 'img/output{}.png'.format(random.randint(100, 999)) plt.savefig(newdir) print(newdir) return newdir elif type == 'm': link = "https://api.upbit.com/v1/candles/minutes/{}".format(min) params = {"count": term, "market": coin} response = requests.get(link, params=params) response = json.loads(response.text) data = [] if int(min) >= 15: for r in response: temp_data = { "Date": r["candle_date_time_kst"], "open": float(r["opening_price"]), "high": float(r["high_price"]), "low": float(r["low_price"]), "close": float(r["trade_price"]), } data.append(temp_data) maxloc = 5 else: for r in response: temp_data = { "Date": r["candle_date_time_kst"][11:19], "open": float(r["opening_price"]), "high": float(r["high_price"]), "low": float(r["low_price"]), "close": float(r["trade_price"]), } data.append(temp_data) maxloc = 15 df = pd.DataFrame(data, columns=['Date', 'open', 'high', 'low', 'close']) df = df[::-1] fig = plt.figure(figsize=(12, 8)) ax = fig.add_subplot(111) ax.set_title(coin, fontsize=22) ax.xaxis.set_major_locator(plt.MaxNLocator(maxloc)) ax.set_xlabel('Date') ax.plot(df['Date'], df['close']) ax.ticklabel_format(axis='y', style='plain') plt.gca().yaxis.set_major_formatter( StrMethodFormatter('{x:,.1f}')) # No decimal places candlestick2_ohlc(ax, df['open'], df['high'], df['low'], df['close'], width=0.5, colorup='r', colordown='b') plt.grid() newdir = 'img/output{}.png'.format(random.randint(100, 999)) plt.savefig(newdir) return newdir elif type == 'w' or type == 'mo': if type == 'w': link = "https://api.upbit.com/v1/candles/weeks" elif type == 'mo': link = "https://api.upbit.com/v1/candles/months" params = {"count": term, "market": coin} response = requests.get(link, params=params) response = json.loads(response.text) data = [] for r in response: temp_data = { "Date": r["candle_date_time_kst"], "open": float(r["opening_price"]), "high": float(r["high_price"]), "low": float(r["low_price"]), "close": float(r["trade_price"]), } data.append(temp_data) maxloc = 5 df = pd.DataFrame(data, columns=['Date', 'open', 'high', 'low', 'close']) df = df[::-1] fig = plt.figure(figsize=(12, 8)) ax = fig.add_subplot(111) ax.set_title(coin, fontsize=22) ax.xaxis.set_major_locator(plt.MaxNLocator(maxloc)) ax.set_xlabel('Date') ax.plot(df['Date'], df['close']) ax.ticklabel_format(axis='y', style='plain') plt.gca().yaxis.set_major_formatter( StrMethodFormatter('{x:,.1f}')) # No decimal places candlestick2_ohlc(ax, df['open'], df['high'], df['low'], df['close'], width=0.5, colorup='r', colordown='b') plt.grid() newdir = 'img/output{}.png'.format(random.randint(100, 999)) plt.savefig(newdir) return newdir
def display_chart(self): chart = self.leverage.chart if not len(chart): return self.trader.ax.clear() # Axis ticker formatting if len(chart) // 30 > len(self.chart_locator) - 1: for index in range(len(self.chart_locator) * 30, len(chart), 30): time_format = chart.index[index].strftime('%H:%M') self.chart_locator.append(index) self.chart_formatter.append(time_format) self.trader.ax.xaxis.set_major_locator( ticker.FixedLocator(self.chart_locator)) self.trader.ax.xaxis.set_major_formatter( ticker.FixedFormatter(self.chart_formatter)) # Axis yticks & lines max_price = chart.High.max() min_price = chart.Low.min() if max_price > self.top_price or min_price < self.bottom_price: self.top_price = math.ceil( max_price / self.interval) * self.interval self.bottom_price = math.floor( min_price / self.interval) * self.interval self.interval_prices = list( range(self.bottom_price, self.top_price + self.interval, self.interval)) self.loss_cut_prices = list( range(self.bottom_price + self.interval - self.loss_cut, self.top_price, self.interval)) self.trader.ax.grid(axis='x', alpha=0.5) self.trader.ax.set_yticks(self.interval_prices) for price in self.interval_prices: self.trader.ax.axhline(price, alpha=0.5, linewidth=0.2) for price in self.loss_cut_prices: self.trader.ax.axhline(price, alpha=0.4, linewidth=0.2, color='Gray') # Current Price Annotation current_time = len(chart) current_price = chart.Close.iloc[-1] self.trader.ax.text(current_time + 2, current_price, format(current_price, ',')) if self.reference_price: self.annotate_chart(current_time) # Moving average x = range(0, len(chart)) self.trader.ax.plot(x, chart.MA5, label='MA5') self.trader.ax.plot(x, chart.MA10, label='MA10') self.trader.ax.plot(x, chart.MA20, label='MA20') self.trader.ax.legend(loc='best') # Slope slope_x = range(len(chart) - 1, len(chart) + 1) slope = numpy.polyfit(slope_x, chart.MA5[-2:], 1) x = range(len(chart) - 20, len(chart)) y = numpy.poly1d(slope) self.trader.ax.plot(x, y(x)) # Draw Chart candlestick2_ohlc(self.trader.ax, chart.Open, chart.High, chart.Low, chart.Close, width=0.4, colorup='red', colordown='blue') self.trader.fig.tight_layout() self.trader.canvas.draw()
def buyStock(stockDf, codeNum, companyName, stockBuySell): # 그래프에서 날짜를 표시가기위해 datetime64 형의 인덱스를 String화하여 연도-월-일 형태로 저장 candlesticks_df = stockDf.tail(200) day_list = [] name_list = [] for i, day in enumerate(candlesticks_df.index): if day.dayofweek == 0: # 월요일에 해당하는 날짜값만 x축에 표시하기 위함 day_list.append(i) name_list.append(day.strftime('%y-%m-%d')) candlesticks_df = candlesticks_df.reset_index() # 한글 폰트 지정 font_name = font_manager.FontProperties( fname="c:/Windows/Fonts/malgun.ttf").get_name() rc('font', family=font_name) fig, ax = plt.subplots(figsize=(20, 10)) ax.xaxis.set_major_locator(ticker.FixedLocator(day_list)) ax.xaxis.set_major_formatter(ticker.FixedFormatter(name_list)) ax.plot(candlesticks_df.index, list(candlesticks_df.Conversion), label="전환선", linewidth=0.7, color='#0496ff') ax.plot(candlesticks_df.index, list(candlesticks_df.Standard), label="기준선", linewidth=0.7, color='#991515') ax.plot(candlesticks_df.index, list(candlesticks_df.Prespan1), label="선행스팬1", linewidth=0.7, color='#008000') ax.plot(candlesticks_df.index, list(candlesticks_df.Prespan2), label="선행스팬2", linewidth=0.7, color='#ff0000') ax.plot(candlesticks_df.index, list(candlesticks_df.Laggingspan), label="후행스팬", linewidth=0.7, color='black') # green cloud ax.fill_between(candlesticks_df.index, candlesticks_df['Prespan1'], candlesticks_df['Prespan2'], \ where=candlesticks_df['Prespan1'] > candlesticks_df['Prespan2'], facecolor='#008000', interpolate=True, alpha=0.25) # red cloud ax.fill_between(candlesticks_df.index, candlesticks_df['Prespan1'], candlesticks_df['Prespan2'], \ where=candlesticks_df['Prespan2'] > candlesticks_df['Prespan1'], facecolor='#ff0000', interpolate=True, alpha=0.25) candlestick2_ohlc(ax, candlesticks_df['Open'], candlesticks_df['High'], candlesticks_df['Low'], \ candlesticks_df['Close'], width=0.6, colorup='r', colordown='b', alpha=0.5) plt.xticks(rotation=45) plt.grid() # Chart info title = companyName + " (" + codeNum + ")" bgcolor = '#131722' grid_color = '#363c4e' spines_color = '#d9d9d9' # Axes plt.title(title, fontsize=20) plt.xlabel('날짜', fontsize=15) plt.ylabel('주가(원)', fontsize=15) ax.grid(linewidth='0.3') ax.spines['bottom'].set_color(spines_color) ax.spines['top'].set_color(spines_color) ax.spines['right'].set_color(spines_color) ax.spines['left'].set_color(spines_color) fig.tight_layout() ax.autoscale_view() plt.legend(loc='upper right', fontsize=15) tempToday = str(date.today()) createFolder("./" + tempToday + "/매수추천") createFolder("./" + tempToday + "/매도추천") # stockBuySell = True 경우 매수 추천 저장 if stockBuySell == True: tempStr = "./" + tempToday + "/매수추천/매수추천 - " + companyName + "(" + tempToday + ").png" plt.savefig(tempStr) print(companyName + "매수추천 저장 완료") # stockBuySell = False 경우 매도 추천 저장 elif stockBuySell == False: tempStr = "./" + tempToday + "/매도추천/매도추천 - " + companyName + "(" + tempToday + ").png" plt.savefig(tempStr) print(companyName + "매도추천 저장 완료")
import yfinance as yf import matplotlib.pyplot as plt from mplfinance.original_flavor import candlestick2_ohlc import matplotlib.dates as mdt import datetime as dt start = '2020-05-13' end = '2020-07-07' acao = yf.download('SHOW3.SA', start, end) acao.reset_index(inplace=True) fig, ax = plt.subplots() plt.title('SHOW3') plt.xlabel('') plt.ylabel('') candlestick2_ohlc(ax, acao.Open, acao.High, acao.Low, acao.Close, width=1, colorup='g') plt.savefig('meugrafico.png') plt.show()
def PlotOHLC(charts: Charts, trigger_queue=None, extra_plot1=None, extra_plot2=None, chart_style='ohlc', fast_ema=None, normal_ema=None, slow_ema=None, plot_bb=False, bb_sample_num=50, sigma=2, rsi=None, plot_obv=False, plot_volume=False): """arrange subplots""" if rsi and (plot_obv or plot_volume): big_rowspan = 70 small_rowspan = 15 rsi_pos = big_rowspan obv_pos = rsi_pos + small_rowspan elif rsi or plot_obv or plot_volume: big_rowspan = 80 small_rowspan = 20 rsi_pos = big_rowspan obv_pos = big_rowspan else: big_rowspan = 100 small_rowspan = 0 rsi_pos = big_rowspan obv_pos = big_rowspan if trigger_queue: triggers = ConvertTriggersForPlot(charts, trigger_queue) else: triggers = None for market_name in charts.close: """add figure number""" global TEST_GLOBAL_plt_fig_num TEST_GLOBAL_plt_fig_num += 1 plt.figure(TEST_GLOBAL_plt_fig_num) # plt.get_current_fig_manager().full_screen_toggle() """do the plotting""" ax1 = plt.subplot2grid((100, 1), (0, 0), rowspan=big_rowspan, colspan=1) # ax1.set_facecolor('#4B4B4B') # plt.xticks(np.arange(charts.chart_lengths[market_name]), charts.date_unix[market_name], rotation=15) # not showing the value of x bottom right # plt.locator_params(axis='x', nbins=6) # shows only the original lines when chart is zoomed if fast_ema: ax1.plot(EMA_rolling(charts.close[market_name], window=fast_ema), color='C0', label=str(fast_ema) + ' EMA', alpha=.7) if normal_ema: ax1.plot(EMA_rolling(charts.close[market_name], window=normal_ema), color='gold', label=str(normal_ema) + ' EMA', alpha=.7) if slow_ema: ax1.plot(EMA_rolling(charts.close[market_name], window=slow_ema), color='red', label=str(slow_ema) + ' EMA', alpha=.7) if plot_bb: bb = BolingerBands_rolling(SMA_rolling(charts.close[market_name], window=bb_sample_num), StandardDev_rolling( charts.close[market_name], window=bb_sample_num), sigma=sigma) ax1.plot(bb["Upper"], color='purple', label='BB (' + str(bb_sample_num) + ', ' + str(sigma) + ')', alpha=.7) ax1.plot(bb["Lower"], color='purple', alpha=.7) if trigger_queue: ax1.plot(triggers["buy"][market_name], color='darkgreen', marker='^', linestyle='', alpha=.8) ax1.plot(triggers["sell"][market_name], color='darkred', marker='v', linestyle='', alpha=.8) if extra_plot1: dimensions = np.shape(extra_plot1[market_name])[0] if dimensions: for layer in range(0, dimensions): ax1.plot(extra_plot1[market_name][layer], color='green') else: ax1.plot(extra_plot1[market_name], color='green') if extra_plot2: dimensions = np.shape(extra_plot2[market_name])[0] if dimensions: for layer in range(0, dimensions): ax1.plot(extra_plot2[market_name][layer], color='red') else: ax1.plot(extra_plot2[market_name], color='red') if 'ohlc' == chart_style: candlestick2_ohlc(ax1, opens=list(charts.open[market_name]), highs=list(charts.high[market_name]), lows=list(charts.low[market_name]), closes=list(charts.close[market_name]), colorup='#14E3C5', colordown='#F45A5A', width=1, alpha=1.0) else: # 'line' == chart_style ax1.plot(charts.close[market_name], color='green') ax1.grid(True) ax1.set_title(market_name) ax1.set_ylabel('Price') if fast_ema or normal_ema or slow_ema or plot_bb: ax1.legend() if rsi: ax2 = plt.subplot2grid((100, 1), (rsi_pos, 0), sharex=ax1, rowspan=small_rowspan, colspan=1) rsi_line = RSI_rolling(charts.close[market_name], window=rsi) ax2.plot(rsi_line, color='C0') ax2.axhline(y=70, color='red', linestyle='--', alpha=.5) ax2.axhline(y=30, color='green', linestyle='--', alpha=.6) ax2.set_ylim(bottom=0, top=100) ax2.set_ylabel(str(rsi) + ' RSI') ax2.set_yticks([30, 70]) ax2.xaxis.grid() # plt.connect('button_press_event', DrawVerticalLine) if plot_obv or plot_volume: ax3 = plt.subplot2grid((100, 1), (obv_pos, 0), sharex=ax1, rowspan=small_rowspan, colspan=1) if plot_volume: if not plot_obv: ax3_vol = ax3 else: ax3_vol = ax3.twinx() volume_overlay(ax3_vol, charts.open[market_name], charts.close[market_name], charts.volume[market_name], colorup='#14E3C5', colordown='#F45A5A', width=1, alpha=.6) ax3_vol.set_ylim(0, max(charts.volume[market_name])) ax3_vol.set_ylabel('Volume') ax3_vol.get_yaxis().set_label_position('left') ax3_vol.get_yaxis().tick_left() if plot_obv: obv = OBV_rolling(charts, market_name) ax3.plot(obv, color='darkblue', label='OBV') ax3.set_ylim(bottom=min(obv), top=max(obv)) ax3.legend() ax3.get_yaxis().set_ticks([]) ax3.xaxis.grid() plt.xlim(xmin=-1, xmax=charts.chart_lengths[market_name] + 1)