def plot_price_chart(self, popen, phigh, plow, pclose, ax=None, spines_col='#5998ff'): ax.grid(True, linestyle='--', linewidth=0.3) ax.yaxis.label.set_color('w') ax.spines['top'].set_color(spines_col) ax.spines['bottom'].set_color(spines_col) ax.spines['left'].set_color(spines_col) ax.spines['right'].set_color(spines_col) ax.tick_params(axis='x', colors='w') ax.tick_params(axis='y', colors='w') ax.get_xaxis().set_visible(False) candlestick2_ohlc(ax, popen, phigh, plow, pclose, width=1, colorup='#9eff15', colordown='#ff1717') return ax
def showCandle(self, idx): fig = plt.figure() ax = fig.add_subplot(1, 1, 1) nary = np.zeros((self.sizeofset, 4), dtype=float) fxary = self.datas[idx].reshape((self.sizeofset, self.sizeofdata)) fxlabelary = self.labels[idx] idxary = np.where(fxlabelary == 1) idx = idxary[0][0] plt.title('label:' + str(idx)) #ax.title = 'label:' + str(idx) for i in range(self.sizeofset): data = fxary[i] nary[i] = [data[0], data[1], data[2], data[3]] tary = nary.T mpf.candlestick2_ohlc(ax, opens=tary[0], highs=tary[1], lows=tary[2], closes=tary[3], width=0.7, colorup='g', colordown='r') #mpf.candlestick_ohlc(ax,[op,hi,lo,cl],width=0.7, colorup='g', colordown='r') ax.grid() plt.show()
def graph(self): for oneaxe in fig.axes: oneaxe.clear() oneaxe.legend(prop={'size': 6}) # close df = self.getdataframe('close') print(df) print('-' * 25) print(df.values[0]) df = 100 * ((df / df.values[0]) - 1) self.dfindexdate(df) df.plot(ax=ax0) # dt = self.tick # dt = 100 * ((dt / dt.values[0]) - 1) # dt.plot(ax=ax1) # # # volume # dfv = self.getdataframe('volume').pct_change() # self.dfindexdate(dfv) # dfv.plot(ax=ax2, width=.9, kind='bar', alpha=.8) # ohlc btc for i, pair in enumerate(self.pairs): quotes = self.dfpairs[pair] candlestick2_ohlc(axs[i], quotes['open'], quotes['high'], quotes['low'], quotes['close'], width=0.6) axs[i].set_title(pair, fontsize=8)
def candlechart(data, width=0.8): fig, ax = plt.subplots() # ローソク足 mpf.candlestick2_ohlc(ax, opens=data.open.values, closes=data.close.values, lows=data.low.values, highs=data.high.values, width=width, colorup='r', colordown='b') xdate = data.index ax.xaxis.set_major_locator(ticker.MaxNLocator(20)) def mydate(x, pos): try: return xdate[int(x)] except IndexError: return '' ax.xaxis.set_major_formatter(ticker.FuncFormatter(mydate)) ax.format_xdata = mdates.DateFormatter('%m-%d') fig.autofmt_xdate() fig.tight_layout() return fig, ax
def plot_prices(self, st_id): fig, ax = plt.subplots(1, 1) quotes = self.strats[st_id].prices.tz_localize(pytz.timezone('UTC')) quotes = quotes.reset_index() candlestick2_ohlc(ax, quotes['open'], quotes['high'], quotes['low'], quotes['close'], width=0.4, colorup='g', colordown='r', alpha=0.4) tdate = [i for i in quotes['Timestamp']] ax.xaxis.set_major_locator(ticker.MaxNLocator(10)) ax.xaxis.set_minor_locator(ticker.MaxNLocator(40)) for trade in self.trades: if trade.strategy_id == st_id: index = tdate.index(trade.timestamp) if trade.quantity > 0: plt.plot(index, trade.price, 'go') elif trade.quantity < 0: plt.plot(index, trade.price, 'ro') fig.autofmt_xdate() plt.title("Strategy " + str(st_id) + " prices") plt.show(block=False)
def SuppRes(df0): df_open = df0.Open.copy() df_high = df0.High.copy() df_low = df0.Low.copy() df_close = df0.Close.copy() df_support = argrelmin(df_low.values, order=5) support_prices = df_low[df_support[0]] support_prices_lower = df_open[df_support[0]] resistance = argrelmax(df_high.values, order=5) resistance_prices = df_high[resistance[0]] resistance_prices_higher = df_open[resistance[0]] print('Support prices', support_prices) print('Support:', df_support) print('Resistance:', resistance) resistance_prices fig, ax = plt.subplots(figsize=[15, 9]) candlestick2_ohlc(ax, df0['Open'], df0['High'], df0['Low'], df0['Close'], colorup='green', colordown='red', width=0.5) plt.scatter(df_support, support_prices) plt.scatter(resistance, resistance_prices) # plt.plot(np.unique(df_support), np.poly1d(np.polyfit(df_support, support_prices, 1))(np.unique(df_support))) plt.show()
def _draw_chart(self, df): data = df.head(30) date = pd.to_datetime(data.index) xlist = [v.strftime("%m/%d") for v in date] self.chart.clear() ax = self.chart.add_subplot(111) dlist = range(len(xlist)) ax.xaxis.set_major_locator(ticker.FixedLocator(dlist)) ax.xaxis.set_major_formatter(ticker.FixedFormatter(xlist)) ax.invert_xaxis() mpl.candlestick2_ohlc(ax, data["Open"], data["High"], data["Low"], data["Close"], width=0.5, colorup='r', colordown='b') #ax.legend(loc='best') ax.grid() self.canvas.draw()
def plot_levels_on_candlestick( df, levels, only_good=False, path=None, formatter=mdates.DateFormatter('%y-%m-%d %H:%M:%S')): ohlc = df[['Date', 'Open', 'High', 'Low', 'Close']].copy() ohlc["Date"] = pd.to_datetime(ohlc['Date']) ohlc["Date"] = ohlc["Datetime"].apply(lambda x: mdates.date2num(x)) f1, ax = plt.subplots(figsize=(10, 5)) candlestick2_ohlc(ax, closes=ohlc.Close.values, opens=ohlc.Open.values, highs=ohlc.High.values, lows=ohlc.Low.values, colordown='red', colorup='green') _plot_levels(ax, levels, only_good) if path: plt.savefig(path) else: plt.show() plt.close()
def plot(self): ''' plot some random stuff ''' # random data #data = [random.random() for i in range(50)] # create an axis ax = self.figure.add_subplot(111) # discards the old graph # ax.hold(False) # deprecated, see above print self.currentData['Open'], self.currentData[ 'High'], self.currentData['Low'], self.currentData['Close'] candlestick2_ohlc(ax, self.currentData['Open'], self.currentData['High'], self.currentData['Low'], self.currentData['Close'], width=0.6) # plot data #ax.plot(data, 'x-') # refresh canvas self.canvas.draw()
def show_candlestick(ohlc): fig, ax = plt.subplots() # ローソク足 mpf.candlestick2_ohlc(ax, opens=ohlc['1_open'].values, closes=ohlc['4_close'].values, lows=ohlc['3_low'].values, highs=ohlc['2_high'].values, width=0.2, colorup='r', colordown='b') # x軸を時間にする xdate = ohlc.index ax.xaxis.set_major_locator(ticker.MaxNLocator(6)) f = lambda x, y: mydate(x, ohlc) ax.xaxis.set_major_formatter(ticker.FuncFormatter(f)) ax.format_xdata = mdates.DateFormatter('%Y-%m-%d') fig.autofmt_xdate() fig.tight_layout() plt.show()
def func_plot_type1(Open, High, Low, Close, indicator, result): plt.figure() # ax1 ax1 = plt.subplot(211) mpf.candlestick2_ohlc(ax1, Open, High, Low, Close, width=0.5, colorup='green', colordown='red') # x = list(range(len(data_HA))) # y = data_HA.HA_High.values # p = data_PS.values # data_CT.values # q = data_CT.bar_idx_live.values # for i,j in zip(x,y): # ax1.text(i,j, '%d' % p[i]) # ax1.text(i,j-20, '%d' % q[i]) ax1.fill_between(range(len(Close)), [Close.max()]*len(Close), [Close.min()]*len(Close), where=indicator== 1, facecolor='green', alpha=0.5) ax1.fill_between(range(len(Close)), [Close.max()]*len(Close), [Close.min()]*len(Close), where=indicator==-1, facecolor='red', alpha=0.5) # ax2 ax2 = plt.subplot(212, sharex=ax1) plt.plot(result[0]) plt.title('Accumulated Return = %s ; Trade Number = %s ; Return per Trade= %s bp' % (result[0][-1], result[1], result[0][-1]/result[1]*10000)) plt.show()
def candlesticks(cls, df, start_date, end_date): quotes = Strategy.slicebydate(df, start_date, end_date) fig, ax = plt.subplots() # candle.candlestick2_ohlc(ax,quotes['Open'],quotes['High'],quotes['Low'],quotes['Close'],width=0.6,colorup='#53AA03',colordown="#C20074") candle.candlestick2_ohlc( ax, quotes['Open'], quotes['High'], quotes['Low'], quotes['Close'], width=0.6, colorup='#10069D', colordown="#34E5DA") # color up is blue and down is cyan xdate = [i.to_pydatetime() for i in quotes['Date']] ax.xaxis.set_major_locator(ticker.MaxNLocator(6)) def mydate(x, pos): try: return xdate[int(x)] except IndexError: return '' ax.xaxis.set_major_formatter(ticker.FuncFormatter(mydate)) fig.autofmt_xdate() plt.plot()
def candlechart(data, width=0.6): fig, ax = plt.subplots() print(data) # ローソク足 mpf.candlestick2_ohlc( ax, opens=data.open.values, closes=data.close.values, lows=data.low.values, highs=data.high.values, width=width, colorup='#77d879', colordown='#db3f3f') xticks_number = 12 xticks_index = range(0, len(data), xticks_number) xticks_display = [data.time.values[i][11:16] for i in xticks_index] # 時間を切り出すため、先頭12文字目から取る fig.autofmt_xdate() fig.tight_layout() plt.sca(ax) plt.xticks(xticks_index, xticks_display) plt.legend() plt.show()
def plot_candle_chart(df, pic_name='candle_chart'): # 对数据进行整理 df.set_index(df['交易日期'], drop=True, inplace=True) df = df[['开盘价', '最高价', '最低价', '收盘价']] # 作图 ll = np.arange(0, len(df), 1) my_xticks = df.index[ll].date fig, ax = plt.subplots() mplf.candlestick2_ohlc(ax, df['开盘价'].values, df['最高价'].values, df['最低价'].values, df['收盘价'].values, width=0.6, colorup='r', colordown='g', alpha=1) plt.xticks(ll, my_xticks) plt.xticks(rotation=60) plt.title(pic_name) plt.subplots_adjust(left=0.09, bottom=0.20, right=0.94, top=0.90, wspace=0.2, hspace=0) # 保存数据 # plt.savefig(pic_name+'.png') plt.show()
def get_graphs(self, indicators: list): data = self.get_dataframe(indicators) xdate = [datetime.fromtimestamp(datetime.strptime(str(date[:-3]), '%b %d %Y %H:').timestamp()) \ for date in data['date']] fig, ax = plt.subplots(len(data.keys()) - 4 + 1, sharex=True, dpi=1000) candlestick2_ohlc(ax[0], data['open'], data['high'], data['low'], data['close'], width=0.6) ax[0].xaxis.set_major_locator(ticker.MaxNLocator(20)) def chart_date(x, pos): try: return xdate[int(x)] except IndexError: return '' ax[0].xaxis.set_major_formatter(ticker.FuncFormatter(chart_date)) fig.autofmt_xdate() fig.tight_layout() i = 1 for indicator in list(data.keys())[5:]: ax[i].plot(data[indicator]) i += 1 plt.show() fig.savefig(self.skin.name) output = {} for indicator in list(data.keys())[4:]: output[indicator] = data[indicator][-1] return output
def isolated_candle_graph(): conn = MySQLdb.connect(host='localhost', user='******', passwd='pickle',# db='pickledb') # falsified information cursor = conn.cursor() sql = "SELECT * FROM ddr" cursor.execute(sql) result = cursor.fetchall() print(result) df = pd.DataFrame(list(result), columns=["Date", "Open", "High", "Low", "Close", "Adj_Close", "Volume"]) fig, ax = plt.subplots() mpl_finance.candlestick2_ohlc(ax, df.Open, df.High, df.Low, df.Close, width=0.6, colorup='r', colordown='c', alpha=1) df = df.set_index(df["Date"]) xdate = df.index def mydate(x, pos): try: return xdate[int(x)] except IndexError: return '' ax.xaxis.set_major_formatter(ticker.FuncFormatter(mydate)) plt.show()
def chart(plan, id, symbol, time, date): #UP- name = id + "_" + str(time) total = 0 for i in plan.keys(): if i == id: for ii in plan.get(i)['strat'].keys(): total += 1 df = hd.handler().candle_data(symbol, plan.get(i)['strat'][ii], 20) fig, ax = plt.subplots(figsize=(15, 10)) candlestick2_ohlc(ax, df.open, df.high, df.low, df.close, width=0.5, colorup='g', colordown='r') ax.set_title( f"{symbol} with {plan.get(i)['strat'][ii]} Minutes Candle", fontsize=18) if not os.path.exists(f'./DATA/charts/{date}'): #UP- os.makedirs(f'./DATA/charts/{date}') #UP- plt.savefig(f'./DATA/charts/{date}/{name}_{total}.svg') #UP- plt.clf()
def make_gs(CODE, where): for code in CODE: url = "https://navercomp.wisereport.co.kr/v2/company/c1040001.aspx?cmp_cd=" + code + "&cn=" html = req.urlopen(url) soup = BeautifulSoup(html, 'html.parser') name = soup.select("span.name")[0].text # 회사명 넣기 data = fdr.DataReader(code, dt(2018,10,1), dt(2019,12,1)).iloc[:,:5] idx = data.index.astype(str) ma = fdr.DataReader(code, dt(2018,10,1),dt(2019,12,1)).ix[:,-3] ma5 = fdr.DataReader(code, dt(2018,9,20),dt(2019,12,1)).ix[:,-3].rolling(window=5).mean()[4:] ma20 = fdr.DataReader(code, dt(2018,8,30),dt(2019,12,1)).ix[:,-3].rolling(window=20).mean()[19:] ma60 = fdr.DataReader(code, dt(2018,7,4),dt(2019,12,1)).ix[:,-3].rolling(window=60).mean()[59:] ma120 = fdr.DataReader(code, dt(2018,4,4),dt(2019,12,1)).ix[:,-3].rolling(window=120).mean()[119:] fig, ax = plt.subplots(figsize=(12,7)) # 여기서 차트 크기를 조정 할 수 있습니다. # 이동평균선을 차트에 추가 합니다. ax.plot(idx, ma5, label='5일', color='green', linewidth=2.5) ax.plot(idx, ma20, label='20일', color='red', linewidth=2.5) ax.plot(idx, ma60, label='60일', color='orange', linewidth=2.5) ax.plot(idx, ma120, label='120일', color='purple', linewidth=2.5) # 아래 명령어를 통해 시고저종 데이터를 사용하여 캔들 차트를 그립니다. candlestick2_ohlc(ax,data['Open'],data['High'], data['Low'],data['Close'],width=0.6, colorup = 'red', colordown ='blue') ax.xaxis.set_major_locator(ticker.MaxNLocator(6)) # 아래는 날짜 인덱싱을 위한 함수 입니다. def mydate(x,pos): try: return idx[int(x-0.5)] except IndexError: return '' ax.xaxis.set_major_formatter(ticker.FuncFormatter(mydate)) plt.title(name + ' , ' + code, size = 20) plt.xlabel('년/월',fontsize=15) plt.ylabel('가격(원)',fontsize=15) plt.grid(color='#BDBDBD', linestyle='--', linewidth=0.5 ) plt.legend(loc='best') plt.axvline(x='2018-12-03', color='black') fig.autofmt_xdate() plt.savefig(where + name + '.png') # blacklist = ['900280', '036800', '115310', '208710', '101330', '063760', '088130', '031980', # '036830', '183300', '269620', '241790', '039440', '011170'] # 과거기준으로 하려면? ma = fdr.DataReader(code, dt(2017,12,1),dt(2018,12,1)).ix[:,-3] ma5 = fdr.DataReader(code, dt(2017,11,27),dt(2018,12,1)).ix[:,-3].rolling(window=5).mean()[4:] ma20 = fdr.DataReader(code, dt(2017,11,6),dt(2018,12,1)).ix[:,-3].rolling(window=20).mean()[19:] ma60 = fdr.DataReader(code, dt(2017,9,1),dt(2018,12,1)).ix[:,-3].rolling(window=60).mean()[59:] ma120 = fdr.DataReader(code, dt(2017,6,8),dt(2018,12,1)).ix[:,-3].rolling(window=120).mean()[119:]
def show_graph(ohlc): ax = plt.subplot() ax.grid(color='gray', linestyle='--', linewidth=0.5) mpf.candlestick2_ohlc(ax, ohlc.open.values, ohlc.high.values, ohlc.low.values, ohlc.close.values, 0.5, 'r', 'b') plt.show()
def candle_stick(self, wrangled): fig = plt.figure(figsize = (28,5)) ax = fig.add_subplot(1,1,1) mplfin.candlestick2_ohlc(ax, width=1, colorup='r', colordown='b', opens = wrangled['Adj. Open'], highs = wrangled['Adj. High'], lows = wrangled['Adj. Low'], closes = wrangled['Adj. Close']) plt.savefig(str(os.getcwd()).replace('\\','/')+'/images/candlestick.png') plt.close()
def createChart(self): fig, ax = plt.subplots(figsize=(8, 4)) candlestick2_ohlc(ax, self.data['Open'], self.data['High'], self.data['Low'], self.data['Close'], width=0.4) xs = len(self.data) locs = [0, 20, 40, 60, 80, 100, 120, xs - 1] plt.xticks(locs, self.data.loc[locs, 'Date']) a = self.data.sort_values('Date', ascending=False).reset_index(drop=True) ma = a.loc[0:8, 'Close'].mean() plt.hlines(ma, xs, xs + 1, colors="blue") plt.text(x=xs + 2, y=ma, s="8", fontsize=8, color='b') ma = a.loc[0:21, 'Close'].mean() plt.hlines(ma, xs, xs + 2, colors="blue") plt.text(x=xs + 3, y=ma, s="21", fontsize=8, color='b') ma = a.loc[0:50, 'Close'].mean() plt.hlines(ma, xs, xs + 4, colors="blue") plt.text(x=xs + 5, y=ma, s="50", fontsize=8, color='b') ma = a.loc[0:100, 'Close'].mean() plt.hlines(ma, xs, xs + 6, colors="blue") plt.text(x=xs + 7, y=ma, s="100", fontsize=8, color='b') self.squeeze() sq = self.squeezeLen() plt.text(x=80, y=self.data["Low"].min(), s="Daily Squeeze = " + str(sq), fontsize=8, color='b') self.squeezeWeekly() sq = self.squeezeLenWeekly() plt.text(x=110, y=self.data["Low"].min(), s="Weekly Squeeze = " + str(sq), fontsize=8, color='b') fig.autofmt_xdate() fig.tight_layout() figfile = BytesIO() fig.savefig(figfile, format='png') figfile.seek(0) figdata_png = base64.b64encode(figfile.getvalue()).decode('utf-8') self.chartURI = 'data:image/png;base64,{}'.format(figdata_png) plt.close()
def plot_ohlc(ax, ep, o, h, l, c, datetime_display_span="h"): max_price = max(h) min_price = min(l) old_val = -1 datecolor = "dodgerblue" do_show = False for i in range(len(ep)): t = ep[i] d = lib.epoch2dt(t) if datetime_display_span == "d": if d.hour == 0 and d.day != old_val: do_show = True old_val = d.day if datetime_display_span == "h": if d.minute == 0 and d.hour != old_val: do_show = True old_val = d.hour if do_show: if c[i] >= (max_price + min_price) / 2: yval = min_price else: yval = max_price ax.axvline(i, c=datecolor) ax.annotate("%02d-%02d\n%02d:%02d" % (int(d.month), int(d.day), int(d.hour), int(d.minute)), (i, yval), size=30, color=datecolor, horizontalalignment="left") do_show = False mid_price = (max_price + min_price) / 2 ax.axhline(y=max_price, color=datecolor) ax.annotate(max_price, (0, max_price), size=30, color=datecolor, horizontalalignment="right") ax.axhline(y=mid_price, color=datecolor) ax.annotate(mid_price, (0, mid_price), size=30, color=datecolor, horizontalalignment="right") ax.axhline(y=min_price, color=datecolor) ax.annotate(min_price, (0, min_price), size=30, color=datecolor, horizontalalignment="right") mpl_finance.candlestick2_ohlc(ax, opens=o, closes=c, lows=l, highs=h, width=0.8, colorup='lightgray', colordown='grey', alpha=1)
def draw_ohlc(self): #data의 변동이 있을때만 다시 그리기 self.topAxax.cla() mpl_finance.candlestick2_ohlc(self.topAxax, self.data['open'][-self.start:], self.data['high'][-self.start:], self.data['low'][-self.start:], self.data['close'][-self.start:], width=0.5, colorup='r', colordown='b')
def PlotCandleAll(self): candlestick2_ohlc(ax, self.data['Open'].values, self.data['High'].values, self.data['Low'].values, self.data['Close'].values, width=0.6, colorup='g', colordown='r', alpha=1)
def draw_K_line(data): """ 绘制K线图 :param data: :return: """ # year_2018 = df['2018-01-01':'2018-07-31'] fig, ax = plt.subplots(figsize=(16, 9)) candlestick2_ohlc(ax, data.Open, data.High, data.Low, data.Close, width=.5, alpha=.6) plt.show()
def plot_price_and_eval(o, h, l, c, eval): # Plotting data and result fig, axes = plt.subplots(nrows=1, ncols=1) candlestick2_ohlc(axes, o, h, l, c, colorup='black', colordown='b', width=0.3) for i in range(0, len(eval)): if eval[i] > 0: plt.axvline(i, c='green') elif eval[i] < 0: plt.axvline(i, c='red') plt.show()
def plot(csv,sell_time): df=pd.read_csv(csv) date=df['Date'] open=df['Open'] high=df['High'] low=df['Low'] close=df['Close'] fig=plt.figure(figsize=(7,5)) graph=fig.add_subplot(1,1,1) graph.plot(date,close,color='red') candlestick2_ohlc(graph,open,high,low,close,colorup="blue",colordown="red",width=2,alpha=0.5)
def plot_stock_price(self): df = self.__data_center.query('TradeData.Stock.Daily', '600000.SSE') df = df[df['trade_date'] > years_ago(1)] # df['trade_date'] = df['trade_date'].apply(lambda d: mdates.date2num(d.to_pydatetime())) adjust_ratio = df['adj_factor'] price_open = df['open'] * adjust_ratio price_close = df['close'] * adjust_ratio price_high = df['high'] * adjust_ratio price_low = df['low'] * adjust_ratio self.__figure.clear() ax1 = self.__figure.add_subplot(2, 1, 1) ax2 = self.__figure.add_subplot(2, 1, 2) time_serial = pd.to_datetime(df['trade_date'], format="%Y/%m/%d") # ax1 = plt.subplot2grid((3, 1), (0, 0), rowspan=2, colspan=1) # 佔全圖2/3的子圖一 ax1.set_xticks(range(0, len(time_serial), 10)) # 設定X軸座標 ax1.set_xticklabels(time_serial) # 設定X軸標籤 mpf.candlestick2_ohlc(ax1, df['open'], df['high'], df['low'], df['close'], width=0.6, colorup='r', colordown='k', alpha=1) # 畫出K線圖 ax1.tick_params('x', bottom=False, labelbottom=False) # 子圖一不顯示X軸標籤 ax1.set_axisbelow(True) # 設定格線在最底圖層 ax1.grid(True) # 畫格線 # ax2 = plt.subplot2grid((3, 1), (2, 0), rowspan=1, colspan=1, sharex=ax1) # 佔全圖1/3的子圖二,設定X軸座標與子圖一相同 mpf.volume_overlay(ax2, df['open'], df['close'], df['amount'] / 1000, colorup='b', colordown='b', width=0.6, alpha=1) # 畫出成交量 ax2.set_axisbelow(True) # 設定格線在最底圖層 ax2.grid(True) # 畫格線 plt.gcf().autofmt_xdate() # 斜放X軸標籤 self.__canvas.draw() # mpf.candlestick2_ochl(axes, price_open, price_close, price_high, price_low, colorup='r', colordown='g') # # axes.set_xlabel('日期') # axes.set_ylabel('价格') # axes.set_xlim(0, len(df['trade_date'])) # axes.set_xticks(range(0, len(df['trade_date']), 15)) # # time_serial = pd.to_datetime(df['trade_date'], format="%Y/%m/%d") # axes.set_xticklabels([time_serial[x] for x in axes.get_xticks()]) # 标签设置为日期 # # # X-轴每个ticker标签都向右倾斜45度 # for label in axes.xaxis.get_ticklabels(): # label.set_rotation(45) # label.set_fontsize(10) # 设置标签字体 # plt.show() self.__canvas.draw()
def DrawCandleChart(self): count = self.CommTR.dynamicCall("GetMultiRowCount()") value = {} rowvalue = [] for i in range(0, 6): for j in range(0, count): x = self.CommTR.dynamicCall("GetMultiData(int, QString)", j, i) rowvalue.append(x) value[i] = rowvalue rowvalue = [] value[0] = pd.to_datetime(value[0]) daeshin = { 'open': value[2], 'high': value[3], 'low': value[4], 'close': value[5] } daeshin_day = DataFrame(daeshin, columns=['open', 'high', 'low', 'close'], index=value[0]) reversed_daeshin_day = daeshin_day[::-1] fig = plt.figure(figsize=(12, 8)) ax = fig.add_subplot(111) namelist = [] daylist = [] #for day in daeshin_day.index: # namelist.append(day.strftime('%d')) #daylist = range(len(daeshin_day)) for i, day in enumerate(reversed_daeshin_day.index): if day.dayofweek == 0: daylist.append(i) namelist.append(day.strftime('%m/%d(Mon)')) ax.xaxis.set_major_locator(ticker.FixedLocator(daylist)) ax.xaxis.set_major_formatter(ticker.FixedFormatter(namelist)) def passDtype(n): return np.array(n, dtype=float) matfin.candlestick2_ohlc(ax, passDtype(reversed_daeshin_day['open']), passDtype(reversed_daeshin_day['high']), passDtype(reversed_daeshin_day['low']), passDtype(reversed_daeshin_day['close']), width=0.5, colorup='r', colordown='b') plt.grid() plt.show()
def _candle(ohlc, ma=None, volume=False, figsize=(10, 8)): # plt.rcParams['font.family'] = 'Times New Roman' plt.rcParams['font.size'] = 20 fig, ax = plt.subplots(figsize=figsize) # candle plot width = 0.8 mpf.candlestick2_ohlc(ax, opens=ohlc.open.values, closes=ohlc.close.values, lows=ohlc.low.values, highs=ohlc.high.values, width=width, colorup='r', colordown='b') # moving average if ma is not None and type(ma) == list: for _ma in ma: sma = ohlc.close.rolling(_ma).mean() v_stack = np.vstack((range(len(sma)), sma.values.T)).T ax.plot(v_stack[:, 0], v_stack[:, 1], label="ma(%i)" % _ma) plt.legend(loc="upper left") # volume if volume: ax2 = ax.twinx() # connect two axis ax2.plot(ohlc.volume.values, label="volume", marker=".", linestyle=":", color="black") plt.legend(loc="upper right") # x axis -> time xdate = ohlc.index ax.xaxis.set_major_locator(ticker.MaxNLocator(10)) ax.grid(True) def mydate(x, pos): try: return xdate[int(x)] except IndexError: return '' ax.xaxis.set_major_formatter(ticker.FuncFormatter(mydate)) ax.format_xdata = mdates.DateFormatter('%Y-%m-%d') fig.autofmt_xdate() fig.tight_layout() return fig, ax
import pandas_datareader.data as web import datetime import matplotlib.pyplot as plt import mpl_finance start = datetime.datetime(2016, 3, 1) end = datetime.datetime(2016, 3, 31) skhynix = web.DataReader("000660.KS", "yahoo", start, end) #print(skhynix) fig = plt.figure(figsize=(12, 8)) ax = fig.add_subplot(111) mpl_finance.candlestick2_ohlc(ax, skhynix['Open'], skhynix['High'], skhynix['Low'], skhynix['Close'], width=0.5, colorup='r', colordown='b') plt.show()