def plot_candle_daily(ax, ts_code, name, last_date, misc): daily = main_session.query(models.DailyPro).filter(models.DailyPro.ts_code == ts_code, models.DailyPro.trade_date <= last_date).order_by( models.DailyPro.trade_date.desc()).limit(sampling_count).all() df = DataFrame() for i, item in enumerate(daily[300::-1]): df.loc[i, 'date'] = str(item.trade_date) df.loc[i, 'open'] = item.open df.loc[i, 'close'] = item.close df.loc[i, 'high'] = item.high df.loc[i, 'low'] = item.low sma_5 = talib.SMA(np.array(df['close']), 5) sma_10 = talib.SMA(np.array(df['close']), 10) sma_20 = talib.SMA(np.array(df['close']), 20) ax.set_xticks(range(0, len(df['date']), 20)) ax.set_xticklabels(df['date'][::20]) ax.plot(sma_5, linewidth=1, label='ma5') ax.plot(sma_10, linewidth=1, label='ma10') ax.plot(sma_20, linewidth=1, label='ma20') mpf.candlestick2_ochl(ax, df['open'], df['close'], df['high'], df['low'], width=0.5, colorup='red', colordown='green', alpha=0.5) # plt.grid() print('plot {ts_code} {name}'.format(ts_code=ts_code, name=name))
def plot_OHLC(df, name): df_m = df['volprice'] / df['vol'] sma_5 = df_m.rolling(window=5).mean() sma_10 = df_m.rolling(window=10).mean() sma_20 = df_m.rolling(window=20).mean() x = round(len(df['date']) / 14) fig = plt.figure(figsize=(24, 12)) ax = fig.add_subplot(1, 1, 1) ax.set_xticks(range(0, len(df['date']), x)) ax.set_xticklabels(df['date'][::x]) ax.plot(sma_5, label='5MA', color='yellow') ax.plot(sma_10, label='10MA', color='blue') ax.plot(sma_20, label='20MA', color='purple') ax.legend(loc='upper left') mpf.candlestick2_ochl(ax, df['open'], df['close'], df['high'], df['low'], width=0.5, colorup='r', colordown='green', alpha=0.6) ax.set_title(name) plt.grid() plt.show()
def save_candlestick_with_volume_img(df, save_filepath): fig, ax = plt.subplots(nrows=2, ncols=1, figsize=(10, 10), sharex=True, gridspec_kw={'height_ratios': [4, 1]}) mpl_finance.candlestick2_ochl(ax[0], df['open'], df['close'], df['high'], df['low'], width=1, colorup='r', colordown='g') ax[0].grid(False) ax[0].set_xticklabels([]) ax[0].set_yticklabels([]) ax[0].xaxis.set_visible(False) ax[0].yaxis.set_visible(False) ax[0].axis('off') mpl_finance.volume_overlay(ax[1], df['open'], df['close'], df['volume'], colorup='r', colordown='g', width=1) ax[1].grid(False) ax[1].set_xticklabels([]) ax[1].set_yticklabels([]) ax[1].xaxis.set_visible(False) ax[1].yaxis.set_visible(False) ax[1].axis('off') plt.savefig(save_filepath) plt.close("all")
def plotKLine(open, close, high, low, tech): fig = plt.figure(figsize=(30, 15)) y = len(close) date = np.linspace(0, y, y) candleAr = [] ax1 = plt.subplot2grid((10, 4), (0, 0), rowspan=5, colspan=4) candlestick2_ochl(ax1, open, close, high, low, width=1, colorup='r', colordown='g', alpha=0.75) ax2 = plt.subplot2grid((10, 4), (5, 0), rowspan=4, colspan=4, sharex=ax1) if 'ATR' in tech.keys(): ax2.plot(date, tech['ATR'], '-b') if 'ad_ATR' in tech.keys(): ax2.plot(date, tech['ad_ATR'], '-r') if 'my_ATR' in tech.keys(): ax2.plot(date, tech['my_ATR'], '-m') if 'short_ATR' in tech.keys(): ax2.plot(date, tech_1['short_ATR'], '-b') if 'long_ATR' in tech.keys(): ax2.plot(date, tech_1['long_ATR'], '-r') if 'close' in tech.keys(): ax2.plot(date, tech_2['close'], '-b') if 'upper' in tech.keys(): ax2.plot(date, tech_2['upper'], '-r') if 'lower' in tech.keys(): ax2.plot(date, tech_2['lower'], '-r')
def plot(df1,ticker): df1.set_index(df1['Date'],inplace=True) #first plot is Heikin-Ashi candlestick #use candlestick function and set Heikin-Ashi O,C,H,L ax1=plt.subplot2grid((200,1), (0,0), rowspan=120,ylabel='HA price') mpf.candlestick2_ochl(ax1, df1['HA open'], df1['HA close'], df1['HA high'], df1['HA low'], width=1, colorup='g', colordown='r') plt.grid(True) plt.xticks([]) plt.title('Heikin-Ashi') #the second plot is the actual price with long/short positions as up/down arrows ax2=plt.subplot2grid((200,1), (120,0), rowspan=80,ylabel='price',xlabel='') df1['Close'].plot(ax=ax2,label=ticker) #long/short positions are attached to the real close price of the stock #set the line width to zero #thats why we only observe markers ax2.plot(df1.loc[df1['signals']==1].index,df1['Close'][df1['signals']==1],marker='^',lw=0,c='g',label='long') ax2.plot(df1.loc[df1['signals']<0].index,df1['Close'][df1['signals']<0],marker='v',lw=0,c='r',label='short') plt.grid(True) plt.legend(loc='best') plt.show()
def plot(klines, symbol, fig=None): style.use('fivethirtyeight') _, opens, highs, lows, closes, volumes = klines.columns # Create figure if fig is None: fig = plt.figure() else: fig.clear() ax1 = fig.add_subplot(111) candlestick2_ochl(ax1, opens, closes, highs, lows, width=1, colorup='g') ax1.set_ylim(lows.min() - lows.min() / 50) # Add a seconds axis for the volume overlay ax2 = ax1.twinx() ax2.set_ylim(0, 5 * volumes.max()) ax2.grid(False) add_volume(ax2, opens, closes, volumes) #add_BBands(ax1, closes) plt.title(symbol) fig.savefig(r'C:\graphs\{}.png'.format(symbol), format='png', dpi=400) plt.close()
def smooth_demo(): data2 = QA.QA_fetch_crypto_asset_day_adv(['huobi'], symbol=['btcusdt'], start='2017-10-01', end='2020-06-30 23:59:59') xn = data2.close.values ma5 = talib.MA(data2.close.values, 10) hma5 = TA_HMA(data2.close.values, 10) kama5 = TA_KAMA(data2.close.values, 10) window_size, poly_order = 5, 1 yy_sg = savgol_filter(xn, window_size, poly_order) plt.figure(figsize = (22,9)) ax1 = plt.subplot(111) mpf.candlestick2_ochl(ax1, data2.data.open.values, data2.data.close.values, data2.data.high.values, data2.data.low.values, width=0.6, colorup='r', colordown='green', alpha=0.5) #ax1.title("The smoothing windows") #plt.plot(xn, lw=1, alpha=0.8) ax1.plot(hma5, lw=2, linestyle="--", color='darkcyan', alpha=0.6) ax1.plot(yy_sg, lw=1, color='darkcyan', alpha=0.8) ax1.plot(ma5, lw=1, color='orange', alpha=0.8) ax1.plot(kama5, lw=1, color='lightskyblue', alpha=0.8) l=['Hull Moving Average', 'savgol_filter', 'talib.MA10', 'KAMA10'] ax1.legend(l) plt.title("Smoothing a MA10 line") plt.show()
def draw(): # quotes = raw_data_helper.get_data("tx5_data/202002/20200212.txt") start = datetime.datetime(2018, 4, 1) # df_2330 = pdr.DataReader('2330.TW', 'yahoo', start=start) # print(df_2330['Close']) # df_2330.index = df_2330.index.format(formatter=lambda x: x.strftime('%Y-%m-%d')) fig = plt.figure(figsize=(24, 8)) # print(df_2330) # print(df_2330['Open']) ax = fig.add_subplot(1, 1, 1) # ax.set_xticks(range(0, len(df_2330.index), 10)) # ax.set_xticklabels(df_2330.index[::10]) ax.set_xticks(range(0, len(quotes["time"]), 10)) ax.set_xticklabels(quotes["time"][::10]) # mpf.candlestick2_ochl(ax, df_2330['Open'], df_2330['Close'], df_2330['High'], # df_2330['Low'], width=0.6, colorup='r', colordown='g', alpha=0.75) mpf.candlestick2_ochl(ax, quotes['Open'], quotes['Close'], quotes['High'], quotes['Low'], width=K_BAR_WIDTH, colorup='r', colordown='g', alpha=0.75) cursor = Cursor(ax, useblit=True, color='blue', linewidth=0.6) # cursor = Cursor(ax) # fig.canvas.mpl_connect('motion_notify_event', mouse_move) fig.align_labels() plt.xticks(rotation=0) ax.format_coord = format_coord plt.show()
def draw_k_line(df_Stock): sma_5 = talib.SMA(np.array(df_Stock['close']), 5) sma_10 = talib.SMA(np.array(df_Stock['close']), 10) sma_30 = talib.SMA(np.array(df_Stock['close']), 30) fig = plt.figure(figsize=(24, 20)) ax = fig.add_axes([0, 0.3, 1, 0.4]) ax.set_xticks(range(0, len(df_Stock.index), 1)) ax.set_xticklabels(df_Stock.index[::]) mpf.candlestick2_ochl(ax, df_Stock['open'], df_Stock['close'], df_Stock['high'], df_Stock['low'], width=0.6, colorup='r', colordown='g', alpha=0.75) plt.rcParams['font.sans-serif'] = ['Microsoft JhengHei'] ax.plot(sma_5, label='5日均線') ax.plot(sma_10, label='10日均線') ax.plot(sma_30, label='30日均線') plt.xticks(rotation=90) plt.grid() ax.legend() plt.savefig('static/media/k_line.png')
def plot(data, keys, ilabel, has_subplot=True): fig = plt.figure(figsize=(9, 5)) ax = fig.add_subplot(2, 1, 1) ax.set_xticklabels([]) plt.title('close price - %s chart' % ilabel) plt.grid(True) candlestick2_ochl(ax, data['open'], data['close'], data['high'], data['low'], width=1.0, colorup='r', colordown='g') ax.set_ylabel(ilabel) ax.set_xticks(range(0, len(data.index), 10)) if has_subplot: bx = fig.add_subplot(2, 1, 2) plt.ylabel('%s values' % ilabel) i = 0 for key in keys: plt.plot(data[key], COLORS[i], lw=0.75, linestyle='-', label=key) i += 1 plt.legend(loc=2, prop={'size': 9.5}) plt.grid(True) fig.autofmt_xdate() plt.show()
def plot_candle_month(ax, ts_code, name, last_date, misc): monthly = main_session.query(models.MonthlyPro).filter(models.MonthlyPro.ts_code == ts_code, models.MonthlyPro.trade_date <= last_date).order_by( models.MonthlyPro.trade_date.desc()).limit(sampling_count).all() if monthly: df = DataFrame() for i, item in enumerate(monthly[300::-1]): df.loc[i, 'date'] = str(item.trade_date) df.loc[i, 'open'] = item.open df.loc[i, 'close'] = item.close df.loc[i, 'high'] = item.high df.loc[i, 'low'] = item.low sma_5 = talib.SMA(np.array(df['close']), 5) sma_10 = talib.SMA(np.array(df['close']), 10) sma_20 = talib.SMA(np.array(df['close']), 20) ax.set_xticks(range(0, len(df['date']), 20)) ax.set_xticklabels(df['date'][::20]) ax.plot(sma_5, linewidth=1, label='ma5') ax.plot(sma_10, linewidth=1, label='ma10') ax.plot(sma_20, linewidth=1, label='ma20') mpf.candlestick2_ochl(ax, df['open'], df['close'], df['high'], df['low'], width=0.5, colorup='red', colordown='green', alpha=0.5) plt.title('{index} {ts_code} {name} circ_mv:{circ_mv}亿 holders:{holders_count} last_chg:{last_chg} min_max:{min_max_gap}'.format(index=int(misc['index']), ts_code=ts_code, name=name, circ_mv=int(misc[COL_CIRC_MV]), holders_count=int(misc[COL_HOLDERS_COUNT]), last_chg=misc[COL_LAST_CHG], min_max_gap=misc[COL_MIN_MAX_GAP]), fontproperties='Heiti TC') # plt.grid() print('plot {ts_code} {name}'.format(ts_code=ts_code, name=name))
def buildImage(directory, dataset, filename, label, csvfile): # Read each CSV window file print("Building image for {}".format(filename)) #print("directory = {}, dataset = {}, filename = {} , label = {}, csvfile = {} ".format(directory, dataset, filename, label, csvfile)) fname = filename.split('/')[4] df = pd.read_csv(filename, parse_dates=True, index_col=0) df.fillna(0) df.reset_index(inplace=True) # Plot Chart plt.style.use('dark_background') fig = plt.figure(figsize = (dimension / dpi, dimension / dpi ), dpi = dpi) chart = fig.add_subplot(1,1,1) candlestick2_ochl(chart, df['Open'], df['Close'], df['High'], df['Low'], width=1, colorup='#77d879', colordown='#db3f3f') chart.grid(False) chart.set_xticklabels([]) chart.set_yticklabels([]) chart.yaxis.set_visible(False) chart.xaxis.set_visible(False) chart.axis('off') # Save chart image imgfile = '{}/{}/{}/{}.png'.format(directory, dataset, label, fname) print("Image File: {}".format(imgfile)) fig.savefig(imgfile, pad_inches=0, transparent=False) plt.close(fig)
def create_EMAplot(data, ticker): formatter = mdates.DateFormatter("%Y-%m") ax.xaxis.set_major_formatter(formatter) locator = mdates.YearLocator() ax.xaxis.set_major_locator(locator) #ax.xaxis.set_minor_locator(mdates.MonthLocator()) font={'weight':'normal', 'size':12} ax4.set_title('Candlestick', fontdict=font) #To make the chart more readable, get one month of data x_vals=data.index mpf.candlestick2_ochl(ax4, data["open"], data["close"],data["high"], data["low"], width=.5, colorup='k', colordown='r', alpha=0.75) ax.xaxis.set_major_formatter(formatter) ax4.set_ylabel('Price (USD)') ax4.legend() ax5.bar(x_vals, data['volume']) ax5.xaxis.set_major_formatter(mdates.DateFormatter("%Y-%m")) ax5_locator = mdates.MonthLocator() ax5.xaxis.set_major_locator(ax5_locator) ax5.set_ylabel('Price (USD)') ax5.set_xlabel('Date') font={'weight':'normal', 'size':12} ax5.set_title("Volume (x10,000,000)", fontdict=font) ax5.legend()
def plot(df1, ticker): df1.set_index(df1['Date'], inplace=True) ax1 = plt.subplot2grid((200, 1), (0, 0), rowspan=120, ylabel='HA price') mpf.candlestick2_ochl(ax1, df1['HA open'], df1['HA close'], df1['HA high'], df1['HA low'], width=1, colorup='g', colordown='r') plt.grid(True) plt.xticks([]) plt.title('Heikin-Ashi') ax2 = plt.subplot2grid((200, 1), (120, 0), rowspan=80, ylabel='price', xlabel='') df1['Close'].plot(ax=ax2, label=ticker) ax2.plot(df1.loc[df1['signals'] == 1].index, df1['Close'][df1['signals'] == 1], marker='^', lw=0, c='g', label='long') ax2.plot(df1.loc[df1['signals'] < 0].index, df1['Close'][df1['signals'] < 0], marker='v', lw=0, c='r', label='short') plt.grid(True) plt.legend(loc='best') plt.show()
def draw_cci3(self,code,ktype): kk=gu_save('') hh=gu_zb(0) name=kk.get_name(code) print(name+code) #取4个类型的df df=kk.get_k_from_api(code,ktype) #取4个类型的CCi if df.empty: return 0 cci=hh.cci(df)[-self.total:] df=df[-self.total:] up,dw=hh.cci_ana_dd2(cci) cciii=[] for i in range(0,self.total): if i in dw: cciii.append(cci[i]) else: cciii.append(0) #画出最后3条线 fig, ax = plt.subplots(2, 1, figsize=(16,8)) ax[0].set_title(name+code+'--'+ktype,fontproperties = 'SimHei',fontsize = 20) mpf.candlestick2_ochl(ax=ax[0],opens=df["open"].values.tolist(), closes=df["close"].values, highs=df["high"].values, lows=df["low"].values,width=0.7,colorup='r',colordown='g',alpha=0.7) ax[1].axhline(y=100, color='b', linestyle=':') ax[1].axhline(y=-100, color='b', linestyle=':') ax[1].plot(cci,'r') ax[1].plot(cciii,'b') plt.show() return 0
def test3(self): df1, name = self._getk() #cci处理 cci_ht, cci_qrfj = self.cci_cl(df1) df = df1[-self.total:] #顶点坐标 up_li2, dw_li2 = self.cci_draw_line(cci_ht, cci_qrfj) print(up_li2) #return 0 fig = plt.figure() X = 2 Y = 1 ax5 = fig.add_subplot(X, Y, 1) ax2 = fig.add_subplot(X, Y, 2) #画K线 mpf.candlestick2_ochl(ax=ax5, opens=df["open"].values.tolist(), closes=df["close"].values, highs=df["high"].values, lows=df["low"].values, width=0.7, colorup='r', colordown='g', alpha=0.7) #画cci指标 ax2.plot(cci_ht, 'r') #叠加文字 #c_text=[] '''for i in range(3,self.total): if cci_ht[i]<cci_ht[i-1] and cci_ht[i-1]>cci_ht[i-2] and cci_ht[i]>90: c_text.append([i,cci_ht[i],'p']) for x in c_text: plt.text(x[0],x[1],x[2],size = 5,bbox = dict(facecolor = "r", alpha = 0.2)) ''' iii = self.total - 1 while cci_qrfj[iii] == 100: iii -= 1 x = np.linspace(0, self.total, 10) print(up_li2) for u in up_li2[-4:]: y1 = u[1] y2 = u[3] x1 = u[0] x2 = u[2] k = (y2 - y1) / (x2 - x1) if k > 0: continue b = y2 - k * x2 y = k * x + b plt.plot(x, y, '-.y') #画两点线 plt.axhline(y=100, color='b', linestyle=':') plt.axhline(y=-100, color='b', linestyle=':') plt.show() return 0
def ohlc2cs(fname, seq_len, dataset_type, dimension, use_volume): # python preprocess.py -m ohlc2cs -l 20 -i stockdatas/EWT_testing.csv -t testing print("Converting olhc to candlestick") symbol = fname.split('_')[0] symbol = symbol.split('/')[1] print(symbol) path = "{}".format(os.getcwd()) # print(path) if not os.path.exists("{}/dataset/{}_{}/{}/{}".format(path, seq_len, dimension, symbol, dataset_type)): os.makedirs("{}/dataset/{}_{}/{}/{}".format(path, seq_len, dimension, symbol, dataset_type)) df = pd.read_csv(fname, parse_dates=True, index_col=0) df.fillna(0) plt.style.use('dark_background') df.reset_index(inplace=True) df['Date'] = df['Date'].map(mdates.date2num) for i in range(0, len(df)): # ohlc+volume c = df.ix[i:i + int(seq_len) - 1, :] if len(c) == int(seq_len): my_dpi = 96 fig = plt.figure(figsize=(dimension / my_dpi, dimension / my_dpi), dpi=my_dpi) ax1 = fig.add_subplot(1, 1, 1) candlestick2_ochl(ax1, c['Open'], c['Close'], c['High'], c['Low'], width=1, colorup='#77d879', colordown='#db3f3f') ax1.grid(False) ax1.set_xticklabels([]) ax1.set_yticklabels([]) ax1.xaxis.set_visible(False) ax1.yaxis.set_visible(False) ax1.axis('off') # create the second axis for the volume bar-plot # Add a seconds axis for the volume overlay # if use_volume: # ax2 = ax1.twinx() # # Plot the volume overlay # bc = volume_overlay(ax2, c['Open'], c['Close'], c['Volume'], # colorup='#77d879', colordown='#db3f3f', alpha=0.5, width=1) # ax2.add_collection(bc) # ax2.grid(False) # ax2.set_xticklabels([]) # ax2.set_yticklabels([]) # ax2.xaxis.set_visible(False) # ax2.yaxis.set_visible(False) # ax2.axis('off') pngfile = 'dataset/{}_{}/{}/{}/{}-{}.png'.format( seq_len, dimension, symbol, dataset_type, fname[11:-4], i) fig.savefig(pngfile, pad_inches=0, transparent=False) plt.close(fig) # normal length - end print("Converting olhc to candlestik finished.")
def plotStock(data, ax): #fig = plt.figure(figsize=(15, 10)) data.sort_index() data.reset_index() data.dropna() data.index.name = 'date' data = data.loc[len(data.index) - 200:, :] #data['date'] = mdates.date2num(pd.to_datetime(data['date'])) #data['date'] = mdates.date2num(data['date'].astype(dt.date)) data = data.reindex( columns=['date', 'open', 'high', 'low', 'close', 'EMA_5', 'EMA_10']) #fig = plt.figure() #fig = plt.figure(facecolor='#07000d', figsize=(15, 10)) ax = plt.subplot2grid((6, 4), (1, 0), rowspan=4, colspan=4, facecolor='k') candlestick2_ochl(ax, data['open'], data['close'], data['high'], data['low'], width=0.5, colorup='r', colordown='green', alpha=0.6) ax.set_xticklabels(data['date'][::10]) ax.plot(data['EMA_5'].values, label='5 日均线') ax.plot(data['EMA_10'].values, label='10 日均线') #ax1.set_xticks(range(0,len(data['date']),10)) #candlestick_ochl(ax1, data.values,width=0.5, colorup='r', colordown='b', alpha=0.6) #ax.plot(data['date'].values, data['EMA_5'].values, '#e1edf9', label='5 日均线',lw=1.5) #ax.plot(data['date'].values, data['EMA_10'].values, '#4ee6fd', label='10 日均线',lw=1.5) ax.grid(True, color='w') #ax.xaxis.set_major_locator(mticker.MaxNLocator(10)) #ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y%m%d')) #ax.yaxis.set_major_locator(mticker.MaxNLocator(prune='upper')) ax.spines['bottom'].set_color("#5998ff") ax.spines['top'].set_color("#5998ff") ax.spines['left'].set_color("#5998ff") ax.spines['right'].set_color("#5998ff") ax.tick_params(axis='y', colors='w') ax.tick_params(axis='x', colors='w') #ax.set_xlabel("Date") #ax.xaxis.label.set_color("r") ax.set_ylabel("stock price and volume") ax.yaxis.label.set_color("r") #plt.setp(ax0.get_xticklabels(), visible=False) #plt.setp(ax1.get_xticklabels(), visible=False) plt.show()
def gen_plot_1(dataframe, startidx, endidx): ##### # plot just price ##### endidx = endidx + 1 #dataframe is a pandas dataframe with open, high, low, close and volume for each time interval open = dataframe['Open'][startidx:endidx].tolist() high = dataframe['High'][startidx:endidx].tolist() low = dataframe['Low'][startidx:endidx].tolist() close = dataframe['Close'][startidx:endidx].tolist() volume = dataframe['Adj Vol'][startidx:endidx].tolist() time = dataframe['Time'][startidx:endidx].tolist() # date=dataframe['Date'][startidx:endidx].tolist() open.reverse() high.reverse() low.reverse() close.reverse() volume.reverse() time.reverse() # date.reverse() num_ticks = 6 def mydate(x, pos): try: return time[int(x)] except IndexError: return '' ##### # plot just price ##### fig = plt.figure() ax = plt.subplot() candlestick2_ochl(ax, open, close, high, low, width=0.5, colorup='b', colordown='r', alpha=0.75) ax.xaxis.set_major_locator(ticker.MaxNLocator(num_ticks)) ax.xaxis.set_major_formatter(ticker.FuncFormatter(mydate)) fig.autofmt_xdate() fig.tight_layout() ax.set_ylabel('Price') ax.set_xlabel('Date/Time') ax.set_xlim(-1.0, len(open) - 1.0) ax.xaxis.set_major_locator(ticker.MaxNLocator(num_ticks)) ax.xaxis.set_major_formatter(ticker.FuncFormatter(mydate)) ax.grid() plt.show()
def show_candle_stick(self, xstep=None, ystep=None): # 创建图像和子图 fig = plt.figure(figsize=(20, 13)) ax = fig.add_axes([0.02, 0.4, 1, 0.6]) ax2 = fig.add_axes([0.02, 0.05, 1, 0.35]) # k 线 mpf.candlestick2_ochl(ax, self.data['open'], self.data['close'], self.data['high'], self.data['low'], width=0.5, colorup='r', colordown='g', alpha=0.8) # 设置横纵轴坐标 # ax.set_xticks(range(0, len(self.data.index), 10)) ax.set_yticks( np.arange(int(self.min_price * 0.9), int(self.max_price * 1.1), 2)) # ax.set_ylabel('price') ax2.set_yticks(np.arange(0, int(self.max_vol * 1.1), 50000)) # ax2.set_ylabel('vol') ax.plot(self.sma_10, label='10 日均线') ax.plot(self.sma_30, label='30 日均线') # 创建图例 ax.legend(loc='upper center', fontsize=14) # 网格 ax.grid(True) # 成交量 mpf.volume_overlay(ax2, self.data['open'], self.data['close'], self.data['volume'], colorup='r', colordown='g', width=0.5, alpha=0.8) # ax2.set_xticks(range(0, len(self.data.index), 10)) # ax2.set_xticklabels(self.data.index.strftime('%Y-%m-%d'), # fontdict = {'fontsize':14}, # rotation=30) ax2.set_xticks(np.arange(0, len(self.data.index), xstep)) xlabels = list( self.data.index.strftime('%Y-%m-%d'))[0:len(self.data.index):xstep] ax2.set_xticklabels(xlabels, fontdict={'fontsize': 15}, rotation=45) print(xlabels) ax2.grid(True) plt.show()
def volumn(): fig = plt.figure(figsize=(8, 6), dpi=100, facecolor="white") # 创建fig对象 gs = gridspec.GridSpec(2, 1, left=0.05, bottom=0.15, right=0.96, top=0.96, wspace=None, hspace=0, height_ratios=[3.5, 1]) numt = np.arange(0, len(df_stockload.index)) graph_KAV = fig.add_subplot(gs[0, :]) graph_KAV.set_title(u"600797 浙大网新-日K线") graph_KAV.set_xlabel(u"日期") graph_KAV.set_ylabel(u"价格") graph_KAV.set_xlim(0, len(df_stockload.index)) # 设置一下x轴的范围 graph_KAV.set_xticks(range(0, len(df_stockload.index), 15)) # X轴刻度设定,每15天标一个日期 graph_KAV.grid(True, color='k') graph_KAV.set_xticklabels( [df_stockload.index.strftime('%Y-%m-%d')[index] for index in graph_KAV.get_xticks()]) # 标签设置为日期 # 绘制K线走势 mpf.candlestick2_ochl(graph_KAV, df_stockload.Open, df_stockload.Close, df_stockload.High, df_stockload.Low, width=0.5, colorup='r', colordown='g') graph_VOL = fig.add_subplot(gs[1, :]) graph_VOL.bar(numt, df_stockload.Volume, color=['g' if df_stockload.Open[x] > df_stockload.Close[x] else 'r' for x in range(0, len(df_stockload.index))]) graph_VOL.set_ylabel(u"成交量") graph_VOL.set_xlabel(u"日期") graph_VOL.set_xlim(0, len(df_stockload.index)) # 设置一下X轴的范围 graph_VOL.set_xticks(range(0, len(df_stockload.index), 15)) # X轴刻度设定,每15天标一个日期 graph_VOL.set_xticklabels( [df_stockload.index.strftime('%Y-%m-%d')[index] for index in graph_VOL.get_xticks()]) # 标签设置为日期 # 将日K线X轴labels隐藏 for label in graph_KAV.xaxis.get_ticklabels(): label.set_visible(False) # X轴每个ticker标签都向右倾斜45度 for label in graph_VOL.xaxis.get_ticklabels(): label.set_rotation(45) label.set_fontsize(10) #设置标签字号 plt.show()
def draw_kchart(stockNumber): stock_name = get_stock_name(stockNumber) if stock_name == "no": return "股票代碼錯誤!" end = datetime.datetime.now() date = end.strftime("%Y%m%d") year = str(int(date[0:4]) - 1) month = date[4:6] stock = pdr.DataReader(stockNumber + '.TW', 'yahoo', start= year+"-"+month,end=end) stock.index = stock.index.format(formatter=lambda x: x.strftime('%Y-%m-%d')) #KD sma_10 = talib.SMA(np.array(stock['Close']), 10) sma_30 = talib.SMA(np.array(stock['Close']), 30) stock['k'], stock['d'] = talib.STOCH(stock['High'], stock['Low'], stock['Close']) stock['k'].fillna(value=0, inplace=True) stock['d'].fillna(value=0, inplace=True) sma_5 = talib.SMA(np.array(stock['Close']), 5) sma_20 = talib.SMA(np.array(stock['Close']), 20) sma_60 = talib.SMA(np.array(stock['Close']), 60) fig = plt.figure(figsize=(20, 10))#,facecolor='black') fig.suptitle(stock_name.strip('加到投資組合'),fontsize="x-large", FontProperties=chinese_title) ax = fig.add_axes([0.1,0.5,0.75,0.4]) plt.title("開盤價:"+str(round(stock['Open'][-1], 2))+" 收盤價:"+str(round(stock['Close'][-1], 2))+"\n最高價:"+str(round(stock['High'][-1] ,2))+" 最低價:"+str(round(stock['Low'][-1], 2)),fontsize="25",fontweight='bold',bbox=dict(facecolor='yellow',edgecolor='red',alpha=0.65),loc='left', FontProperties=chinese_subtitle) plt.title("更新日期:"+stock.index[-1],fontsize="20",fontweight='bold',loc="right", FontProperties=chinese_subtitle) plt.grid(True,linestyle="--",color='gray',linewidth='0.5',axis='both') ax2 = fig.add_axes([0.1,0.3,0.75,0.20]) plt.grid(True,linestyle="--",color='gray',linewidth='0.5',axis='both') ax3 = fig.add_axes([0.1,0.03,0.75,0.20]) mpf.candlestick2_ochl(ax, stock['Open'], stock['Close'], stock['High'], stock['Low'], width=0.6, colorup='r', colordown='g', alpha=0.75) ax.plot(sma_5, label='5日均線') ax.plot(sma_10, label='10日均線') ax.plot(sma_20, label='20日均線') ax.plot(sma_60, label='60日均線') ax2.plot(stock['k'], label='K值') ax2.plot(stock['d'], label='D值') ax2.set_xticks(range(0, len(stock.index),10)) ax2.set_xticklabels(stock.index[::10],fontsize="10", rotation=25) mpf.volume_overlay(ax3, stock['Open'], stock['Close'], stock['Volume'], colorup='r', colordown='g', width=0.5, alpha=0.8) ax3.set_xticks(range(0, len(stock.index),10)) ax3.set_xticklabels(stock.index[::5],fontsize="10", rotation=45) ax.legend(prop=chinese_font, fontsize=20); ax2.legend(prop=chinese_font); plt.grid(True,linestyle="--",color='gray',linewidth='0.5',axis='both') plt.gcf() plt.savefig("Kchrat.png",bbox_inches='tight',dpi=300,pad_inches=0.0) plt.show() plt.close() return Imgur.showImgur("Kchrat")
def show_K_xian_tu(data_list): ax1 = plt.subplot2grid((9, 10), (0, 0), rowspan=7, colspan=10) ax2 = plt.subplot2grid((9, 10), (7, 0), rowspan=2, colspan=10, sharex=ax1) data_time = data_list.index print(data_time) data_list = data_list.reset_index() data_list['date'] = data_list['date'].map(mdate.date2num) # 把日期形式改变成数字形式方便matplotlib读取 mpf.candlestick2_ochl(ax=ax1, opens=data_list['open'], closes=data_list['close'], highs=data_list['high'], lows=data_list['low'], width=1,colorup='red',colordown='green') ax2.bar(data_list.index, data_list['volume']) plt.xticks(data_list.index[::200],data_time[::200]) plt.show()
def dr_cci2(szb): #详细分析 co=cciorder(szb) #取4个类型的df df=co.df if df.empty:return 0 cci=co.cci ln=len(cci) total=250 if ln<total: total=ln PLUS_DI,MINUS_DI,ADX,ADXR=co.stockzb.dmi() bixl_li,bicz_li=co.bias_1() vok=co.vol1() vo=vok[-total:] bixl=bixl_li[-total:] bicz=bicz_li[-total:] df=df[-total:] cci=cci[-total:] MINUS_DI=MINUS_DI[-total:] PLUS_DI=PLUS_DI[-total:] ADX=ADX[-total:] ADXR=ADXR[-total:] #df=df[-self.total:] #4个类型的顶点 #画出最后3条线 name=co.getname() code=co.getcode() fig, ax = plt.subplots(4, 1, figsize=(16,8)) ax[0].set_title(name+code+'--',fontproperties = 'SimHei',fontsize = 20) ax[1].plot(cci,'r') ax[2].plot(ADX,'r') ax[2].plot(PLUS_DI,'y') ax[2].plot(MINUS_DI,'b') ax[2].plot(ADXR,'g') ax[2].axhline(y=80, color='b', linestyle=':') ax[2].axhline(y=50, color='b', linestyle=':') ax[2].axhline(y=20, color='b', linestyle=':') ax[3].plot(vo,'r') #ax[3].plot(bicz,'b') ax[3].axhline(y=0, color='b', linestyle=':') mpf.candlestick2_ochl(ax=ax[0],opens=df["open"].values.tolist(), closes=df["close"].values, highs=df["high"].values, lows=df["low"].values,width=0.7,colorup='r',colordown='g',alpha=0.7) ax[1].axhline(y=100, color='b', linestyle=':') ax[1].axhline(y=-100, color='b', linestyle=':') plt.style.use('ggplot') plt.show() return 1
def test2(self): df1, name = self._getk() index = 619 N = 14 df = df1 #图表格式 X = 3 Y = 1 fig = plt.figure() ax5 = fig.add_subplot(X, Y, 1) ax2 = fig.add_subplot(X, Y, 2) ax3 = fig.add_subplot(X, Y, 3) print(name, df.loc[index, 'date']) '''fig = plt.figure() ax1=fig.add_subplot(5,1,1) ax2=fig.add_subplot(5,1,2) ax3=fig.add_subplot(5,1,3) ax4=fig.add_subplot(5,1,4) ax5=fig.add_subplot(5,1,5) ax1.plot(macd1.values.tolist(),'g',macd2.values.tolist(),'b',macd3.values.tolist(),'y') ax2.plot(up.values.tolist(),'g',mid.values.tolist(),'b',lo.values.tolist(),'y') ax3.plot(cci.values.tolist(),'r')''' #dmi图 MINUS_DI, PLUS_DI, ADX, ADXR = self.dmi(df, index) l = len(ADX.values.tolist()) print(l) zz = [ 1 if ADX.loc[x] < MINUS_DI.loc[x] and ADX.loc[x] < PLUS_DI.loc[x] else 0 for x in range(l) ] print(zz) ax3.plot(zz) ax3.plot(PLUS_DI.values.tolist(), 'y', MINUS_DI.values.tolist(), 'k') #ax2.plot(ADX.values.tolist(),'g',ADXR.values.tolist(),'b',PLUS_DI.values.tolist(),'y',MINUS_DI.values.tolist(),'k') #股价图 mpf.candlestick2_ochl(ax=ax5, opens=df["open"].values, closes=df["close"].values, highs=df["high"].values, lows=df["low"].values, width=0.7, colorup='r', colordown='g', alpha=0.7) plt.show()
def save_candlestick_img_with_volume(df, save_filepath): fig, ax = plt.subplots(nrows=2, ncols=1, figsize=(2.56, 2.56), sharex=True, gridspec_kw={'height_ratios': [2, 1]}) mpl_finance.candlestick2_ochl(ax[0], df['Open'], df['Close'], df['High'], df['Low'], width=1, colorup='r', colordown='g') x_list = [i for i in range(len(df))] ma5_value = numpy.array(df["Open_MA_5"]) ma25_value = numpy.array(df["Open_MA_25"]) ma75_value = numpy.array(df["Open_MA_75"]) ax[0].plot(x_list, ma5_value, markersize=2, color='black') ax[0].plot(x_list, ma25_value, markersize=2, color='y') ax[0].plot(x_list, ma75_value, markersize=2, color='b') ax[0].grid(False) ax[0].set_xticklabels([]) ax[0].set_yticklabels([]) ax[0].xaxis.set_visible(False) ax[0].yaxis.set_visible(False) y_min = min(df["Low"].min(), ma5_value.min(), ma25_value.min(), ma75_value.min()) y_max = max(df["High"].max(), ma5_value.max(), ma25_value.max(), ma75_value.max()) ax[0].set_ylim([y_min, y_max]) ax[0].axis('off') mpl_finance.volume_overlay(ax[1], df['Open'], df['Close'], df['volume'], colorup='black', colordown='black', width=2) ax[1].grid(False) ax[1].set_xticklabels([]) ax[1].set_yticklabels([]) ax[1].xaxis.set_visible(False) ax[1].yaxis.set_visible(False) ax[1].axis('off') plt.savefig(save_filepath) plt.close("all") gc.collect()
def fig_plot(df, stock_id): n = -200 closes = np.array(df['Close'].iloc[n:].tolist()) highs = np.array(df['High'].iloc[n:].tolist()) lows = np.array(df['Low'].iloc[n:].tolist()) opens = np.array(df['Open'].iloc[n:].tolist()) Time = np.array(df['Date'].map(lambda x: str(x)).iloc[n:].tolist()) Vol = np.array(df['Volume'].iloc[n:].tolist()) #use talib pakage to calculate SMA series avg60 = talib.SMA(closes, timeperiod=60) avg120 = talib.SMA(closes, timeperiod=120) avg150 = talib.SMA(closes, timeperiod=150) #create plot figure fig = plt.figure() ax1 = plt.subplot(2,1,1) ax2 = plt.subplot(2,1,2) #x label range ax1.set_xticks(range(0, len(Time), 15)) # ax1.set_xticklabels(Time[::10], rotation=20) mpf.candlestick2_ochl(ax1, opens, closes, highs, lows, width=0.6, colorup='r', colordown='g') #SMA line ax1.plot(avg60, 'g', label='MA60') ax1.plot(avg120, 'k--', label='MA120') ax1.plot(avg150, 'k.', label='MA150') #價量結構 for n in [10, 50]: MaxVolClose = df['Close'].iloc[df['Volume'].iloc[-n:].idxmax()] MaxVolOpen = df['Open'].iloc[df['Volume'].iloc[-n:].idxmax()] if MaxVolClose > MaxVolOpen: ax1.axhline(y=MaxVolOpen, c='r', ls='--', lw=2, label=f'support at {MaxVolOpen}') else: ax1.axhline(y=MaxVolClose, c='b', ls='--', lw=2, label=f'pressure at {MaxVolClose}') #成交量 ax2.bar(Time, Vol ,color='b') ax2.set_xticks(range(0, len(Time), 15)) # ax2.set_xticklabels(Time[::10], rotation=40) #圖片網紋 ax1.grid(True, ls=':', color='k', alpha=0.5) ax2.grid(True, ls=':', color='k', alpha=0.5) #fig setting plt.rc('figure', figsize=(10, 10)) plt.title(stock_id) plt.subplots_adjust(wspace=0, hspace=0) ax1.legend(loc = 'best') fig_path = 'C:/Users/Drey/Pictures/uptrend/'+ stock_id.split('.')[0] + '.png' # fig_path = '/home/drey/stockgallery/media/images/' + stock_id.split('.')[0] + '.png' plt.savefig(fig_path) plt.close()
def stock_Candlestick(userstock): stock=TheConstructor(userstock) fig = plt.figure(figsize=(24, 8)) ax = fig.add_subplot(1, 1, 1) ax.set_xticks(range(0, len(stock.index), 5)) ax.set_xticklabels(stock.index[::5]) plt.xticks(fontsize=10,rotation=90) mpf.candlestick2_ochl(ax, stock['Open'], stock['Close'], stock['High'], stock['Low'], width=0.5, colorup='r', colordown='green', alpha=0.6) plt.title("Candlestick_chart") # 標題設定 plt.grid() plt.savefig('Candlestick_chart.png') #存檔 plt. close() # 殺掉記憶體中的圖片 return Imgur.showImgur('Candlestick_chart')#開始利用imgur幫我們存圖片,以便於等等發送到手機
def draw_subgraph(self, stockdat, numt): """ 绘制K线图 """ # ohlc = list(zip(np.arange(0,len(stockdat.index)),stockdat.Open,stockdat.Close,stockdat.High,stockdat.Low))#使用zip方法生成数据列表 mpf.candlestick2_ochl(self.am, stockdat.Open, stockdat.Close, stockdat.High, stockdat.Low, width=0.5, colorup='r', colordown='g') # 绘制K线走势 ''' 绘制均线 ''' self.am.plot(numt, stockdat['Ma20'], 'black', label='M20', lw=1.0) self.am.plot(numt, stockdat['Ma60'], 'green', label='M60', lw=1.0) self.am.plot(numt, stockdat['Ma120'], 'blue', label='M120', lw=1.0) self.am.legend(loc='best', shadow=True, fontsize='10') ''' 绘制成交量 ''' self.vol.bar(numt, stockdat.Volume, color=[ 'g' if stockdat.Open[x] > stockdat.Close[x] else 'r' for x in range(0, len(stockdat.index)) ]) ''' 绘制MACD ''' # 绘制BAR>0 柱状图 bar_red = np.where(stockdat['macd_bar'] > 0, 2 * stockdat['macd_bar'], 0) # 绘制BAR<0 柱状图 bar_green = np.where(stockdat['macd_bar'] < 0, 2 * stockdat['macd_bar'], 0) self.macd.plot(numt, stockdat['macd_dif'], 'red', label='macd dif') # dif self.macd.plot(numt, stockdat['macd_dea'], 'blue', label='macd dea') # dea self.macd.bar(numt, bar_red, facecolor='red', label='hist bar') self.macd.bar(numt, bar_green, facecolor='green', label='hist bar') self.macd.legend(loc='best', shadow=True, fontsize='10') # legend = self.macd.legend(loc='best',shadow=True, fontsize ='10') # legend.get_frame().set_facecolor('#00FFCC')# Put a nicer background color on the legend. # legend.get_title().set_fontsize(fontsize = 20) ''' 绘制KDJ ''' self.devol.plot(numt, stockdat['K'], 'blue', label='K') # K self.devol.plot(numt, stockdat['D'], 'g--', label='D') # D self.devol.plot(numt, stockdat['J'], 'r-', label='J') # J self.devol.legend(loc='best', shadow=True, fontsize='10')
def plt(self, savefig=False): # 動作が重くならないようにクリアする plt.clf() #fig = plt.figure(figsize=(10, 6)) fig, (ax, ax2) = plt.subplots(2,1, gridspec_kw = {'height_ratios':[3, 1]}, figsize=(8, 8)) #ax = fig.add_subplot(111) ax.set_title('code:' + str(self.code) + "\n[rule]buy in 5 candle from GC at MACD", loc='center', fontsize=20) ax.set_xlabel('day') ax.set_ylabel('price') ax.autoscale_view() ax.grid(True) #ax.patch.set_facecolor('k') # 背景色 #ax.patch.set_alpha(0.6) # 透明度 finance.candlestick2_ochl(ax, opens=self.ohcl["open"],\ highs=self.ohcl["high"],\ lows=self.ohcl["low"],\ closes=self.ohcl["close"],\ width=0.5, colorup='r',\ colordown='g', alpha=0.75) self.__plt_ichimoku_cloud(ax) self.__plt_bolinger_band(ax) self.__plt_envelope(ax) self.__plt_upper_support_line(ax) self.__plt_GMMA(ax) self.__plt_volume(ax) #self.__plt_RSI(ax2) #self.__plt_RCI(ax2) self.__plt_MACD(ax2) #plt.xlim([30,65]) ax.set_xlim(80, 135) ax2.set_xlim(80, 135) plt.grid(True, linestyle='--', color='0.75') # 画像を保存する if savefig == True: fig_name = str(self.code) + ".png" plt.savefig(fig_name) fig.tight_layout() plt.show()
def plot_stock_line(api,code, name, table_name, current, start='2017-10-01', save=False): title = '{} {} {} {}'.format(current, code, name, table_name) title = title.replace('*', '_') if os.path.exists(title + '.png'): return if code is None and name is not None: code = base_info[base_info['name'] == name]['code'].values[0] df = None for _ in range(4): try: df = ts.bar(code, conn=api, start_date=start) except Exception as e: logger.info(e) ts.close_apis(api) time.sleep(random.random() * 30) api = ts.get_apis() else: break if df is None: return df = df.sort_index() if name is None: name = base_info[base_info['code'] == code]['name'].values[0] df = df.reset_index() df['datetime'] = df['datetime'].dt.strftime('%Y-%m-%d') sma5 = talib.SMA(df['close'].values, 5) sma20 = talib.SMA(df['close'].values, 10) # ax.set_xticks(range(0,len(df),20)) # # ax.set_xticklabels(df['date'][::5]) # ax.set_xticklabels(df['datetime'][::20]) fig = plt.figure(figsize=(10, 8)) # fig,(ax,ax2)=plt.subplots(2,1,sharex=True,figsize=(16,10)) ax = fig.add_axes([0, 0.3, 1, 0.50]) ax2 = fig.add_axes([0, 0.1, 1, 0.20]) candlestick2_ochl(ax, df['open'], df['close'], df['high'], df['low'], width=1, colorup='r', colordown='g', alpha=0.6) ax.grid(True) ax.set_title(title) ax.plot(sma5, label='MA5') ax.legend() ax.plot(sma20, label='MA20') ax.legend(loc=2) ax.grid(True) # df['vol'].plot(kind='bar') volume_overlay(ax2, df['open'], df['close'], df['vol'], width=1, alpha=0.8, colordown='g', colorup='r') ax2.set_xticks(range(0, len(df), 5)) # ax.set_xticklabels(df['date'][::5]) ax2.set_xticklabels(df['datetime'][::5]) plt.setp(ax2.get_xticklabels(), rotation=30, horizontalalignment='right') ax2.grid(True) plt.subplots_adjust(hspace=0.3) if save: # path = os.path.join(os.path.dirname(__file__),'data',today) fig.savefig(title + '.png') else: plt.show() plt.close()