def sample_513(): """ 5.1.3 k线图的绘制 :return: """ import matplotlib.finance as mpf __colorup__ = "red" __colordown__ = "green" # 为了示例清晰,只拿出前30天的交易数据绘制蜡烛图, tsla_part_df = tsla_df[:30] fig, ax = plt.subplots(figsize=(14, 7)) qutotes = [] for index, (d, o, c, h, l) in enumerate( zip(tsla_part_df.index, tsla_part_df.open, tsla_part_df.close, tsla_part_df.high, tsla_part_df.low)): # 蜡烛图的日期要使用matplotlib.finance.date2num进行转换为特有的数字值 d = mpf.date2num(d) # 日期,开盘,收盘,最高,最低组成tuple对象val val = (d, o, c, h, l) # 加val加入qutotes qutotes.append(val) # 使用mpf.candlestick_ochl进行蜡烛绘制,ochl代表:open,close,high,low mpf.candlestick_ochl(ax, qutotes, width=0.6, colorup=__colorup__, colordown=__colordown__) ax.autoscale_view() ax.xaxis_date() plt.show()
def dataframe2quote(data): quote = [] for i in range(data.shape[0]): d = data.iloc[i] time = date2num(data.index[i]) quote.append((i, d.open, d.highest, d.lowest, d.close, d.turnoverValue)) return quote
def loadStockQuotes(symbol, dates): col_names = ['Open', 'Close', 'High', 'Low'] df = load_OHLCV(symbol, dates, column_names=col_names, base_dir=DIR_SEC_CSV) # quotes = [ (date, open, close, high, low), .....] quotes = df.to_records(convert_datetime64=True).tolist() quotes = [(date2num(d), o, c, h, l) for d, o, c, h, l in quotes] return quotes
def loadStockQuotes(symbol, startdate, enddate): #[ (Date, Open, High, Low, Close, Adj Close, Volume), .....] df = load_OHLCV(symbol, startdate, enddate) #quotes = [ (date, open, close, high, low), .....] quotes = df.to_records(convert_datetime64=True).tolist() quotes = [ (date2num(d), o, h, l, c) for d, o, h, l, c, adj, v in quotes ] return quotes
def loadStockQuotes(symbol, dates): col_names=['<OPEN>', '<CLOSE>', '<HIGH>', '<LOW>'] df = load_OHLCV(symbol, dates, column_names=col_names, base_dir=default_path) #quotes = [ (date, open, close, high, low), .....] quotes = df.to_records(convert_datetime64=True).tolist() quotes = [ (date2num(d), o, c, h, l) for d,o,c,h,l in quotes ] return quotes
def import_stock_data_from_zszq(self, path, identifier): # This method loads trading data of a specified stock from Zhaoshang Securities data # path of the data source if path[-1] == "/": path = path + identifier + ".txt" else: path = path + "/" + identifier + ".txt" # read data if os.path.isfile(path): file_input = codecs.open(path, "r", "gbk").readlines() else: raise IOError("File Not Found.") # header - id, stock name ##header1 = input[0].split(" ") # header - date, open, highest, lowest, close, volume, total header2 = file_input[1].split("\t") # price data prices = file_input[2:-1] header = {} # header indices for x in header2: if codecs.encode(x.strip(), "gbk") == codecs.encode("日期", "gbk"): header["date"] = header2.index(x) elif codecs.encode(x.strip(), "gbk") == codecs.encode("开盘", "gbk"): header["open"] = header2.index(x) elif codecs.encode(x.strip(), "gbk") == codecs.encode("最高", "gbk"): header["highest"] = header2.index(x) elif codecs.encode(x.strip(), "gbk") == codecs.encode("最低", "gbk"): header["lowest"] = header2.index(x) elif codecs.encode(x.strip(), "gbk") == codecs.encode("收盘", "gbk"): header["close"] = header2.index(x) elif codecs.encode(x.strip(), "gbk") == codecs.encode("成交量", "gbk"): header["volume"] = header2.index(x) elif codecs.encode(x.strip(), "gbk") == codecs.encode("成交额", "gbk"): header["total"] = header2.index(x) # generate price vectors for day in prices: data = day.split("\t") pdate = finance_plot.date2num(datetime.datetime.strptime(data[header["date"]].strip(), "%Y/%m/%d")) popen = float(data[header["open"]].strip()) phighest = float(data[header["highest"]].strip()) plowest = float(data[header["lowest"]].strip()) pclose = float(data[header["close"]].strip()) pvolume = float(data[header["volume"]].strip()) ptotal = float(data[header["total"]].strip()) self.quotes.append([pdate, popen, phighest, plowest, pclose, pvolume, ptotal]) print("Quotes of stock {0} from date {1} to {2} have been loaded".format(identifier, datetime.date.fromordinal(int(self.quotes[0][0])), datetime.date.fromordinal(int(self.quotes[-1][0])))) return 0
def plot_data(): df = pd.read_csv("sp_500_joined.csv") tickers = df.dtypes.index df.fillna(0, inplace=True) val = [] for i in df['Date'][1800:]: val.append(date2num(datetime.datetime.strptime(i, '%Y-%m-%d'))) y = numpy.array(df[tickers[-1]][1800:]) x = numpy.array(val) plt.plot(x, y) plt.show()
def prepare_plot_trade_args(self, trade_idx, preoffset_bars, postoffset_bars): entry_time = self.detailed_results["EntryTime"][trade_idx] entry_idx = self.data[self.data["time"] == entry_time].index.tolist()[0] start_idx = max([0, entry_idx - preoffset_bars]) exit_time = self.detailed_results["ExitTime"][trade_idx] exit_idx = self.data[self.data["time"] == exit_time].index.tolist()[0] end_idx = min([len(self.data), exit_idx + postoffset_bars + 1]) ts = self.ts opens = self.opens highs = self.highs lows = self.lows closes = self.closes d = [(date2num(ts[i]), opens[i], highs[i], lows[i], closes[i]) for i in range(start_idx, end_idx)] position = self.detailed_results["Position"][trade_idx] arrow_color = 'green' if position > 0 else 'red' entry_price = self.detailed_results["EntryPrice"][trade_idx] exit_price = self.detailed_results["ExitPrice"][trade_idx] return (d, self.interval, (date2num(entry_time), entry_price), (date2num(exit_time), exit_price), arrow_color, "Trade #" + str(trade_idx))
def drawData(ohlcv, macd, trade_loop_back, pdays): dif = macd['dif'] dea = macd['dea'] bar = macd['bar'] fig, axs = plt.subplots(nrows=3, ncols=1, facecolor=(0.5, 0.5, 0.5), figsize=(14, 7)) draw1, draw2, draw3 = axs.ravel() # 可视化profit_array draw1.plot(np.array(trade_loop_back.profit_array).cumsum(), label='profit_array') # #print(trade_loop_back.days_array) # #可视化K线和交易日 qutotes = [] for index, (d, o, c, h, l) in enumerate( zip(ohlcv.index, ohlcv.open, ohlcv.close, ohlcv.highest, ohlcv.lowest)): d = mpf.date2num(d) val = (d, o, c, h, l) qutotes.append(val) mpf.candlestick_ochl(draw2, qutotes, width=0.4, colorup="green", colordown="red") #draw2.autoscale_view() #draw2.xaxis_date() act = pdays[(pdays.stock - pdays.shift(1).stock) != 0] # draw2.axvline(np.array([736875, 736876]), label = 'buy', color="green") # for index, line in act[act.stock == 1].date: # draw2.axvline(qutotes[index][0], label = 'buy', color="green") # for index, line in act[act.stock == 0].date: # draw2.axvline(qutotes[index][0], label = 'sell', color="red") # draw2.axvline(np.float32(act[act.stock == 1].date), label = 'buy', color="green") # draw2.axvline(np.float32(act[act.stock == 0].date), label = 'sell', color="red") draw3.plot(ohlcv.index, dif, label='macd dif') draw3.plot(ohlcv.index, dea, label='signal dea') bar_red = np.where(bar > 0, bar, 0) bar_green = np.where(bar < 0, bar, 0) draw3.bar(ohlcv.index, bar_red, facecolor='red', label='hist bar') draw3.bar(ohlcv.index, bar_green, facecolor='green', label='hist bar') draw3.legend(loc='best') plt.show()
def main(): hb = ccxt.huobipro() hb.proxies = { 'http': 'http://127.0.0.1:8123', 'https': 'http://127.0.0.1:8123', } data = hb.fetch_ohlcv('BTC/USDT', '15m') arr = np.array(data) ohlcv = pd.DataFrame(arr, columns=('time', 'open', 'highest', 'lowest', 'close', 'volume')) ohlcv = ohlcv.sort_index(by='time') timeIndex = pd.date_range(time.strftime( '%Y-%m-%d %H:%M:%S', time.localtime(int(ohlcv.head(1).time) / 1000)), periods=ohlcv.shape[0], freq='15m') ohlcv.index = timeIndex dif, dea, bar = talib.MACD(ohlcv.close, fastperiod=12, slowperiod=26, signalperiod=9) fig, axs = plt.subplots(figsize=(14, 7)) #可视化K线和交易日 qutotes = [] for index, (d, o, c, h, l) in enumerate( zip(ohlcv.index, ohlcv.open, ohlcv.close, ohlcv.highest, ohlcv.lowest)): print(d) d = mpf.date2num(d) print(d) val = (d, o, c, h, l) qutotes.append(val) mpf.candlestick_ochl(axs, qutotes, width=1, colorup="green", colordown="red") print(qutotes) axs.autoscale_view() #axs.xaxis_date()#仅日线时使用 plt.show()
def candle_draw(): __colorup__ = "red" __colordown__ = "green" pingan_part_df = pingan_df[:100] fig, ax = plt.subplots(figsize=(14, 7)) qutotes = [] for index, (d, o, c, h, l) in enumerate( zip(pingan_part_df.index, pingan_part_df.OPEN, pingan_part_df.CLOSE, pingan_part_df.HIGH, pingan_part_df.LOW)): d = mpf.date2num(d) # 日期、开盘、收盘、最高、最低组成一个tuple对象val val = (d, o, c, h, l) qutotes.append(val) mpf.candlestick_ochl(ax, qutotes, width=0.6, colorup=__colorup__, colordown=__colordown__) ax.autoscale_view() ax.xaxis_date() plt.grid(True) plt.show()
def _do_plot_candle(date, p_open, high, low, close, volume, view_index, symbol, day_sum, save, minute): """ 绘制不可交互的k线图 param date: 融时间序列交易日时间,pd.DataFrame.index对象 :param p_open: 金融时间序列开盘价格序列,np.array对象 :param high: 金融时间序列最高价格序列,np.array对象 :param low: 金融时间序列最低价格序列,np.array对象 :param close: 金融时间序列收盘价格序列,np.array对象 :param volume: 金融时间序列成交量序列,np.array对象 :param symbol: symbol str对象 :param day_sum: 端线图 matplotlib的版本有些有bug显示不对 :param save: 是否保存可视化结果在本地 :param minute: 是否是绘制分钟k线图 """ # 需要内部import不然每次import abupy都有warning,特别是子进程很烦人 try: # noinspection PyUnresolvedReferences, PyDeprecation import matplotlib.finance as mpf except ImportError: # 2.2 才会有 # noinspection PyUnresolvedReferences, PyDeprecation import matplotlib.mpl_finance as mpf if not g_only_draw_price: # 成交量,价格都绘制 # noinspection PyTypeChecker fig, (ax1, ax2) = plt.subplots(2, sharex=True, figsize=(20, 12)) else: # 只绘制价格 fig, ax1 = plt.subplots(figsize=(6, 6)) if day_sum: # 端线图绘制 qutotes = [] for index, (d, o, c, l, h) in enumerate(zip(date, p_open, close, low, high)): d = index if minute else mpf.date2num(d) val = (d, o, c, l, h) qutotes.append(val) # plot_day_summary_oclh接口,与mpf.candlestick_ochl不同,即数据顺序为开收低高 mpf.plot_day_summary_oclh(ax1, qutotes, ticksize=5, colorup=__colorup__, colordown=__colordown__) else: # k线图绘制 qutotes = [] for index, (d, o, c, h, l) in enumerate(zip(date, p_open, close, high, low)): d = index if minute else mpf.date2num(d) val = (d, o, c, h, l) qutotes.append(val) # mpf.candlestick_ochl即数据顺序为开收高低 mpf.candlestick_ochl(ax1, qutotes, width=0.6, colorup=__colorup__, colordown=__colordown__) if not g_only_draw_price: # 开始绘制成交量 ax1.set_title(symbol) ax1.set_ylabel('ochl') ax1.grid(True) if not minute: ax1.xaxis_date() if view_index is not None: # 开始绘制买入交易日,卖出交易日,重点突出的点位 e_list = date.tolist() # itertools.cycle循环使用备选的颜色 for v, csColor in zip(view_index, itertools.cycle(K_PLT_MAP_STYLE)): try: v_ind = e_list.index(v) except Exception as e: # logging.exception(e) logging.debug(e) # 向前倒一个 v_ind = len(close) - 1 label = symbol + ': ' + str(date[v_ind]) ax1.plot(v, close[v_ind], 'ro', markersize=12, markeredgewidth=4.5, markerfacecolor='None', markeredgecolor=csColor, label=label) # 因为candlestick_ochl 不能label了,所以使用下面的显示文字 # noinspection PyUnboundLocalVariable ax2.plot(v, 0, 'ro', markersize=12, markeredgewidth=0.5, markerfacecolor='None', markeredgecolor=csColor, label=label) plt.legend(loc='best') # 成交量柱子颜色,收盘价格 > 开盘,即红色 # noinspection PyTypeChecker bar_red = np.where(close >= p_open, volume, 0) # 成交量柱子颜色,开盘价格 > 收盘。即绿色 # noinspection PyTypeChecker bar_green = np.where(p_open > close, volume, 0) date = date if not minute else np.arange(0, len(date)) ax2.bar(date, bar_red, facecolor=__colorup__) ax2.bar(date, bar_green, facecolor=__colordown__) ax2.set_ylabel('volume') ax2.grid(True) ax2.autoscale_view() plt.setp(plt.gca().get_xticklabels(), rotation=30) else: ax1.grid(False) if save: # 保存可视化结果在本地 from pylab import savefig save_dir = os.path.join(K_SAVE_CACHE_PNG_ROOT, ABuDateUtil.current_str_date()) png_dir = os.path.join(save_dir, symbol) ABuFileUtil.ensure_dir(png_dir) r_cnt = 0 while True: png_name = '{}{}.png'.format( png_dir, '' if r_cnt == 0 else '-{}'.format(r_cnt)) if not ABuFileUtil.file_exist(png_name): break r_cnt += 1 # noinspection PyUnboundLocalVariable savefig(png_name) fig.clf() plt.close(fig) else: """ save 了就不show了 """ plt.show()
bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.) # 绘制K线图,通过 matplotlib.finance.candlestick_ochl 以及 matplotlib.finance.candlestick2_ohlc 函数 import matplotlib.finance as mpf __colorup__ = "red" __colordown__ = "green" tsla_part_df = tsla_df[:30] fig, ax = plt.subplots(figsize=(14, 7)) quotes = [] for index, (d, o, c, h, l) in enumerate( zip(tsla_part_df.index, tsla_part_df.open, tsla_part_df.close, tsla_part_df.high, tsla_part_df.low)): d = mpf.date2num(d) val = (d, o, c, h, l) quotes.append(val) mpf.candlestick_ochl(ax, quotes, width=0.6, colorup=__colorup__, colordown=__colordown__) ax.autoscale_view() ax.xaxis_date() # 引用 Bokeh 支持交互可视化 from abupy import ABuMarketDrawing ABuMarketDrawing.plot_candle_form_klpd(tsla_df, html_bk=True) # 使用 Pandas 可视化数据
def calcDiscountFactor(self, discount_curve): dates = [date2num(p.EndDate) for p in discount_curve] dfs = [p.DiscountFactor for p in discount_curve] cs = CubicSpline(dates, dfs) self.StartDiscountFactor = cs(date2num(self.StartDate)) self.EndDiscountFactor = cs(date2num(self.EndDate))
def plot_history_day(trade_record, data_financial, pre=50, post=20, save=False, record_index=-1): if not trade_record: raise ValueError('Empty record. %s' % trade_record) symbol = trade_record[0] stock_history = dp.read(config.DATA_PATH_STOCK, symbol) index_history = dp.read(config.DATA_PATH_INDEX_DICT, 'SH#000001') dates = [trade_record[1], trade_record[1], trade_record[1]] stock_history_dates = [r['date'] for r in stock_history] dates_index = [ bisect.bisect_left(stock_history_dates, date) for date in dates ] stock_history_to_plot = stock_history[dates_index[0] - pre:dates_index[-1] + post] index_history_to_plot = [ index_history[r['date']] for r in stock_history_to_plot ] stock_history_dates = [r['date'] for r in stock_history_to_plot] dates_index = [ bisect.bisect_left(stock_history_dates, date) for date in dates ] marker_position = {0: 'open', 1: 'open', 2: 'open'} stock_history_markers = [ stock_history_to_plot[j][marker_position[i]] for i, j in enumerate(dates_index) ] profit = (stock_history_markers[2] / stock_history_markers[1] - 1.0) * 100 hold_time = (dates[2] - dates[1]).days if profit > 0: return plt.rcParams['font.size'] = 15 fig, ax1 = plt.subplots(figsize=(25, 10)) ax1.grid(True) ax1.plot([r['date'] for r in stock_history_to_plot], [r['ma10'] for r in stock_history_to_plot], '--', color='#0094af', alpha=0.7) ax1.plot([r['date'] for r in stock_history_to_plot], [r['ma20'] for r in stock_history_to_plot], '--', color='#434051', alpha=0.7) ax1.plot(dates, stock_history_markers, 'bo', alpha=0.7) quotes = [[ date2num(stock_history_to_plot[i]['date']), stock_history_to_plot[i]['open'], stock_history_to_plot[i]['high'], stock_history_to_plot[i]['low'], stock_history_to_plot[i]['close'], ] for i in range(len(stock_history_to_plot))] ax1.axhline( y=stock_history_to_plot[dates_index[0]]['lo50'], # xmin=stock_history_to_plot[0]['date'], # xmax=stock_history_to_plot[-1]['date'], # color='b', alpha=0.3, linewidth=2) candlestick_ohlc(ax1, quotes, width=0.7, colorup='#d81715', colordown='#0c8731', alpha=0.9) # ax1.set_xlim(dates[0] - datetime.timedelta(days=20), # dates[-1] + datetime.timedelta(days=20)) ax1.set_xlabel('date') # Make the y-axis label, ticks and tick labels match the line color. ax1.set_ylabel('stock price of %s' % stock_history[0]['symbol'], color='k') ax1.tick_params('y', colors='k') horizontal = { 0: dates[0] - datetime.timedelta(days=pre // 3), 1: dates[1] - datetime.timedelta(days=pre // 4), 2: dates[2] - datetime.timedelta(days=(dates[2] - dates[1]).days // 3) } max_price = max([r['close'] for r in stock_history_to_plot]) min_price = min([r['close'] for r in stock_history_to_plot]) vertical = { 0: (max_price - stock_history_markers[0]) / 3 + stock_history_markers[0], 1: (max_price - stock_history_markers[1]) / 2 + stock_history_markers[1], 2: (min_price - stock_history_markers[2]) / 2 + stock_history_markers[2] } # 个股基本面数据全,每股收益大于2毛,ROE大于10%,营收增长大于30%。 stock_basic_info = '' report_index = dp.find_financial_report_index(data_financial, symbol, dates[1]) if report_index > 0: # 可以比较成长性 current_report, previous_report = data_financial[symbol][report_index], \ data_financial[symbol][report_index - 1] if any([ r[item] == '' or float(r[item]) == 0 for r in [current_report, previous_report] for item in ['每股收益TTM', '净资产收益率TTM', '营业总收入'] ]): pass else: stock_basic_info = 'EPSTTM: %.2f' % float(current_report['每股收益TTM']) \ + '\nROETTM: %.2f %%' % (float(current_report['净资产收益率TTM']) * 100) \ + '\nIncome growth: %.2f %%\n' % \ ((float(current_report['营业总收入']) / float(previous_report['营业总收入']) - 1.0) * 100) if stock_basic_info: plt.text(0.02, 0.90, stock_basic_info, horizontalalignment='left', verticalalignment='center', transform=ax1.transAxes, color='#1d8450', alpha=0.8) annotate_text = { 0: 'Watch', 1: 'Buy', 2: 'Sell', } for i in range(len(dates)): plt.annotate( '%s: %s, %.2f' % (annotate_text[i], dates[i], stock_history_markers[i]), xy=(dates[i], stock_history_markers[i]), xytext=(horizontal[i], vertical[i]), arrowprops=dict(width=1, headwidth=5, facecolor='black', shrink=0.15), ) ax2 = ax1.twinx() # ax1.rcParams['font.size'] = 13 ax2.plot([r['date'] for r in index_history_to_plot], [r['close'] for r in index_history_to_plot], 'b', alpha=0.5) ax2.set_ylabel('SHCI', color='b') ax2.tick_params('y', colors='b') # ax2.set_ylim(min([r['close'] for r in index_history_to_plot]) * 0.7, # max([r['close'] for r in index_history_to_plot]) * 1.3) plt.title("record # %d: profit = %.2f %%, hold time = %d calendar days" % (record_index, profit, hold_time)) fig.tight_layout() plt.show(block=not save) if save: plt.savefig('visualizations/record # %d.pdf' % record_index, format='pdf') plt.close()
merged_dataframes = [input_dataset, input_dataset_label['total_cases']] merged_data = pd.concat(merged_dataframes, axis=1) input_dataset_sj = merged_data.loc[merged_data['city'] == 'sj'] input_dataset_iq = merged_data.loc[merged_data['city'] == 'iq'] import datetime from matplotlib.finance import date2num dateList = [] temp = np.array(input_dataset_sj['week_start_date']) for i in range(len(temp)): #print( str(input_dataset_sj['week_start_date'].iloc[[i]]) ) dateList.append( date2num(datetime.datetime.strptime(temp[i], "%m/%d/%Y")) / 365) plt.figure(figsize=(20, 10)) plt.plot(dateList, input_dataset_sj['total_cases']) plt.title("Total Cases for San Juan") plt.xlabel("Weeks") plt.ylabel("Total Cases") plt.show() # In[677]: dateList = [] temp = np.array(input_dataset_iq['week_start_date']) for i in range(len(temp)): #print( str(input_dataset_sj['week_start_date'].iloc[[i]]) )
column_names = [v for k,v in json['dataset'].items() if k=='column_names'] data = [v for k,v in json['dataset'].items() if k=='data'] dates = [x[0] for x in data[0]] open = [x[1] for x in data[0]] high = [x[2] for x in data[0]] low = [x[3] for x in data[0]] close = [x[4] for x in data[0]] no_of_shares = [x[6] for x in data[0]] print(dates[0]) year = [int(x[:4]) for x in dates] month = [int(x[5:7]) for x in dates] day = [int(x[8::]) for x in dates] float_days=[] for i in range(len(year)): float_days.append(date2num(datetime.datetime(year[i], month[i], day[i]))) #print(float_days) quotes=[[]] for i in range(len(year)): quotes.append([float_days[i],open[i],close[i],high[i],low[i]]) quotes = quotes[1::] ax = plt.gca() plt.title("RELIANCE COMMUNICATIONS STOCK PRICE TREND TILL TODAY") plt.ylabel("Price") plt.xlabel("Date(epoch)") fin.candlestick_ochl(ax,quotes,width=0.2, colorup='k', colordown='r', alpha=1.0) ''' Plot the time, open, close, high, low as a vertical line ranging from low to high. Use a rectangular bar to represent the open-close span. If close >= open, use colorup to color the bar, otherwise use colordown
def _do_plot_candle(date, p_open, high, low, close, volume, view_index, symbol, day_sum, save, minute): """ 绘制不可交互的k线图 param date: 融时间序列交易日时间,pd.DataFrame.index对象 :param p_open: 金融时间序列开盘价格序列,np.array对象 :param high: 金融时间序列最高价格序列,np.array对象 :param low: 金融时间序列最低价格序列,np.array对象 :param close: 金融时间序列收盘价格序列,np.array对象 :param volume: 金融时间序列成交量序列,np.array对象 :param symbol: symbol str对象 :param day_sum: 端线图 matplotlib的版本有些有bug显示不对 :param save: 是否保存可视化结果在本地 :param minute: 是否是绘制分钟k线图 """ # 需要内部import不然每次import abupy都有warning,特别是子进程很烦人 try: # noinspection PyUnresolvedReferences, PyDeprecation import matplotlib.finance as mpf except ImportError: # 2.2 才会有 # noinspection PyUnresolvedReferences, PyDeprecation import matplotlib.mpl_finance as mpf if not g_only_draw_price: # 成交量,价格都绘制 # noinspection PyTypeChecker fig, (ax1, ax2) = plt.subplots(2, sharex=True, figsize=(20, 12)) else: # 只绘制价格 fig, ax1 = plt.subplots(figsize=(6, 6)) if day_sum: # 端线图绘制 qutotes = [] for index, (d, o, c, l, h) in enumerate(zip(date, p_open, close, low, high)): d = index if minute else mpf.date2num(d) val = (d, o, c, l, h) qutotes.append(val) # plot_day_summary_oclh接口,与mpf.candlestick_ochl不同,即数据顺序为开收低高 mpf.plot_day_summary_oclh(ax1, qutotes, ticksize=5, colorup=__colorup__, colordown=__colordown__) else: # k线图绘制 qutotes = [] for index, (d, o, c, h, l) in enumerate(zip(date, p_open, close, high, low)): d = index if minute else mpf.date2num(d) val = (d, o, c, h, l) qutotes.append(val) # mpf.candlestick_ochl即数据顺序为开收高低 mpf.candlestick_ochl(ax1, qutotes, width=0.6, colorup=__colorup__, colordown=__colordown__) if not g_only_draw_price: # 开始绘制成交量 ax1.set_title(symbol) ax1.set_ylabel('ochl') ax1.grid(True) if not minute: ax1.xaxis_date() if view_index is not None: # 开始绘制买入交易日,卖出交易日,重点突出的点位 e_list = date.tolist() # itertools.cycle循环使用备选的颜色 for v, csColor in zip(view_index, itertools.cycle(K_PLT_MAP_STYLE)): try: v_ind = e_list.index(v) except Exception as e: # logging.exception(e) logging.debug(e) # 向前倒一个 v_ind = len(close) - 1 label = symbol + ': ' + str(date[v_ind]) ax1.plot(v, close[v_ind], 'ro', markersize=12, markeredgewidth=4.5, markerfacecolor='None', markeredgecolor=csColor, label=label) # 因为candlestick_ochl 不能label了,所以使用下面的显示文字 # noinspection PyUnboundLocalVariable ax2.plot(v, 0, 'ro', markersize=12, markeredgewidth=0.5, markerfacecolor='None', markeredgecolor=csColor, label=label) plt.legend(loc='best') # 成交量柱子颜色,收盘价格 > 开盘,即红色 # noinspection PyTypeChecker bar_red = np.where(close >= p_open, volume, 0) # 成交量柱子颜色,开盘价格 > 收盘。即绿色 # noinspection PyTypeChecker bar_green = np.where(p_open > close, volume, 0) date = date if not minute else np.arange(0, len(date)) ax2.bar(date, bar_red, facecolor=__colorup__) ax2.bar(date, bar_green, facecolor=__colordown__) ax2.set_ylabel('volume') ax2.grid(True) ax2.autoscale_view() plt.setp(plt.gca().get_xticklabels(), rotation=30) else: ax1.grid(False) if save: # 保存可视化结果在本地 from pylab import savefig save_dir = os.path.join(K_SAVE_CACHE_PNG_ROOT, ABuDateUtil.current_str_date()) png_dir = os.path.join(save_dir, symbol) ABuFileUtil.ensure_dir(png_dir) r_cnt = 0 while True: png_name = '{}{}.png'.format(png_dir, '' if r_cnt == 0 else '-{}'.format(r_cnt)) if not ABuFileUtil.file_exist(png_name): break r_cnt += 1 # noinspection PyUnboundLocalVariable savefig(png_name) fig.clf() plt.close(fig) else: """ save 了就不show了 """ plt.show()
def make_graphs(tickers,names,delt,matr,inp): year_days = 260.0 if(inp[0] == 'Get quotes and show graphs' or 'Show graphs only'): week = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'] nm = len(matr) time_label = 'From ' + matr[0][0]+' to '+matr[nm-1][0] + ' (dd/mm/yyyy)' date_now = datetime.datetime.strptime(matr[nm-1][0], "%d/%m/%Y").date() wdn = date_now.weekday() weekday = week[wdn] if inp[1] == '1 month': span = int(year_days / 12) if inp[1] == '3 months': span = int(0.25 * year_days) if inp[1] == '6 months': span = int(0.5 * year_days) if inp[1] == '1 year': span = int(year_days) if inp[1] == '2 years': span = int(2.0 * year_days) if inp[1] == '3 years': span = int(3.0 * year_days) if inp[1] == '5 years': span = int(5.0 * year_days) if inp[1] == 'all': span = nm for j in range(len(tickers)): # for each ticker ... y = [] # array of prices t = [] t_float = [] v0 = 0 for i in range(nm): # along time line... try: v = float(matr[i][j+1]) if(i==0 or v != v0): y.append(matr[i][j+1]) # from data list matr t.append(datetime.datetime.strptime(matr[i][0], '%d/%m/%Y')) v0 = v t_float.append(date2num(datetime.datetime.strptime(matr[i][0], '%d/%m/%Y'))) except: pass t0 = t_float[0] #starting time point for i in range(len(t)): t_float[i] = t_float[i] - t0 #relative time in days starting at zero trend_days = int(float(inp[2]) * year_days) #duration of trend approximation n = len(y) start_point = max(0, n - span) i_start_trend = max(0, n - trend_days) t_date_trend = list(t) t_trend = list(t_float) #copy of t_float t_trend[0:i_start_trend] = [] #time points in days of trend duration y_trend = list(y) y_trend[0:i_start_trend] = [] #price array for trend duration try: z = numpy.polyfit(t_trend, y_trend, 1) p = numpy.poly1d(z) y_lin = [] for i in range(len(t)): y_lin.append(p(t_float[i])) except: print('no lin fit') t_date_trend[0:i_start_trend] = [] y_lin[0:i_start_trend] = [] t[0:start_point] = [] y[0:start_point] = [] n = len(y) delta = int((y[n-1]/y[n-2]-1)*100000)/1000 down = float(inp[3][:-1]) / 100. up = float(inp[4][:-1]) / 100. x = round(y[n-1]/y_lin[len(y_lin)-1] - 1. , 3) action = 'Wait ('+ str(x*100)+'% relative to trend)' if x >0 and x > up: action = 'Sell ('+ str(x*100)+'% over trend)' if x<0 and -x > down: action = 'Buy ('+ str(-x*100)+'% below trend)' si ='' if(delta > 0): si = '+' fig = pyplot.figure() pyplot.title(tickers[j]+' ('+names[j]+') ' + weekday, color='white',fontweight='bold') graphtext = 'Price today: ' +str(y[n-1]) + '\n(Change today '+ si + str(delta)+ '%) \n ' + action pyplot.ylabel('Price',color='white',fontweight='bold',rotation = 45) ax = pyplot.gca() pyplot.text(0.95,0.95,graphtext,horizontalalignment='right',verticalalignment='top',transform = ax.transAxes,color='blue',fontweight='bold') pyplot.grid() graph = fig.add_subplot(111) graph.patch.set_facecolor('cyan') graph.tick_params(axis='x', colors='blue') graph.tick_params(axis='y', colors='black') graph.plot_date(t,y,'-',color='red',label= tickers[j]) graph.plot_date(t_date_trend, y_lin, '--', fillstyle='none',color='blue', label='xxoooooooooooooooooo') pyplot.gcf().autofmt_xdate() fig.show() pyplot.savefig(tickers[j]+'.png') messagebox.showinfo("showinfo",'\nClose all graph windows') pyplot.close('all')