def main(): # 株価の取得(銘柄コード, 開始日, 終了日) code = 4783 data = get_stock(code, '2017-1-1', '2017-8-21') # データフレームの作成 df = pd.DataFrame( { '始値': data[1], '終値': data[2], '高値': data[3], '安値': data[4] }, index=data[0]) # グラフにプロット fig = plt.figure() ax = plt.subplot() mpf.candlestick2_ohlc(ax, df['始値'], df['高値'], df['安値'], df['終値'], width=0.5, colorup="g", colordown="r") ax.grid() ax.legend() fig.autofmt_xdate() #x軸のオートフォーマット plt.show()
def DrawGraph4(): import matplotlib.finance as matfin import matplotlib.ticker as ticker fig = plt.figure(figsize=(12,8)) # Create Empty Object with specific size ax = fig.add_subplot(1,1,1) #matfin.candlestick2_ohlc(ax, df['Open'], df['High'], df['Low'], df['Close'], width=0.5, colorup='red', colordown='blue') matfin.candlestick2_ohlc(ax, df_STDEV['OP'], df_STDEV['HI'], df_STDEV['LO'], df_STDEV['CL'], width=0.5, colorup='red', colordown='blue') #day_list = [] #name_list = [] #for i, day in enumerate(df.index): #for i, day in enumerate(df_STDEV['DATE']): # if (day.day == 1): # 월요일마다 'day.dayofweek == 0' # day_list.append(i) # name_list.append(day.strftime('%m-%d')) # 요일은 (%a) #ax.xaxis.set_major_locator(ticker.FixedLocator(day_list)) #ax.xaxis.set_major_formatter(ticker.FixedFormatter(name_list)) #plt.title(company_name) #plt.xlabel('Time'); #plt.ylabel('Price') xmin = df_STDEV.index.min() - datetime.timedelta(15) xmax = df_STDEV.index.max() + datetime.timedelta(15) #xmin = df.index.min() - datetime.timedelta(15) #xmax = df.index.max() + datetime.timedelta(15) #ymin = df['Close'].min(); ymax = df['Close'].max() #plt.xlim((xmin,xmax)) # set ONLY X-axis range #plt.ylim((ymin,ymax)) # set ONLY Y-axis range #plt.axis([xmin,xmax,ymin,ymax]) # set Axes [xmin,xmax,ymin,ymax] #plt.axis('equal') # set Axes [xmin,xmax,ymin,ymax] plt.grid(True) plt.show()
def main(): args = get_args() data = read_data(args) data = data[:].iloc[0:-1] x = np.arange(len(data.index)) y = data['close'].values trend_reversal_analysis(15, data, direction=-1, change_ratio_margins=np.concatenate([ np.linspace(0.0005, 0.005, 10), np.linspace(0.006, 0.035, 9) ]), max_reversal_margins=np.linspace(0.1, 1., 10), show_as_percentage=True) # validate_ohlc(data['open'], data['high'], data['low'], data['close'], data) if False: fig, ax = plt.subplots() candlestick2_ohlc(ax, data['open'], data['high'], data['low'], data['close'], width=0.6) show() validate_ohlc(data['open'], data['high'], data['low'], data['close'], data) fig = FF.create_candlestick(data['open'], data['high'], data['high'] * 0., data['close'], dates=data.index)
def plot_ohlcv(self, df): fig, ax = plt.subplots() # Plot the candlestick candlestick2_ohlc(ax, df['open'], df['high'], df['low'], df['close'], width=1, colorup='g', colordown='r', alpha=0.5) # shift y-limits of the candlestick plot so that there is space # at the bottom for the volume bar chart pad = 0.25 yl = ax.get_ylim() ax.set_ylim(yl[0] - (yl[1] - yl[0]) * pad, yl[1]) # Add a seconds axis for the volume overlay ax2 = ax.twinx() ax2.set_position( matplotlib.transforms.Bbox([[0.125, 0.1], [0.9, 0.26]])) # Plot the volume overlay # bc = volume_overlay(ax2, df['open'], df['close'], df['volume'], # colorup='g', alpha=0.5, width=1) ax.xaxis.set_major_locator(ticker.MaxNLocator(6)) def mydate(x, pos): try: return df.index[int(x)] except IndexError: return '' ax.xaxis.set_major_formatter(ticker.FuncFormatter(mydate)) plt.margins(0) plt.show()
def his100chart(company): company = company.lower() df100 = history100day(company) import matplotlib.pyplot as plt from matplotlib.finance import candlestick2_ohlc #show 20 day moving averages print("Last 100-day trade history chart") df100["HMean"] = df100["High"].rolling(20).mean() df100["LMean"] = df100["Low"].rolling(20).mean() df100.reset_index(inplace=True) fig, ax = plt.subplots() plt.xticks(rotation=45) plt.xlabel("Last 100 days") plt.ylabel("USD Price") plt.title(company + "/USD : High and Low 20 day moving averages") candlestick2_ohlc(ax, df100["Open"], df100["High"], df100["Low"], df100["Close"], width=1, colorup='g') df100.HMean.plot(ax=ax) df100.LMean.plot(ax=ax) plt.show()
def graphData(self, quotes): """Works in http://localhost:8888/notebooks/Jupyter/OHLC%20Graphs.ipynb end""" # Fix the no graphics backend issue mpl.use('TkAgg') fig, ax = plt.subplots() candlestick2_ohlc( ax, quotes['Open'], quotes['High'], quotes['Low'], quotes['Close'], width=0.6) xdate = [datetime.datetime.fromtimestamp(i) 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() fig.tight_layout() plt.show() return
def kline(ax=None, code=None, data=None, start=None, end=None, ktype='D', num=DATE_NUM, figsize=FIG_SIZE, width=1, colorup='w', colordown='k', alpha=0.5): ax, data = _init(code, ax=ax, start=start, end=end, ktype=ktype, data=data, figsize=figsize) candlestick2_ohlc(ax, data.open, data.high, data.low, data.close, width, colorup, colordown, alpha) # init_xtick_date(ax, data, num) return data
def DrawGraph4(): import matplotlib.finance as matfin import matplotlib.ticker as ticker fig = plt.figure(figsize=(12,8)) # Create Empty Object with specific size ax = fig.add_subplot(1,1,1) #matfin.candlestick2_ohlc(ax, DF_stock["Open"], DF_stock["High"], DF_stock["Low"], DF_stock["Close"], width=0.5, colorup="red", colordown="blue") matfin.candlestick2_ohlc(ax, df_STDEV["OP"], df_STDEV["HI"], df_STDEV["LO"], df_STDEV["CL"], width=0.5, colorup="red", colordown="blue") #day_list = [] #name_list = [] #for i, day in enumerate(DF_stock.index): #for i, day in enumerate(df_STDEV["DATE"]): # if (day.day == 1): # 월요일마다 "day.dayofweek == 0" # day_list.append(i) # name_list.append(day.strftime("%m-%d")) # 요일은 (%a) #ax.xaxis.set_major_locator(ticker.FixedLocator(day_list)) #ax.xaxis.set_major_formatter(ticker.FixedFormatter(name_list)) #plt.title(company_name) #plt.xlabel("Time"); #plt.ylabel("Price") xmin = df_STDEV.index.min() - datetime.timedelta(15) xmax = df_STDEV.index.max() + datetime.timedelta(15) #xmin = DF_stock.index.min() - datetime.timedelta(15) #xmax = DF_stock.index.max() + datetime.timedelta(15) #ymin = DF_stock["Close"].min(); ymax = DF_stock["Close"].max() #plt.xlim((xmin,xmax)) # set ONLY X-axis range #plt.ylim((ymin,ymax)) # set ONLY Y-axis range #plt.axis([xmin,xmax,ymin,ymax]) # set Axes [xmin,xmax,ymin,ymax] #plt.axis("equal") # set Axes [xmin,xmax,ymin,ymax] plt.grid(True) plt.show()
def plot_curr_time(curr_time, quotes, slices=40): if quotes is None: return fig, ax1 = plt.subplots() ax2 = ax1.twinx() candlestick2_ohlc(ax1, quotes['open'], quotes['high'], quotes['low'], quotes['close'], width=0.6) vol_prof = construct_vol_profile(curr_time, quotes, slices=40) prices = [x[0] for x in vol_prof] vols = [x[1] for x in vol_prof] oldMin = min(vols) oldMax = 5000000 newMin = 0 newMax = 90 vol_scale = [ (((x - oldMin) * (newMax - newMin)) / (oldMax - oldMin)) + newMin for x in vols ] t = np.arange(slices) ax2.barh(t, vol_scale, alpha=0.5) ax1.get_yaxis().set_visible(False) ax2.get_yaxis().set_visible(False) ax1.get_xaxis().set_visible(False) ax2.get_xaxis().set_visible(False) fig.savefig('./images/' + str(curr_time) + '.png', bbox_inches='tight') plt.close(fig) return
def root(): upbit = Upbit() frame = upbit.get_candles('BTC', 'days') fig = plt.figure(figsize=(20, 16)) ax1 = fig.add_subplot(212) ax2 = fig.add_subplot(212) ax1 = plt.subplot2grid((4, 4), (0, 0), rowspan=3, colspan=4) ax2 = plt.subplot2grid( (4, 4), (3, 0), rowspan=1, colspan=4 ) # ax = fig.add_subplot(111) # ax.xaxis.set_major_formatter(ticker.FixedLocator(time_list)) #frame['MA20'] = frame['tradePrice'].rolling(window=20).mean() #frame['MA60'] = frame['tradePrice'].rolling(window=60).mean() print(frame) matfin.candlestick2_ohlc(ax1, frame['openingPrice'], frame['highPrice'], frame['lowPrice'], frame['tradePrice'], width=0.5, colorup='r', colordown='b') #ax1.plot(frame['MA20'], label='MA20') #ax1.plot(frame['MA60'], label='MA60') ax2.plot(frame['candleAccTradeVolume']) canvas = FigureCanvas(fig) png_output = BytesIO() canvas.print_png(png_output) response = make_response(png_output.getvalue()) response.headers['Content-Type'] = 'image/png' return response
def plotCandles(o, h, l, c, ema8, ema13, ema21, ema55, pair, ax1): # MAIN FRAME. # ============================================================= # - CANDLESTICK SUB-PLOT. # ============================================================= ax1.clear(); ax1.set_title(pair) ax1.set_facecolor('black') candlestick2_ohlc(ax1, o, h, l, c, width=0.6, colorup='g', colordown='r') ax1.plot(ema8, linewidth=1, color='cyan'); ax1.plot(ema13, linewidth=1, color='purple'); ax1.plot(ema21, linewidth=1, color='orange'); ax1.plot(ema55, linewidth=1, color='yellow'); lastclose = c[len(c) - 1]; lastopen = o[len(o) - 1]; if(lastclose > lastopen): ax1.axhline(y=lastclose, color='g', linestyle='--') elif(lastclose < lastopen): ax1.axhline(y=lastclose, color='r', linestyle='--') else: ax1.axhline(y=lastclose, color='b', linestyle='--') plt.gcf();
def check_db_data(cls, code, start_date, end_date, table, db='server_db', dbname='big-data', db2='server_db', dbname2='big-data', path='f://zjf//check_data//'): if table == None: raise Exception("table can't be empty") data = KlineData(location=db, dbname=dbname).read_data(code=code, start_date=start_date, end_date=end_date, kline=table, timemerge=True) data = data.sort_values(by=['date'], ascending=True) data2 = KlineData(location=db2, dbname=dbname2).read_data(code=code, start_date=start_date, end_date=end_date, kline=table, timemerge=True) data2 = data2.sort_values(by=['date'], ascending=True) print('start draw.......') # fig, ax = plt.subplots() # fig.subplots_adjust(bottom=0.2) ax = plt.subplot(211) # plt.title('本地') ax.set_xticks([]) candlestick2_ohlc(ax, data.open, data.high, data.low, data.close, width=1, colorup='red', colordown='green') plt.title(db + '--' + table + '--' + code) ax = plt.subplot(212) # plt.title('远程') plt.title(db2 + '--' + table + '--' + code) candlestick2_ohlc(ax, data2.open, data2.high, data2.low, data2.close, width=1, colorup='red', colordown='green') # plt.show() File.check_file(path=path) ax.set_xticks([]) plt.savefig(path + table + '.png', transparent=True) plt.close()
def main(): #start = datetime.datetime(2016, 3, 1) #end = datetime.datetime(2016, 3, 31) #skhynix = web.DataReader("078930.KS", "yahoo", start, end) stockInfo = StockReader.getStockItem("026260").tail(30) stockInfo['MA5'] = stockInfo['Adj Close'].rolling(window=5).mean() stockInfo['MA20'] = stockInfo['Adj Close'].rolling(window=20).mean() stockInfo['MA60'] = stockInfo['Adj Close'].rolling(window=60).mean() stockInfo['MA120'] = stockInfo['Adj Close'].rolling(window=120).mean() #print(stockInfo) fig = plt.figure(figsize=(12, 8)) ax = fig.add_subplot(311) day_list = [] name_list = [] for i, day in enumerate(stockInfo.index): #if day.dayofweek == 0: day_list.append(i) name_list.append(day.strftime('%d')) #name_list.append(day.strftime('%Y-%m-%d') + '(Mon)') #else: # print(day.weekday()) print(day_list) print(name_list) ax.text(.5, .9, 'centered title', horizontalalignment='center', transform=ax.transAxes) ax.xaxis.set_major_locator(ticker.FixedLocator(day_list)) ax.xaxis.set_major_formatter(ticker.FixedFormatter(name_list)) matfin.candlestick2_ohlc(ax, stockInfo['Open'], stockInfo['High'], stockInfo['Low'], stockInfo['Close'], width=0.5, colorup='r', colordown='b') plt.grid() print(stockInfo['Volume']) ax = fig.add_subplot(312) ax.bar(stockInfo['Volume'].index, stockInfo['Volume'], width=0.8) plt.grid() plt.figure(1) plt.subplot(313) plt.plot(stockInfo.index, stockInfo['MA5'], label="MA5") plt.plot(stockInfo.index, stockInfo['MA20'], label="MA20") plt.plot(stockInfo.index, stockInfo['MA60'], label="MA60") #plt.plot(stockInfo.index, stockInfo['MA120'], label="MA120") plt.legend(loc='best') plt.grid() plt.show()
def plotKWithNoGap(ohlcDF, figureSize=(30,8), tickWin=5): from matplotlib.finance import candlestick2_ohlc fig, ax = plt.subplots(figsize=figureSize) candlestick2_ohlc(ax, ohlcDF['OPEN'], ohlcDF['HIGH'], ohlcDF['LOW'], ohlcDF['CLOSE'], width=0.7, colorup='g', colordown='r') ax.xaxis.set_ticks(np.arange(0, len(ohlcDF), tickWin)) ax.xaxis.set_major_formatter(MyFormatter(ohlcDF.index)) ax.set_xlim(-1, len(ohlcDF)) fig.autofmt_xdate() # 自动调整x轴日期显示效果 plt.grid(True) plt.show()
def plot_tech_indicators(Open, high, Low, Close, tech_data, indicators): fig,ax = plt.subplots() candlestick2_ohlc(ax, Open, High, Low, Close, width=0.6) #create a general color scheme colors = ['r','g','b','y','v'] col = 0 for indicator in indicators: plt.plot(list(tech_data[indicator]), colors[col]) col += 1 #add legend plt.show()
def check(cls, code, start_date, end_date): table = 'kline_min5' table2 = 'tmp_kline_min5' path = 'f:/zjf/data/check6/' data = KlineData.read_data(code=code, start_date=start_date, end_date=end_date, kline=table, timemerge=True) if len(data) <= 0: return data = data.sort_values(by=['date'], ascending=True) data = data[data.time <= 955] data2 = KlineData.read_data(code=code, start_date=start_date, end_date=end_date, kline=table2, timemerge=True) if len(data2) <= 0: return data2 = data2.sort_values(by=['date'], ascending=True) data2 = data2[data2.time <= 955] print('start draw.......') # fig, ax = plt.subplots() # fig.subplots_adjust(bottom=0.2) ax = plt.subplot(211) # plt.title('本地') ax.set_xticks([]) candlestick2_ohlc(ax, data.open, data.high, data.low, data.close, width=1, colorup='red', colordown='green') plt.title(table + '--' + code) ax = plt.subplot(212) # plt.title('远程') plt.title(table2 + '--' + code) candlestick2_ohlc(ax, data2.open, data2.high, data2.low, data2.close, width=1, colorup='red', colordown='green') File.check_file(path=path) ax.set_xticks([]) plt.savefig(path + code + '.png', transparent=True) plt.close()
def plot_graph(self, stockName): df = pd.read_csv(stockName) fig, ax = plt.subplots() try: candlestick2_ohlc(ax, df['open'], df['high'], df['low'], df['close'], width=0.9) plt.xlabel('Date') plt.ylabel('Price') print("Plotting -> {}".format(stockName)) stock_plot = stockName.split('.csv')[0].split('/')[1] plt.title("Stock Graph For {}".format(stock_plot)) plt.savefig('Visualizations/candlestick_{}.png'.format(stock_plot)) except: print("Error -> {}".format(stockName))
def candlestick(self, start_date=None, end_date=None, figsize=None): self._make_sure_has_run() temp = self._df.loc[start_date:end_date] fig, ax = plt.subplots(figsize=figsize) ax.set_title(self.__str__(), size=13) xdates = [i.strftime("%Y-%m-%d") for i in temp.index] steps = int(math.ceil(len(temp)/62.0)) ax.set_xticks(np.arange(len(temp), step = steps)) ax.set_xticklabels(xdates[::steps], rotation=90) candlestick2_ohlc(ax,temp['ha_open'],temp['ha_high'],temp['ha_low'],temp['ha_last'],width=0.6, colorup='#77d879', colordown='#db3f3f')
def plot(data, name): n = len(data['close']) fig, ax = plt.subplots(3, sharex=True) candlestick2_ohlc(ax[0], data['open'], data['high'], data['low'], data['close'], width=0.6) ax[1].plot(data['btc_equ']) ax[2].plot(data['average_gains']) ax[0].set_title(name) plt.show()
def showSignalPoint(self): dfSignal = pd.read_csv(self.path + 'MinEquity.csv') dfSignal.columns = [ 'dt', 'equity', 'open', 'high', 'low', 'close', 'volume', 'openInt', 'dire', 'sprice', 'svolume' ] temcolum = np.arange(dfSignal.index.size) dfSignal['num'] = temcolum longsignal = dfSignal[dfSignal.loc[:, 'dire'] > 0] longx = longsignal['num'] longy = longsignal.loc[:, 'sprice'] shortsignal = dfSignal[dfSignal.loc[:, 'dire'] < 0] shortx = shortsignal['num'] shorty = shortsignal.loc[:, 'sprice'] # fig1 = plt.figure('signal draw') ax1 = plt.subplot(111) # plt.xaxis_date() plt.xticks(rotation=45) mf.candlestick2_ohlc(plt.axes(), dfSignal.loc[:, 'open'], dfSignal.loc[:, 'high'], dfSignal.loc[:, 'low'], dfSignal.loc[:, 'close'], width=0.75, colorup=u'r', colordown=u'g', alpha=1) for i in range(dfSignal.shape[1] - 12): plt.plot(dfSignal.index, dfSignal.iloc[:, i + 9], '.-', label=dfSignal.columns[i + 9]) plt.scatter(longx, longy, s=160, c='m', marker='^', label='long') plt.scatter(shortx, shorty, s=160, c='k', marker='v', label='short') ax2 = ax1.twinx() ax2.plot(dfSignal.loc[:, 'equity'], c='r') plt.legend() plt.grid() plt.tight_layout() plt.savefig(self.path + 'Signal.png') plt.show() fig1.clear() plt.close()
def plot_candlestick1(data, ax=None, title_label=None): ''' matplotlib implementation. ''' if ax is None: fig, ax = plt.subplots(1, 1, figsize=(16, 8)) candlestick2_ohlc(ax, data['open'], data['high'], data['low'], data['close'], width=1) return
def candlestick(): class Data: def __init__(self, index, start, date): self.index = index self.start = start self.date = date def get(self): return web.DataReader(self.index, 'google', self.start, self.date) class rol_mean_plot: def __init__(self, data, window): self.data = data self.window = window def rol_mean(self): return self.data.rolling(window=self.window).mean().plot( subplots=False, grid=True, figsize=(8, 6)) def plot(y, window): rol_mean_plot.rol_mean(rol_mean_plot(y, window)) index = input('\nEnter the Index:\n\n>>> ') start = input('Enter the initial date [YYYY, MM, DD]:\n\n>>> ') dt = start.split(',') start = datetime.datetime(int(dt[0]), int(dt[1]), int(dt[2])) end = input('Enter the end date [YYYY, MM, DD]:\n\n>>> ') st = end.split(',') end = datetime.datetime(int(st[0]), int(st[1]), int(st[2])) # dateRange = pd.date_range(start, end, freq='D') quotes = Data.get(Data(index, start, end)) fig, ax = plt.subplots(figsize=(8, 6)) candlestick2_ohlc(ax, quotes['Open'], quotes['High'], quotes['Low'], quotes['Close'], width=0.6) plt.xticks(rotation=45) plt.title('Stock Index {}'.format(index)) plt.xlabel('Days in period [{} - {}]'.format(start, end)) plt.ylabel('{} Price'.format(index)) plt.show()
def plot(data, columnNames=None, timeColumnName=None, majorLocatorStep=20, majorOffset=0, minorLocatorStep=5, minorOffset=0, displayMinor=False, timeFormat='%Y-%m-%d', rotation=45, stickWidth=0.6, alpha=1): ''' 根据所给的数据,画出蜡烛图 @param: data: 原始数据,要求为pandas.DataFrame的形式,默认的有open, close, high low这四列,反之需要通过columnNames参数提供,依次的顺序为openName, closeName, highName, lowName,若要画出时间轴,则需要数据中有date列, 否则则需要通过使用的时候通过timeFormat来提供 columnNames: 默认data中有open, close, high, low这些列,反之则需要自行提供 timeColumnName: 当需要画以时间为横轴的图时,需要提供时间列的列名 majorLocatorStep: 主刻度间隔,默认为间隔20个数据 minorLocatorStep: 副刻度间隔,默认为间隔5个数据 displayMinor: 是否在副刻度上也标明时间或者顺序下标,默认不标明 majorFormat: 解析时间列主刻度的方法,需按照datetime中的形式解析,默认为%Y-%m-%d minorFormat: 解析时间列副刻度的方法,需按照datetime中的形式解析,默认为%Y-%m-%d rotation: 横轴值旋转度数,默认旋转45度 stickWidth: 蜡烛图的宽度,默认为0.6 alpha: 蜡烛图颜色的深度,默认为1 ''' plt.style.use('seaborn-ticks') fig, ax = plt.subplots() if not columnNames is None: openName, closeNames, highName, lowName = columnNames else: openName, closeNames, highName, lowName = ('open', 'close', 'high', 'low') opens, closes, highs, lows = data[openName].tolist(), data[closeNames].tolist(), data[ highName].tolist(), data[lowName].tolist() fig.subplots_adjust(bottom=0.2) majorLocator = ticker.IndexLocator(majorLocatorStep, majorOffset) ax.xaxis.set_major_locator(majorLocator) minorLocator = ticker.IndexLocator(minorLocatorStep, minorOffset) ax.xaxis.set_minor_locator(minorLocator) if not timeColumnName is None: times = data[timeColumnName].tolist() time_formatterSetting(ax, times, majorLocatorStep, majorOffset, timeFormat, displayMinor, minorLocatorStep, minorOffset) finance.candlestick2_ohlc(ax, opens, highs, lows, closes, width=stickWidth, colorup='r', colordown='g', alpha=alpha) plt.setp(ax.get_xticklabels(), rotation=rotation) if displayMinor: plt.setp(ax.xaxis.get_minorticklabels(), rotation=rotation) xmin, xmax = plt.xlim() plt.xlim(xmin=xmin-1) plt.grid(True) plt.show()
def plot_p(df): import matplotlib.pyplot as plt from matplotlib.finance import candlestick2_ohlc fig, ax = plt.subplots() candlestick2_ohlc(ax, df['price_open'].values, df['price_high'].values, df['price_low'].values, df['price_close'].values, width=0.6, colorup='g', colordown='r', alpha=1) plt.show() print('Done.')
def save_to_file(df, filename): import matplotlib.pyplot as plt from matplotlib.finance import candlestick2_ohlc fig, ax = plt.subplots() candlestick2_ohlc(ax, df['price_open'].values, df['price_high'].values, df['price_low'].values, df['price_close'].values, width=0.6, colorup='g', colordown='r', alpha=1) plt.savefig(filename) plt.close(fig)
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]) 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(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)) matfin.candlestick2_ohlc(ax, daeshin_day['open'], daeshin_day['high'], daeshin_day['low'], daeshin_day['close'], width=0.5, colorup='r', colordown='b') plt.grid() plt.show()
def plot_security_k(ax,_dfquotes,begin,_locatormulti=40): """ plot k graph with ma5,10,20,30 line Args: _dfquotes (dataframe): the seurity dataframe which include'openPrice''closePrice''highestPrice''lowestPrice''tradeDate' ax : matplotlib ax object begin : the index of first k bar, _dfquotes[begin:] will be plot _locatormulti (int): adjust the axis's ticker display interval Returns: lineandbars : return candlestick2_ohlc's lineandbars objects Examples: >> """ global _tickerstart global dfquotes dfquotes = _dfquotes _tickerstart = begin lineandbars = maf.candlestick2_ohlc(ax,dfquotes[u'openPrice'][_tickerstart:].values,\ dfquotes[u'highestPrice'][_tickerstart:].values,\ dfquotes[u'lowestPrice'][_tickerstart:].values,\ dfquotes[u'closePrice'][_tickerstart:].values,\ colorup='r',colordown='g',width=0.5,alpha=1.0) #adjust the k graph's color lineandbars[1].set_edgecolor(lineandbars[1].get_facecolor()) lineandbars[0].set_color(lineandbars[1].get_facecolor()) _multilocator = int((len(dfquotes)-_tickerstart)/_locatormulti)#超过40个交易日,日期刻度单位加一天 ax.xaxis.set_major_locator(MultipleLocator(1+_multilocator)) ax.xaxis.set_major_formatter(ticker.FuncFormatter(format_date)) plt.gcf().autofmt_xdate() plotEMA([5,10,20,30],dfquotes[u'closePrice'].values,_tickerstart) for label in ax.xaxis.get_ticklabels(): label.set_rotation(90) return lineandbars
def plot_with_price(quotes, save_to_file=None, min_max=[]): # fig = plt.figure() fig, ax = plt.subplots(figsize=(30, 15)) # ax.set_xlim([1,2]) # ax.set_ylim(min_max) candlestick2_ohlc(ax, quotes['open'], quotes['high'], quotes['low'], quotes['close'], width=0.6) xdate = [i for i in quotes.index] 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)) ax2 = ax.twinx() # ax2.set_ylim([0,5000]) # Plot the volume overlay bc = volume_overlay(ax2, quotes['open'], quotes['close'], quotes['volume'], colorup='g', alpha=0.1, width=1) ax2.add_collection(bc) fig.autofmt_xdate() fig.tight_layout() # plt.show() if (save_to_file is not None): plt.savefig(save_to_file)
def stock_week_tech_analysis(code): print("stock techinical analysis start to parse the stock on week level" + str(code)) dff = ts.get_hist_data(code, start='2016-01-04', ktype='W') df = dff[::-1] df macd, macdsignal, macdhist = ta.MACD(np.array(df['close']), fastperiod=12, slowperiod=26, signalperiod=9) ma5 = ta.MA(np.array(df['close']), 5, matype=0) ma10 = ta.MA(np.array(df['close']), 10, matype=0) ma20 = ta.MA(np.array(df['close']), 20, matype=0) # ma20 = ta.MA(np.array(df['close'],20,mtype=0) print("the close[-1] is " + str(df['close'][-1]) + " and the ma5[-1] is " + str(ma5[-1]) + "and the ma20[-1] is " + str(ma20[-1])) if ma5[-1] > ma20[-1]: if df['close'][-1] > ma5[-1]: print(" the stock " + str(code) + " is bull! ") if ma5[-1] < ma20[-1]: if df['close'][-1] < ma5[-1]: print(" the stock " + str(code) + " is bear! ") fig = plt.figure() fig.subplots_adjust(bottom=0.1) fig.subplots_adjust(hspace=0) gs = gridspec.GridSpec(2, 1, height_ratios=[4, 1]) ax0 = plt.subplot(gs[0]) candles = candlestick2_ohlc(ax0, np.array(df['open']), df['high'], df['low'], df['close'], width=1, colorup='r', colordown='g') ax0.plot( ma5, color='black', lw=2, ) ax0.plot(ma20, color='yellow', lw=2) ax0.plot(ma10, color='green', lw=2) # trying to plot the trending line of the stock maxidx = df['close'].idxmax(axis=1) minidx = df['close'].idxmin(axis=1) # dmax = time.strptime(maxidx,"%Y-%m-%d") ; # dmin = time.strptime(minidx,"%Y-%m-%d") ; if maxidx > minidx: maxidx2 = df['close'][:minidx].idxmax(axis=1) minidx2 = df['close'][maxidx:].idxmin(axis=1) else: maxidx2 = df['close'][minidx:].idxmax(axis=1) minidx2 = df['close'][:maxidx].idxmin(axis=1) ax0.plot([df['close'][:maxidx].count(), df['close'][:maxidx2].count()], [df['close'][maxidx], df['close'][maxidx2]]) ax0.plot([df['close'][:minidx].count(), df['close'][:minidx2].count()], [df['close'][minidx], df['close'][minidx2]]) # ax0.plot(minidx,df['close'][minidx],minidx2,df['close'][minidx2]) ; plt.show()
def main(): # 株価の取得(銘柄コード, 開始日, 終了日) code = 3906 today = datetime.date.today() print(today) todaystr = today.strftime('%Y-%m-%d') data = get_stock(code, '2017-6-1', todaystr) print(todaystr) print("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^") # データフレームの作成 df = pd.DataFrame( { '始値': data[1], '終値': data[2], '高値': data[3], '安値': data[4] }, index=data[0]) print(df) # グラフにプロット fig = plt.figure() ax = plt.subplot() mpf.candlestick2_ohlc(ax, df['始値'], df['高値'], df['安値'], df['終値'], width=0.5, colorup="g", colordown="r") ax.set_xticklabels( [(df.index[int(x)].strftime("%Y/%M/%D") if x <= df.shape[0] else x) for x in ax.get_xticks()], rotation=90) ax.set_xlim([0, df.shape[0]]) # 横軸の範囲はデータの個数(df.shape[0]個)までに変更しておく ax.grid() ax.legend() fig.autofmt_xdate() #x軸のオートフォーマット plt.show()
def plotKWithNoGap(ohlcDF, figureSize=(30, 8), tickWin=5): from matplotlib.finance import candlestick2_ohlc fig, ax = plt.subplots(figsize=figureSize) candlestick2_ohlc(ax, ohlcDF['OPEN'], ohlcDF['HIGH'], ohlcDF['LOW'], ohlcDF['CLOSE'], width=0.7, colorup='g', colordown='r') ax.xaxis.set_ticks(np.arange(0, len(ohlcDF), tickWin)) ax.xaxis.set_major_formatter(MyFormatter(ohlcDF.index)) ax.set_xlim(-1, len(ohlcDF)) fig.autofmt_xdate() # 自动调整x轴日期显示效果 plt.grid(True) plt.show()
def candle(conn, size): cur = conn.cursor() cur.execute("""SELECT open FROM """ + env.sname + """ ORDER BY id DESC""") open = np.array(cur.fetchall())[:, 0] cur.execute("""SELECT high FROM """ + env.sname + """ ORDER BY id DESC""") high = np.array(cur.fetchall())[:, 0] cur.execute("""SELECT low FROM """ + env.sname + """ ORDER BY id DESC""") low = np.array(cur.fetchall())[:, 0] cur.execute("""SELECT close FROM """ + env.sname + """ ORDER BY id DESC""") close = np.array(cur.fetchall())[:, 0] cur.execute("""SELECT date FROM """ + env.sname + """ ORDER BY id DESC""") date = np.array(cur.fetchall())[:, 0] cur.execute("""SELECT volume FROM """ + env.sname + """ ORDER BY id DESC""") volume = np.array(cur.fetchall())[:, 0] day_list = [] name_list = [] for i, day in enumerate(date[len(date) - size:]): if day.weekday() == 0: day_list.append(i) name_list.append(day.strftime('%m/%d')) fig = plt.figure(figsize=(24, 16)) ax = fig.add_subplot(111) ax.xaxis.set_major_locator(ticker.FixedLocator(day_list)) ax.xaxis.set_major_formatter(ticker.FixedFormatter(name_list)) matfin.candlestick2_ohlc(ax, np.ndarray.tolist(open[len(date) - size:]), np.ndarray.tolist(high[len(date) - size:]), np.ndarray.tolist(low[len(date) - size:]), np.ndarray.tolist(close[len(date) - size:]), width=0.5, colorup='r', colordown='b') plt.title(env.sname + ' ' + str(size) + ' Days') plt.show() plt.gcf().clear() cur.execute("""SELECT * FROM """ + env.sname + """ ORDER BY id DESC""") all = np.array(cur.fetchall())[:, :] return all
def display_candlestick(ohlc, candle_width=0.8, width=20, height=10): plt.figure(figsize=(width, height), dpi=80) ax = plt.subplot() return mpf.candlestick2_ohlc( ax, ohlc['Open'], ohlc['High'], ohlc['Low'], ohlc['Close'], width=candle_width, colorup='blue', colordown='red', )
def get_plot_candlesticks_dataframe(data_frame, ax): candlestick2_ohlc(ax, data_frame[PriceStrings.STR_PRICE_OPEN.value], data_frame[PriceStrings.STR_PRICE_HIGH.value], data_frame[PriceStrings.STR_PRICE_LOW.value], data_frame[PriceStrings.STR_PRICE_CLOSE.value], width=0.8, colorup='#008000', colordown='#FF0000', alpha=1) # xdate = [datetime.datetime.fromtimestamp(i) for i in dataframe[PriceStrings.STR_PRICE_TIME.value]] xdate = data_frame[PriceStrings.STR_PRICE_TIME.value].values ax.xaxis.set_major_locator(ticker.MaxNLocator(6)) def get_date(x, pos): try: return xdate[int(x)] except IndexError: return '' ax.xaxis.set_major_formatter(ticker.FuncFormatter(get_date))
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() 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')
import pandas as pd import matplotlib.pyplot as plt from matplotlib.finance import candlestick2_ohlc quotes = pd.read_csv(r'D:\USDRUB_160101_180323.txt') fig, ax = plt.subplots() candlestick2_ohlc(ax,quotes['open'],quotes['high'],quotes['low'],quotes['close'], width=0.5) plt.show()
def plot_candlestick(sub,ax1,point =10, mount_flag = 0, direction = u'不买不卖'): sub=sub[sub.LOWEST_PRICE > 0] sub.reset_index(len(sub),inplace=True) del sub['index'] step = len(sub)/point if step < 1: step = 1 baseline = range(len(sub)/step+1) baseline = [int(x) * step for x in baseline] if len(sub) <= baseline[-1]: baseline = baseline[:-1] # baseline = range(len(sub)) listLabels = sub['TRADE_DATE'].values max_price = max(sub['HIGHEST_PRICE'].values) min_price = min(sub['LOWEST_PRICE'].values) plot_max = max_price * 1.05 plot_min = min_price * 0.95 candlestick2_ohlc(ax1, sub['OPEN_PRICE'],sub['HIGHEST_PRICE'], sub['LOWEST_PRICE'],sub['CLOSE_PRICE'], width=0.8, colorup='#ff1717',colordown='#53c156', alpha =1); if direction == u'卖出': ax1.plot(max(sub.index.values),sub['HIGHEST_PRICE'].values[-1],'gv') elif direction == u'买入': ax1.plot(max(sub.index.values),sub['LOWEST_PRICE'].values[-1],'r^') ## 成交量 # ax2=ax1.twinx() ax2 = ax1 if mount_flag == 1: plot_delta = plot_max - plot_min bar_height = plot_delta/5 mount_min = plot_min - bar_height sub['Mount']=sub['DEAL_AMOUNT'].astype(np.float64)*bar_height/max(sub['DEAL_AMOUNT'].values) ##归一化后的成交量 upframe = sub[sub.CLOSE_PRICE > sub.OPEN_PRICE] downframe = sub[sub.CLOSE_PRICE < sub.OPEN_PRICE] ax2.bar(downframe.index.values,downframe['Mount'].values,bottom=mount_min,color='#53c156', edgecolor='black',width=0.5) ax2.bar(upframe.index.values,upframe['Mount'].values,bottom=mount_min,color='#ff1717', edgecolor='black',width=0.5) ax2.set_ylim([mount_min*0.95,plot_max]) else: ax2.set_ylim([plot_min*0.95,plot_max]) ##均线 colors = ['r-','m-','b-','c-','y-'] mas = [5,10,20,60,120] linearr = [] desarr = [] for count in range(0,5): ma = mas[count] color = colors[count] line,=ax1.plot(sub.index.values,sub['mean%s'%ma].values,color) # line,=ax1.plot(sub.index.values,sub['mean5'].values,color='r-') linearr.append(line) desarr.append("mean%s"%ma) ax1.set_ylabel("Price") ax1.set_xticks(baseline) ax1.set_xticklabels(listLabels[baseline],fontdict={'size':8}) if max(baseline)> len(sub): ax1.set_xlim([min(baseline)-2,max(baseline)+2]) else: ax1.set_xlim([min(baseline)-2,len(sub)+2]) if direction == u'不买不卖': ax1.legend(linearr,desarr,loc='upper left',ncol=3) ax1.grid(True)
def candlechart(fig, ax, ohlc, width=0.8): return 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')
a=range(len(df_daily.index)) new=[] for i in a: if i%365==0: new.append(i) x=df_daily.index.strftime('%Y') # In[ ]: fig = plt.figure(figsize=(18,4)) ax1 = plt.subplot(1,1,1) plt.ylabel('Price') plt.xlabel('Date') plt.xticks(new,x[new], rotation=45) candlestick2_ohlc(ax1,o,h,l,c,width=1,colorup='k',colordown='r') ax1.autoscale_view() fig.autofmt_xdate() # In[ ]: df_daily['log_returns_close']= np.log(df_daily['price']['close']) - np.log(df_daily['price']['close'].shift(1)) df_daily['log_returns_open']= np.log(df_daily['price']['open']) - np.log(df_daily['price']['open'].shift(1)) df_daily['log_returns_high']= np.log(df_daily['price']['high']) - np.log(df_daily['price']['high'].shift(1)) df_daily['log_returns_low']= np.log(df_daily['price']['low']) - np.log(df_daily['price']['low'].shift(1)) # In[ ]: df_daily.drop(df_daily.head(1).index,inplace=True)
ticknames = getMonthNames(r.date, tickindex) formatter = IndexDateFormatter(date2num(r.date), '%m/%d/%y') millionformatter = FuncFormatter(millions) thousandformatter = FuncFormatter(thousands) fig = plt.figure() fig.subplots_adjust(bottom=0.1) fig.subplots_adjust(hspace=0) gs = gridspec.GridSpec(2, 1, height_ratios=[4, 1]) ax0 = plt.subplot(gs[0]) candles = candlestick2_ohlc(ax0, r.open, r.high, r.low, r.close, width=1, colorup='g', colordown='r') ma05 = MA(r.adj_close, 5, type='simple') ma20 = MA(r.close, 20, type='simple') ma60 = MA(r.adj_close, 60, type='simple') Don20Hi = DonchianHi(r.high, 20) Don20Lo = DonchianLo(r.low, 20) BB20 = BB(r.close, 20) ma05[:5]=np.NaN ma20[:20]=np.NaN ma60[:60]=np.NaN ax0.plot(ma05, color='black', lw=2, label='MA (5)')