def candlestick(self, ticker, start = None, end = None): data = self[ticker][start:end] quotes = zip(date2num(data.index.astype(datetime.date)), data.Open, data.High, data.Low, data.Close) fig, ax = plt.subplots() candlestick_ohlc(ax, quotes) ax.xaxis_date() fig.autofmt_xdate() return (fig, ax)
def plot_candlestick(df): """ Plots a candlestick chart of the time series :param df: :return: """ # creating a new DataFrame based on the adjusted_close price resampled with a 10 day window tickers_ohlc = df['adj_close'].resample('10D').ohlc() # creating a new DataFrame based on the adjusted volume resampled with a 10 day window tickers_volume = df['adj_volume'].resample('10D').sum() # resetting the index of the DataFrame tickers_ohlc = tickers_ohlc.reset_index() # converting the date column to mdates tickers_ohlc['date'] = tickers_ohlc['date'].map(mdates.date2num) # creating a new figure fig = plt.figure() # creating a subplot with a 6x1 grid and starts at (0,0) ax1 = plt.subplot2grid((6, 1), (0, 0), rowspan=5, colspan=1) # creating a subplot with a 6x1 grid and starts at (5,0) ax2 = plt.subplot2grid((6, 1), (5, 0), rowspan=1, colspan=1, sharex=ax1) # converts the axis from raw mdate numbers to dates ax1.xaxis_date() # plotting the candlestick graph candlestick_ohlc(ax1, tickers_ohlc.values, width=2, colorup='g') # plotting the volume bar chart ax2.fill_between(tickers_volume.index.map(mdates.date2num), tickers_volume.values, 0) fig.tight_layout()
def plot_candlestic_with_extrema(dataframe, peak_indices, trough_indices, stock_name): fig, ax = plt.subplots(figsize=(16, 7)) fig.subplots_adjust(bottom=0.2) quotes = zip(mdates.date2num(dataframe.index.to_pydatetime()), dataframe[u'Open'], dataframe[u'High'], dataframe[u'Low'], dataframe[u'Close']) low_price_seq = dataframe['Low'].values high_price_seq = dataframe['High'].values candlestick_ohlc(ax, quotes, width=0.75, colorup='g', colordown='red', alpha=0.6) plt.plot(dataframe.index[peak_indices], pd.Series(high_price_seq, index=dataframe.index)[peak_indices], "v", color='black') plt.plot(dataframe.index[trough_indices], pd.Series(low_price_seq, index=dataframe.index)[trough_indices], "^", color='blue') ax.xaxis_date() ax.legend([stock_name], loc='upper right', shadow=True, fancybox=True) ax.autoscale_view() plt.setp(plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right') plt.rc('axes', grid=True) plt.rc('grid', color='0.75', linestyle='-', linewidth=0.5) plt.show()
def changeCandle(): plt.clf() if candleType == "1H": ax1 = plt.subplot2grid((6, 1), (0, 0), rowspan=5, colspan=1) ax2 = plt.subplot2grid((6, 1), (5, 0), rowspan=1, colspan=1, sharex=ax1) plt.setp(ax1.get_xticklabels(), visible=False) if showDates == False: plt.setp(ax2.get_xticklabels(), visible=False) df_ohlc = df_segment[["Close"]].resample(candleType).sum() df_volume = df_segment["Volume To"].resample(candleType).sum() df_ohlc.reset_index(inplace=True) df_ohlc["Date"] = df_ohlc["Date"].map(mdates.date2num) ax1.xaxis_date() # show mdates as readable normal date plt.plt(ax1) ax2.fill_between(df_volume.index.map(mdates.date2num), df_volume.values, 0, facecolors=volumeColor) fig.canvas.draw() else: ax1 = plt.subplot2grid((6, 1), (0, 0), rowspan=5, colspan=1) ax2 = plt.subplot2grid((6, 1), (5, 0), rowspan=1, colspan=1, sharex=ax1) plt.setp(ax1.get_xticklabels(), visible=False) if showDates == False: plt.setp(ax2.get_xticklabels(), visible=False) df_ohlc = df_segment["Close"].resample(candleType).ohlc() df_volume = df_segment["Volume To"].resample(candleType).sum() df_ohlc.reset_index(inplace=True) df_ohlc["Date"] = df_ohlc["Date"].map(mdates.date2num) ax1.xaxis_date() # show mdates as readable normal date candlestick_ohlc(ax1, df_ohlc.values, width=candleWidth, colorup=lightColor, colordown=darkColor) ax2.fill_between(df_volume.index.map(mdates.date2num), df_volume.values, 0, facecolors=volumeColor) fig.canvas.draw()
def plot_candlestick(self, data_in): """ Add volume: https://stackoverflow.com/questions/13128647/matplotlib-finance-volume-overlay :param data_in: list of list [[bar.date, bar.open, bar.high, bar.low, bar.close, bar.volume], [...], ...] :return: """ # Loop over all candles # data_in = [1,1] ohlc_data = [] self.axes.cla() for i in range(0, len(data_in)): date = data_in[i][BAR_DICT['Date']] conv_date = datetime.datetime.strptime(date, '%Y%m%d') # data_in[i][1] = data_in[i][1].astype(float) # data_in[i][2] = data_in[i][2].astype(float) # data_in[i][3] = data_in[i][3].astype(float) # data_in[i][4] = data_in[i][4].astype(float) # data_in[i][5] = data_in[i][5].astype(float) ohlc = [] ohlc.append(date2num(conv_date)) ohlc.append(float(data_in[i][1])) ohlc.append(float(data_in[i][2])) ohlc.append(float(data_in[i][3])) ohlc.append(float(data_in[i][4])) ohlc.append(float(data_in[i][5])) ohlc_data.append(ohlc) candlestick_ohlc(self.axes, ohlc_data, width=0.4, colorup='#77d879', colordown='#db3f3f') self.axes.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d')) self.axes.xaxis.set_major_locator(mticker.MaxNLocator(10)) self.fig.autofmt_xdate() self.axes.grid(True) self.draw()
def plot_custom_plot(self, cs_data, no_time=False): self.clear_sub_plots() candle_list = [] dates = [f['datetime'] / 1000.0 for f in cs_data] if not no_time: for candle in cs_data: candle_list.append([ float(mdates.epoch2num(candle['datetime'] / 1000.0)), float(candle['open']), float(candle['high']), float(candle['low']), float(candle['close']), float(candle['volume']) ]) else: for x in range(len(cs_data)): candle_list.append([ x, float(cs_data[x]['open']), float(cs_data[x]['high']), float(cs_data[x]['low']), float(cs_data[x]['close']), float(cs_data[x]['volume']) ]) # Changing the labels for the x-axis # self.axis_list[3].xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d')) # dates_formatted = [mdates.epoch2num(candle['datetime'] / 1000.) for candle in cs_data['candles']] # print('Dates formatted %s' % dates_formatted) self.axis_list[1].get_xaxis().set_visible(False) self.axis_list[2].get_xaxis().set_visible(False) candlestick_ohlc(self.axis_list[2], candle_list, colorup='green', colordown='red', width=.001)
def pattern(df, rule, signal): if signal == 'BearishHarami' or signal == 'BullishHarami': last1, last2 = 8, 9 elif signal == 'MorningStar' or signal == 'EveningStar': last1, last2 = 7, 8 target = df fontsize = 12 plt.rcParams['xtick.labelsize'] = fontsize plt.rcParams['ytick.labelsize'] = fontsize plt.rcParams['axes.titlesize'] = fontsize fig = plt.figure(figsize=(24, 8)) ax = plt.subplot2grid((1, 1), (0, 0)) ax.set_xticks(range(10)) ax.set_xticklabels(target.index) y = target['close'].iloc[0:last1].values.reshape(-1, 1) x = np.array(range(1, last2)).reshape(-1, 1) model = LinearRegression() model.fit(x, y) y_pred = model.predict(x) ax.plot(y_pred, label='Trend') arr = np.c_[range(target.shape[0]), target[['open', 'high', 'low', 'close']].values] mpf.candlestick_ohlc(ax, arr, width=0.4, alpha=1, colordown='#53c156', colorup='#ff1717') locs, labels = plt.xticks() plt.setp(labels, rotation=45) plt.grid() ax.legend(loc='best', prop={'size': fontsize}) title_name = signal + '_' + rule ax.set_title(title_name) fig.subplots_adjust(bottom=0.25) name = signal + '_' + rule plt.savefig(name) plt.show()
def prepare(self, chart_data): # Initialize the canvas and prepare to draw 4 charts self.fig, self.axes = plt.subplots(nrows=4, ncols=1, facecolor='w', sharex=True) for ax in self.axes: # Disable scientific notations that are hard to read ax.get_xaxis().get_major_formatter().set_scientific(False) ax.get_yaxis().get_major_formatter().set_scientific(False) # Chart 1. Daily Chart self.axes[0].set_ylabel('Env.') # y 축 레이블 표시 # Volume visualization x = np.arange(len(chart_data)) volume = np.array(chart_data)[:, -1].tolist() self.axes[0].bar(chart_data["date"], volume, color='b', alpha=0.3) # ohlc stands for open, high, low and close, it is a two-dimensional array in this order ax = self.axes[0].twinx() ax.set_title("Daily Chart") ohlc = np.hstack((x.reshape(-1, 1), np.array(chart_data)[:, 1:-1])) # Bar chart output to self.axes [0] # Positive chart is in red, negative chart is in blue candlestick_ohlc(ax, ohlc, colorup='r', colordown='b')
def graph_main_old(tag_df, start='2017-09-01', code=None): data = get_stock_data2(tag_df, start) # 将数据导入数据库 #df_in_db(data, code) with open('./dataSets/data.temp', 'wb') as f: f.write(pickle.dumps([data, code])) prices = data[['open', 'high', 'low', 'close']] prices_lst = prices.values.tolist() prices_lst.reverse() prices = pd.DataFrame(prices_lst, columns=['open', 'high', 'low', 'close']) dates = data['date_time'].apply( lambda x: datetime.datetime.strftime(x, "%Y-%m-%d")) candleData = np.column_stack([list(range(len(dates))), prices]) fig = plt.figure(figsize=(10, 6)) ax = fig.add_axes([0.1, 0.3, 0.8, 0.6]) ax.xaxis.set_major_locator(ticker.MultipleLocator(1)) #ax.set_xticklabels(dates, rotation=45) ax.grid(True, linestyle='-.') mpf.candlestick_ohlc(ax, candleData, width=0.5, colorup='r', colordown='b') plt.savefig('./static/images/test.png') #plt.show() return labels_util(dates, candleData), code
def matplotRealTime(i): ohlc = [] endTime = time.time() dataCandle = login.get_candles('EURUSD', 60, 100, endTime) dataIndex = 1 if len(dataCandle) > 0: for data in dataCandle: candleData = dataIndex, data['open'], data['max'], data[ 'min'], data['close'], data['volume'] ohlc.append(candleData) dataIndex += 1 ax1.clear() ax1.grid(True) plt.xlabel('Date') plt.ylabel('Price') plt.title("IQ OPTION") candlestick_ohlc(ax1, ohlc, width=0.4, colorup='#77d879', colordown='#db3f3f')
def drop_k(symbol): #获取数据,并将日期类型转换为matplotlib日期 data = nasdaq_mysql.getData(symbol) new_data = [] for row in data: row = list(row) row[0] = mdata.date2num(datetime.strptime(str(row[0]), "%Y-%m-%d")) new_data.append(row) #创建子图,得到一个二元组,图表对象和坐标轴对象 fig, ax = plt.subplots(figsize=(10, 5)) #调整子图参数,bottom是设置图表到底部的距离 fig.subplots_adjust(bottom=0.2) plt.ylabel('股价(元)') plt.xlabel('时间') plt.title('股票代码:{0}近三个月历史记录'.format(symbol)) mpl.candlestick_ohlc(ax, new_data, width=1.0, colorup='r', colordown='g') #设置坐标轴属性 ax.xaxis_date() #日期类型 plt.xticks(rotation=45) #显示刻度值旋转45度 plt.savefig('股票K线图.png') plt.show()
def get_plot_candlesticks_dataframe(data_frame, ax): candlestick_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, _): try: return xdate[int(x)] except IndexError: return '' ax.xaxis.set_major_formatter(ticker.FuncFormatter(get_date))
def draw_candlestick(): index = np.arange(5) columns = np.array(['date', 'open', 'high', 'low', 'close']) datas = [ (0, 12, 14, 12, 12.5), (1, 12, 14, 12, 12.5), (2, 12, 14, 12, 12.5), (3, 12, 14, 12, 12.5), (4, 12, 14, 12, 12.5), ] df = pd.DataFrame(datas, index=index, columns=columns) df = df.as_matrix() print(df) fig, ax = plt.subplots() # ax.xaxis_date() plt.xticks(rotation=45) mpf.candlestick_ohlc(ax, df, width=1.0, colorup='r', colordown='green', alpha=1) ##设置利用mpf画股票K线图 date_tickers = ['20190101', '20190102', '20190103', '20190104', '20190105'] ax.set_xticks(range(len(date_tickers))) ax.set_xticklabels(date_tickers) ax.set_xticklabels(date_tickers) plt.show() return False
def gett(): #button(确定) #股票代码 w.start() plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False dailyQuota = w.wsd(aa, "open,high,low,close", statime, endtime, "Fill=Previous") print(dailyQuota.Times) print(len(dailyQuota.Data)) tupleQuota = [] for i in range(len(dailyQuota.Data[0])): tupleQuota.append((dailyQuota.Times[i].toordinal(), dailyQuota.Data[0][i], dailyQuota.Data[1][i], dailyQuota.Data[2][i], dailyQuota.Data[3][i])) print(tupleQuota) mondayFormatter = DateFormatter('%Y-%m-%d') fig, ax = plt.subplots() ax.xaxis.set_major_formatter(mondayFormatter) candlestick_ohlc(ax, tupleQuota, width=0.4, colorup='r', colordown='g') plt.xticks(rotation=30) plt.title(aa) plt.show()
def plt_chart_atr(chart, path=os.path.join(os.getcwd(), "tmp")): df_tmp_full = chart.sort_values(by=["date"], ascending=True) df_tmp = df_tmp_full.ix[:, [ 'open_price', 'close_price', 'high_price', 'low_price' ]] move_avrg_lst = [5, 10, 20, 40, 80] fig = plt.figure() ax = plt.subplot() xdate = [x for x in df_tmp_full.date] # 日付 ochl = np.vstack((date2num(xdate), df_tmp.values.T)).T # mpf.candlestick_ochl(ax, ochl, width=0.7, colorup='g', colordown='r') candlestick_ohlc(ax1, ochl, width=0.7, colorup='g', colordown='r') ax.grid() # グリッド表示 ax.set_xlim(df_tmp_full.iloc[0].date, df_tmp_full.iloc[-1].date) # x軸の範囲 fig.autofmt_xdate() # x軸のオートフォーマット plt.plot(df_tmp_full["date"], df_tmp_full["atr"], label="atr") plt.legend() plt.savefig(os.path.join(path, chart["stock_id"].values[0] + '_chart.png')) #画像保存
def plot_candlestick(df, ax=None, fmt="%Y-%m-%d"): if ax is None: fig, ax = plt.subplots() idx_name = df.index.name print(idx_name) dat = df.reset_index()[[idx_name, "Open", "High", "Low", "Close"]] dat[df.index.name] = dat[df.index.name].map(mdates.date2num) ax.xaxis_date() ax.xaxis.set_major_formatter(mdates.DateFormatter(fmt)) plt.xticks(rotation=45) _ = candlestick_ohlc(ax, dat.values, width=.6, colorup='g', alpha=1) ax.set_xlabel(idx_name) ax.set_ylabel("OHLC") return ax
def draw_k(hist_data): data_list = [] for dates, row in hist_data.iterrows(): date_time = datetime.datetime.strptime(dates, '%Y-%m-%d') t = date2num(date_time) open, high, close, low = row[:4] datas = (t, open, high, low, close ) # tushare里的数据顺序为open,high,close,low注意 data_list.append(datas) fig, ax = plt.subplots(figsize=(16, 10)) fig.subplots_adjust(bottom=0.2) mpf.candlestick_ohlc(ax, data_list, width=1.5, colorup='r', colordown='green') plt.grid() ax.xaxis_date() ax.autoscale_view() plt.setp(plt.gca().get_xticklabels(), rotation=30) plt.show()
def plot_stock(self, k_data): from mpl_finance import candlestick_ohlc self.priceMax = k_data.high.values.max() self.dateMin = k_data.time.values.min() self.dateMax = k_data.time.values.max() candlestick_ohlc(self.price_ax, k_data.values, width=1.0, colorup='r', colordown='g') self.price_ax.plot(k_data.time, k_data['uprice'], 'b', label="无穷成本均线", linewidth=1) self.price_ax.set_ylabel("prices") self.price_ax.yaxis.label.set_color('k') self.price_ax.set_xlim(self.dateMin, self.dateMax) self.price_ax.set_ylim(self.priceMin, self.priceMax) self.price_ax.xaxis.set_major_locator(mticker.MultipleLocator(250)) self.price_ax.xaxis.set_major_formatter( mticker.FuncFormatter(self.format_date)) self.price_ax.grid(True, color='k', linestyle='--')
def plot(): plt.style.use('ggplot') data = pd.read_csv("NVDA.csv") data = data.loc[:, ['Date', 'Open', 'High', 'Low', 'Close']] data['Date'] = pd.to_datetime(data['Date']) data['Date'] = data['Date'].apply(mpl_dates.date2num) data = data.astype(float) # Creating Subplots fig, ax = plt.subplots() candlestick_ohlc(ax, data.values, width=0.6, colorup='green', colordown='red', alpha=0.8) # Setting labels & titles ax.set_xlabel('Date') ax.set_ylabel('Price') fig.suptitle('NVIDIA STOCK PRICE CANDLESTICK CHART') # Formatting Date date_format = mpl_dates.DateFormatter('%d-%m-%Y') ax.xaxis.set_major_formatter(date_format) fig.autofmt_xdate() fig.tight_layout() plt.show()
def plot(self, start_date, end_date, index_code): df, index_data = self.get_data(start_date, end_date, index_code) date_tickers = index_data.date.tolist() def _format_date(x, pos=None): if x < 0 or x > len(date_tickers) - 1: return '' return date_tickers[int(x)] info = self.compute_stock_score(df) candlestick_ohlc(self.price_ax, index_data.values, width=1.0, colorup='r', colordown='g') self.ratio_ax.plot(info['date'], info['rate'], 'r', label="超跌系数", linewidth=1) self.price_ax.xaxis.set_major_locator(mticker.MultipleLocator(20)) self.price_ax.xaxis.set_major_formatter( mticker.FuncFormatter(_format_date)) plt.show()
def prepare(self, chart_data): # 캔버스를 초기화하고 4개의 차트를 그릴 준비 self.fig, self.axes = plt.subplots(nrows=4, ncols=1, facecolor='w', sharex='all') for ax in self.axes: # 보기 어려운 과학적 표기 비활성화 ax.get_xaxis().get_majer_formatter().set_scientific(False) ax.get_yaxis().get_major_formatter().set_scientific(False) # 차트 1. 일봉 차트 self.axes[0].set_ylabel('Env.') # y 축 레이블 표시 # 거래량 가시화 x = np.arange(len(chart_data)) volume = np.array(chart_data)[:, -1].tolist() self.axes[0].bar(x, volume, color='b', alpha=0.3) # ohlc 란 open, high, low, close 의 약자로 이 순서로 구성된 2차원 배열 ax = self.axes[0].twinx() ohlc = np.hstack((x.reshape(-1, 1), np.array(chart_data)[:, 1:-1])) # self.axes[0]에 봉 차트 출력 # 양봉은 빨간색으로, 음봉은 파란색으로 표시 candlestick_ohlc(ax, ohlc, colorup='r', colordown='b')
def showStock(stock): df = pd.read_csv(stock + '.csv', parse_dates=True, index_col=0) df['100ma'] = df['Adj Close'].rolling(window=100, min_periods=0).mean() df_ohlc = df['Adj Close'].resample('10D').ohlc() df_volume = df['Volume'].resample('10D').sum() df_ohlc.reset_index(inplace=True) df_ohlc['Date'] = df_ohlc['Date'].map(mdates.date2num) ax1 = plt.subplot2grid((6, 1), (0, 0), rowspan=5, colspan=1) ax2 = plt.subplot2grid((6, 1), (5, 0), rowspan=1, colspan=1, sharex=ax1) ax1.xaxis_date() candlestick_ohlc(ax1, df_ohlc.values, width=2, colorup='g') ax2.fill_between(df_volume.index.map(mdates.date2num), df_volume.values, 0) #ax1.plot(df.index, df['Adj Close']) #ax1.plot(df.index, df['100ma']) #ax2.bar(df.index, df['Volume']) plt.show()
def candle_plot_time_series(self, scrip_code, df, recent=0, show=True, save=True): Validator.validate_attribute(recent, int, True) count, steps, dfmt = self.__plot_params(df, recent) figure, axis = plt.subplots(figsize=(16, 8)) # create a copy of the DataFrame to operate on dohlc = df.tail(count).copy() # take the index back to column dohlc.reset_index(inplace=True) # drop the closed price column, adj.closed price will be considered dohlc.drop('Close', axis=1, inplace=True) # convert the datetime format to short string format dohlc.Date = dohlc.Date.apply(DateTime.dateformatter_short) # get hold of dates for title naming str_dates = dohlc.Date # convert the string dates to pandas TimeStamp values dohlc.Date = pd.to_datetime(dohlc.Date, format='%d-%m-%Y') # convert the pandas TimeStamp values to matplotlib float values dohlc.Date = dohlc.Date.apply(mdates.date2num) candlestick_ohlc(ax=axis, quotes=dohlc.values, width=0.6, colorup='green', colordown='red', alpha=0.7) axis.xaxis.set_major_formatter(mdates.DateFormatter(dfmt)) axis.set_xticks(dohlc.Date[::-steps]) plt.setp(plt.gca().get_xticklabels(), rotation=90) start_date = str_dates.iloc[0] end_date = str_dates.iloc[-1] plt.title(scrip_code + ' (' + start_date + ' to ' + end_date + ')') plt.tight_layout() self.__show_and_save(plt, show, save, 'candlesticks.png')
def plt_chart_w_rsi(self, path=os.path.join(os.getcwd(), "chart")): real_id_lst = self.df["stock_id"].drop_duplicates() for id_str in real_id_lst: df_tmp_full = self.df[self.df.stock_id == id_str].sort_values( by=["date"], ascending=True) df_tmp = df_tmp_full.ix[:, [ 'open_price', 'high_price', 'low_price', 'close_price' ]] fig = plt.figure() ax1 = plt.subplot(211) ax2 = plt.subplot(212) xdate = [x for x in df_tmp_full.date] # 日付 ochl = np.vstack((date2num(xdate), df_tmp.values.T)).T # mpf.candlestick_ochl(ax1, ochl, width=0.7, colorup='g', colordown='r') candlestick_ohlc(ax1, ochl, width=0.7, colorup='g', colordown='r') ax1.grid() # グリッド表示 ax1.set_xlim(df_tmp_full.iloc[0].date, df_tmp_full.iloc[-1].date) # x軸の範囲 fig.autofmt_xdate() # x軸のオートフォーマット close_price_lst = df_tmp_full["close_price"].values.flatten() ax2.grid() # グリッド表示 ax2.set_xlim(df_tmp_full["date"].values[0], df_tmp_full["date"].values[-1]) # x軸の範囲 fig.autofmt_xdate() # x軸のオートフォーマット plt.plot(df_tmp_full["date"].values, df_tmp_full["rsi"].values, label="rsi_14") plt.legend() if not os.path.isdir(path): os.makedirs(path) plt.savefig(os.path.join(path, str(id_str) + '_chart_w_rsi.png')) #画像保存
def candlestick(comp_name, filter_data, cmp_tick, from_date_s, to_date_s): #sort data into open, high, low, close format filter_prices = filter_data.loc[:, ["Open", "High", "Low", "Close"]] #Reset index to get dates as a seperate column filter_prices = filter_prices.reset_index() #conver date to numbers filter_prices['Date'] = filter_prices['Date'].apply(mpl_dates.date2num) #convert to float filter_prices = filter_prices.astype(float) #Create subplot graph, plot = plt.subplots(2, sharex=True, figsize=(15, 6)) #create candle stick graph on plot candlestick_ohlc(plot[0], filter_prices.values, width=0.3, colorup="green", colordown="red") #convert number back to dates dates_from_num = mpl_dates.DateFormatter('%d-%m-%Y') graph.suptitle( "Candlestick graph v/s Volume for {} -> {} from {} - {}".format( cmp_tick, comp_name, from_date_s, to_date_s)) plot[0].set_title("Candlestick Graph") plot[0].xaxis.set_major_formatter(dates_from_num) plot[0].set_ylabel("Stock Price") plot[1].set_title("Volume") plot[1].bar(filter_data.index, filter_data.Volume) plot[1].set_xlabel("Time") plot[1].set_ylabel("Volume") plt.show()
def draw_candlestick_on_ax(ax, stock_code, key_type, need_update, key_count=73): key_quotes, date_quotes, low_quotes, high_quotes = klinedata.load_klinedata( stock_code, key_type, need_update, key_count) mpf.candlestick_ohlc(ax, key_quotes, colordown='#53c156', colorup='#ff1717', width=0.2, alpha=1) #colordown='#F5F5F5', colorup='#DCDCDC' # #https://matplotlib.org/examples/pylab_examples/date_index_formatter.html class MyFormatter(ticker.Formatter): def __init__(self, fmt='%Y-%m-%d %H:%M'): self.fmt = fmt def __call__(self, x, pos=0): #x就是x轴的刻度数值,但是是浮点数 if x < 0 or x >= len(date_quotes): return '' # slice seconds return date_quotes[int(x)][:-3] if date_quotes[int( x)][-3:-2] == ':' else date_quotes[int(x)] # set xaxix format formatter = MyFormatter(date_quotes) ax.xaxis.set_major_formatter(formatter) ax.xaxis.set_major_locator(ticker.MultipleLocator(len(date_quotes) // 4)) # 根据数据量控制间隔 for label in ax.get_xticklabels(): label.set_horizontalalignment('center') add_guides(stock_code, key_type, low_quotes, high_quotes)
def candleVolume(seriesData,candletitle='a',bartitle='b'): Date=[date2num(date) for date in seriesData.index] seriesData.index=list(range(len(Date))) seriesData['Date']=Date listData=zip(seriesData.Date,seriesData.Open,seriesData.High,seriesData.Low, seriesData.Close) ax1 = plt.subplot(211) ax2 = plt.subplot(212) for ax in ax1,ax2: mondays = WeekdayLocator(MONDAY) weekFormatter = DateFormatter('%m/%d/%Y') ax.xaxis.set_major_locator(mondays) ax.xaxis.set_minor_locator(DayLocator()) ax.xaxis.set_major_formatter(weekFormatter) ax.grid(True) ax1.set_ylim(seriesData.Low.min()-2,seriesData.High.max()+2) ax1.set_ylabel('蜡烛图及收盘价线') candlestick_ohlc(ax1,listData, width=0.7,colorup='r',colordown='g') plt.setp(plt.gca().get_xticklabels(),\ rotation=45,horizontalalignment='center') ax1.autoscale_view() ax1.set_title(candletitle) ax1.plot(seriesData.Date,seriesData.Close,\ color='black',label='收盘价') ax1.legend(loc='best') ax2.set_ylabel('成交量') ax2.set_ylim(0,seriesData.Volume.max()*3) ax2.bar(np.array(Date)[np.array(seriesData.Close>=seriesData.Open)] ,height=seriesData.iloc[:,4][np.array(seriesData.Close>=seriesData.Open)] ,color='r',align='center') ax2.bar(np.array(Date)[np.array(seriesData.Close<seriesData.Open)] ,height=seriesData.iloc[:,4][np.array(seriesData.Close<seriesData.Open)] ,color='g',align='center') ax2.set_title(bartitle) return(plt.show())
def getcandlestick(stock): data = get_history(symbol=stock, start=date.today() - relativedelta(months=+3), end=date.today()) data = data.reset_index() data = data[['Date', 'Open', 'High', 'Low', 'Close']] #visualization plt.style.use('ggplot') ohlc = data ohlc['Date'] = pd.to_datetime(ohlc['Date']) ohlc['Date'] = ohlc['Date'].apply(mpl_dates.date2num) ohlc = ohlc.astype(float) fig, ax = plt.subplots() candlestick_ohlc(ax, ohlc.values, width=0.6, colorup='green', colordown='red', alpha=0.8) # Setting labels & titles ax.set_xlabel('Date') ax.set_ylabel('Price') fig.suptitle('Daily Candlestick Chart of ' + stock) # Formatting Date date_format = mpl_dates.DateFormatter('%d-%m-%Y') ax.xaxis.set_major_formatter(date_format) fig.autofmt_xdate() fig.tight_layout() #mean #ohlc['SMA5'] = ohlc["Close"].rolling(5).mean() #ax.plot(ohlc['Date'], ohlc['SMA5'], color = 'green', label = 'SMA5') plt.savefig('./media/candlestick.png', dpi=100, bbox_inches='tight')
def do_ml(ticker): X, y, df = extract_featuresets(ticker, day_range) X_train, X_test, y_train, y_test = cross_validation.train_test_split( X, y, test_size=0.75) # clf = neighbors.KNeighborsClassifier() clf = VotingClassifier([('lsvc', svm.LinearSVC()), ('knn', neighbors.KNeighborsClassifier()), ('rfor', RandomForestClassifier())]) clf.fit(X_train, y_train) confidence = clf.score(X_test, y_test) print('Accuracy:', confidence) predictions = clf.predict(X_test) print('Predicted spread:', Counter(predictions)) df = pd.read_csv('stock_dfs/{}.csv'.format(ticker), parse_dates=True, index_col=0) # df['100ma'] = df['Adj Close'].rolling(window=100, min_periods=0).mean() df_ohlc = df['Adj Close'].resample('10D').ohlc() df_volume = df['Volume'].resample('10D').sum() df_ohlc.reset_index(inplace=True) df_ohlc['Date'] = df_ohlc['Date'].map(mdates.date2num) ax1 = plt.subplot2grid((6, 1), (0, 0), rowspan=5, colspan=1) ax2 = plt.subplot2grid((6, 1), (5, 0), rowspan=1, colspan=1, sharex=ax1) ax1.xaxis_date() candlestick_ohlc(ax1, df_ohlc.values, width=2, colorup='g', colordown='r', alpha=0.75) ax2.fill_between(df_volume.index.map(mdates.date2num), df_volume.values, 0) plt.show() return confidence
def plot(self, n=50): m = len(self.date) if m == 0: print('Markets.plot: No values saved, not posible to plot!') return elif m < n: n = m # Create figure fig, ax = plt.subplots() # Create subplot up ax = plt.subplot(211) # Candlestick plot quotes = [ tuple([ self.date[i], self.open[i], self.high[i], self.low[i], self.close[i] ]) for i in range(m - n, m) ] candlestick_ohlc(ax, quotes, width=0.6) # Value plot plt.plot(self.date[m - n:m + 1], self.value[m - n:m + 1], 'y') plt.ylabel('Value') plt.title(self.name + ': CandleSticks-Value') ax.xaxis.set_major_formatter(DateFormatter('')) ax.grid(True) # Create subplot down ax = plt.subplot(212) # Volume plot plt.bar(self.date[m - n:m + 1], self.volume[m - n:m + 1], 0.6) plt.ylabel('Volume') plt.title(self.name + ': Volume') ax.xaxis.set_major_formatter(DateFormatter('%b %d, %y')) ax.grid(True) # Format date, layout and print fig.autofmt_xdate() fig.tight_layout() plt.show()
def stockPricePlot(code,start_date,date): pro = ts.pro_api('5d9ec9dc6d71031a48a24b0e0f6c87e84fd2caf6bf15ac5845df7177') #token可以在新版tushare的网站上找到 history = pro.query('daily', ts_code = code, start_date = start_date, end_date = date) history = history[::-1].reset_index() print(history.head()) # 获取股票列表 stocklist = getlist() name = [] print('stocklist:', len(stocklist)) if code in stocklist.keys(): name = stocklist[code] print('name', name) # 2. 数据操作 close = history[['close','open']] # 将索引时间变成数据的一部分 close.dropna(inplace=True) date_tickers = history['trade_date'] date_tickers = np.array(date_tickers.values) # 变成时间戳 ohlc = history[['open','high','low','close']] ohlc.reset_index() ohlc['date'] = ohlc.index # 将索引时间变成数据的一部分 ohlc = ohlc.dropna() #print(ohlc) # 3. 画图 k线图candle stick plot,散点图 scatter plot, # 3.1 散点图 2行1列的图,散点图从0,0开始,占一行一列 x是tradedate,y是close,蓝色的 print(close[0:5],ohlc[0:5]) subplot1 = plt.subplot2grid((2,1),(0,0),rowspan=1,colspan=1) # x轴变成date #subplot1.xaxis_date() subplot1.plot(date_tickers,close['open'],'black') tick_spacing = 1 tick_spacing = 7 subplot1.xaxis.set_major_locator(ticker.MultipleLocator(tick_spacing)) plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False plt.title('\"'+code+'-'+str(name[0])+u'\"的股票历史记录 ') # 3.2 k线图 为了在放大K线图的时候放大散点图,要共享x轴 subplot2 = plt.subplot2grid((2,1),(1,0),rowspan=1,colspan=1,sharex=subplot1) a = mpf.candlestick_ohlc(ax=subplot2,quotes=ohlc[['date','open','high','low','close']].values,width=0.7,colorup='r',colordown='green', alpha=1) plt.savefig('D:/software/python/project/stock/learn_envs/bishe_inter/result/history.png') plt.show()
# (Year, month, day) tuples suffice as args for quotes_historical_yahoo date1 = (2004, 2, 1) date2 = (2004, 4, 12) mondays = WeekdayLocator(MONDAY) # major ticks on the mondays alldays = DayLocator() # minor ticks on the days weekFormatter = DateFormatter('%b %d') # e.g., Jan 12 dayFormatter = DateFormatter('%d') # e.g., 12 quotes = quotes_historical_yahoo_ohlc('INTC', date1, date2) if len(quotes) == 0: raise SystemExit fig, ax = plt.subplots() fig.subplots_adjust(bottom=0.2) ax.xaxis.set_major_locator(mondays) ax.xaxis.set_minor_locator(alldays) ax.xaxis.set_major_formatter(weekFormatter) #ax.xaxis.set_minor_formatter(dayFormatter) #plot_day_summary(ax, quotes, ticksize=3) candlestick_ohlc(ax, quotes, width=0.6) ax.xaxis_date() ax.autoscale_view() plt.setp(plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right') plt.show()
import datetime as dt import matplotlib.pyplot as plt from matplotlib import style import pandas as pd import pandas_datareader.data as web from mpl_finance import candlestick_ohlc import matplotlib.dates as mdates pd.set_option('display.expand_frame_repr', False) style.use('ggplot') df = pd.read_csv('TSLA.csv', parse_dates=True, index_col=0) df_ohlc = df['Close'].resample('10D').ohlc() df_volume = df['Volume'].resample('10D').sum() df_ohlc = df_ohlc.reset_index() df_ohlc['Date'] = df_ohlc['Date'].map(mdates.date2num) print (df_ohlc.tail()) ax1 = plt.subplot2grid((6,1), (0,0), rowspan=5, colspan=1) ax2 = plt.subplot2grid((6,1), (5,0), rowspan=1, colspan=1,sharex=ax1) candlestick_ohlc(ax1, df_ohlc.values, width=2, colorup='g') ax2.fill_between(df_volume.index.map(mdates.date2num),df_volume.values,0) plt.show()
def plot(startday, islog = False): columns = ['date','open','high','low','close','unknown','volume'] filename_full = 'data/'+symbol+'_full_'+contractType+'_future.csv' filename_matrix = 'data/'+symbol+'_matrix_full_'+contractType+'_future.csv' filename_pred = 'data/'+symbol+'_pred_'+contractType+'_future.csv' filename_back = 'data/'+symbol+'_back_'+contractType+'_future.csv' filename_fulltemp = 'data/'+symbol+'_fulltemp_'+contractType+'_future.csv' filename_matrix_temp = 'data/'+symbol+'_matrix_fulltemp_'+contractType+'_future.csv' now = datetime.now() now = time.mktime(now.timetuple()) if os.path.exists(filename_full): with open(filename_full, 'r') as f: df = pd.read_csv(f,header=0, index_col=0, sep ='\t') with open(filename_pred,'r') as f_pred: df_pred = pd.read_csv(f_pred, header=0, index_col=0, sep='\t') with open(filename_matrix,'r') as f_matrix: df_matrix = pd.read_csv(f_matrix, header = 0,index_col=0,sep='\t') with open(filename_back,'r') as f_back: df_back = pd.read_csv(f_back, header = 0,index_col=0,sep='\t') with open(filename_fulltemp,'r') as f_temp: df_concat = pd.read_csv(f_temp, header = 0,index_col=0,sep='\t') with open(filename_matrix_temp,'r') as f_matrix_temp: df_matrix_temp = pd.read_csv(f_matrix_temp, header = 0,index_col=0,sep='\t') df = df.drop(['unknown'],axis = 1) df_pred = df_pred.fillna(0) df_back = df_back.fillna(0) # df_matrix_temp = df_matrix_temp.fillna(0) df_matrix_temp['flag'] = df_matrix_temp['flag'].apply(lambda x:x*1.1) df_matrix_temp['date1'] = df_matrix_temp['date'] df_back['shortposition'] = df_back['shortposition'].apply(lambda x:-x) df['date'] = df['date'].apply(lambda x:mdates.date2num(datetime.fromtimestamp(x))) df_matrix['date'] = df_matrix['date'].apply(lambda x:mdates.date2num(datetime.fromtimestamp(x))) df_pred['date'] = df_pred['date'].apply(lambda x:mdates.date2num(datetime.fromtimestamp(x))) df_back['date'] = df_back['date'].apply(lambda x:mdates.date2num(datetime.fromtimestamp(x))) df_concat['date'] = df_concat['date'].apply(lambda x:mdates.date2num(datetime.fromtimestamp(x))) df_matrix_temp['date'] = df_matrix_temp['date'].apply(lambda x:mdates.date2num(datetime.fromtimestamp(x))) #df['date'] = pd.to_datetime(df['date']) #df['date'] = pd.to_datetime(df['date']) #df['date'] = df['date'].values.astype('float64') #df['date'].astype('float64')#['date'].apply(lambda x:np.ndarray.astype(x/1000)) ohlc = [tuple(x) for x in df_concat.to_records(index=False)] ohlc = ohlc[::5] #fig = plt.figure() ax1 = plt.subplot2grid((9,1), (0,0), rowspan = 5) plt.ylabel('Price') plt.title('BTC_future_next_quarter') candlestick_ohlc(ax1, ohlc, width=0.0004, colorup='#77d879', colordown='#db3f3f') xrange1 = mdates.date2num(datetime.fromtimestamp(now-startday*24*3600)) xrange2 = mdates.date2num(datetime.fromtimestamp(now+0.5*24*3600)) ax1.scatter('date', 'longposition',color='purple',s = 0.18, data=df_back,label = 'long-pos') ax1.scatter('date', 'shortposition',color='black',s = 0.18, data=df_back,label = 'short-pos') ax1.set_xlim(xrange1, xrange2) price_low = df_matrix_temp['close'][df_matrix_temp['date1'].searchsorted(now-startday*24*3600)[0]:].min()*(1-0.08) price_high = df_matrix_temp['close'][df_matrix_temp['date1'].searchsorted(now-startday*24*3600)[0]:].max()*(1+0.08) ax1.set_ylim(price_low, price_high) ax1.xaxis.set_major_formatter(mdates.DateFormatter('%m-%d %H:%M')) ax1.xaxis.set_major_locator(mticker.MaxNLocator(15)) ax1.xaxis.set_minor_locator(mticker.MaxNLocator(5)) ax1.legend(loc='best',prop={'size':10}) ax1.grid(True) ax2 = plt.subplot2grid((9,1), (5,0), rowspan = 1, sharex = ax1) ax2.scatter('date', 'flag', color='red',s=0.1,data=df_matrix_temp,label='history') for model in models: ax2.plot('date', 'prob_'+model, linewidth = 0.4,data=df_pred,label='prediction_'+model) ax2.set_xlim(xrange1, xrange2) ax2.set_ylim(-1.25,1.25) ax2.legend(loc='best',prop={'size':6}) ax2.grid(True) ax3 = plt.subplot2grid((9,1), (6,0), rowspan = 3, sharex = ax1) ax3.plot('date','btc_spot_back',data=df_back,label='spot_back') ax3.plot('date','btc_spot_hist',data=df_back,label='spot_history') ax3.plot('date','btc_future_back_RF',data=df_back,label='future_back_RF') ax3.plot('date','btc_future_back_XGB',data=df_back,label='future_back_XGB') ax3.plot('date','btc_future_hist',data=df_back,label='future_history') ax3.set_xlim(xrange1, xrange2) ax3.legend(loc='best',prop={'size':8}) if islog: ax3.set_yscale('log') ax3.grid(True) for label in ax3.xaxis.get_ticklabels(): label.set_rotation(45) plt.xlabel('Date') plt.setp(ax1.get_xticklabels(), visible=False) plt.setp(ax2.get_xticklabels(), visible=False) #plt.setp(ax3.get_xticklabels(), visible=False) #plt.legend() plt.subplots_adjust(left=0.09, bottom=0.2, right=0.94, top=0.90, wspace=0.12, hspace=0) #plt.show() plt.savefig('data/figure.png')