コード例 #1
0
def candle_figure():
    data = pd.read_csv('000032.csv')
    open = data['open']
    high = data['high']
    close = data['close']
    low = data['low']
    dates = np.arange(len(data))
    print(dates[:10])
    volume = data['volume']
    ticker = 'ALBB'
    mondays = WeekdayLocator(MONDAY)
    alldays = DayLocator()
    weekFormatter = DateFormatter('%b %d')
    dayFormatter = DateFormatter('%d')
    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_oclh(ax, (dates, open, close, high, low))
    _candlestick(ax, (dates, open, close, high, low), width=0.6)
    ax.xaxis_date()
    ax.autoscale_view()
    plt.setp(plt.gca().get_xticklabels(),
             rotation=80,
             horizontalalignment='right')
    plt.show()
コード例 #2
0
ファイル: draw_test.py プロジェクト: zhengfaning/vnpy_andy
def draw_kl2(df: pd.DataFrame, minute=False, day_sum=False):

    # 为了示例清晰,只拿出前30天的交易数据绘制蜡烛图,
    part_df = df
    # fig, ax = plt.subplots(figsize=(14, 7))
    fig, ax1 = plt.subplots(figsize=(6, 6))
    qutotes = []

    if day_sum:
        # 端线图绘制
        qutotes = []
        for index, (d, o, c, l, h) in enumerate(
                zip(part_df.time, part_df.open, part_df.close, part_df.high,
                    part_df.low)):
            d = index if minute else dts.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(part_df.time, part_df.open, part_df.close, part_df.high,
                    part_df.low)):
            d = index if minute else dts.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__)
    # for index, (d, o, c, h, l) in enumerate(
    #         zip(part_df.time, part_df.open, part_df.close,
    #             part_df.high, part_df.low)):
    #     # 蜡烛图的日期要使用dts.date2num进行转换为特有的数字值
    #     # d = datetime.datetime.fromtimestamp(d / 1000)
    #     # d = dts.date2num(d)
    #     d = index
    #     # 日期,开盘,收盘,最高,最低组成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()
コード例 #3
0
 def draw_k_easy(self):
     fig, ax = plt.subplots(figsize=(15, 5))
     mpf.plot_day_summary_oclh(ax,
                               self.mat_data,
                               colorup='r',
                               colordown='k')
     plt.grid(True)
     ax.xaxis_date()
     plt.title(self.name + ':' + self.code)
     plt.ylabel('Price')
     plt.show()
コード例 #4
0
''' generamos la ema. recordar que los valores pueden
ser 0 y daria problemas en el grafico.
por eso la generamos aqui.'''
ema50 = fb.get_ema_periodo(50, quotes['Close'])

# select desired range of dates
quotes = quotes[(quotes.index >= date1) & (quotes.index <= date2)]
''' ajustamos los valores de la media a los valores del cierre'''
l = len(quotes['Close'])
ema50 = ema50[-l:]

fig, ax = plt.subplots(figsize=(24, 12))

plot_day_summary_oclh(ax,
                      zip(date2num(quotes.index.to_pydatetime()),
                          quotes['Open'], quotes['Close'], quotes['Low'],
                          quotes['High']),
                      ticksize=3)

plt.plot(zip(date2num(quotes.index.to_pydatetime())), ema50)

ax.xaxis.set_major_locator(mondays)
ax.xaxis.set_major_formatter(daysFmt)
ax.autoscale_view()
ax.xaxis.grid(True, 'major')
ax.grid(True)

fig.autofmt_xdate()

plt.show()
コード例 #5
0
ファイル: plot_oclh_demo_d.py プロジェクト: marcostrfn/bolsa
quotes = pd.read_csv('AUDNZD.csv',
                     index_col=0,
                     parse_dates=True,
                     infer_datetime_format=True,
                     sep=";")

# select desired range of dates
quotes = quotes[(quotes.index >= date1) & (quotes.index <= date2)]

fig, ax = plt.subplots(figsize=(20, 10))


ax1 = plt.subplot2grid((8,6), (0,0), colspan=5, rowspan=5)

plot_day_summary_oclh(ax1, zip(date2num(quotes.index.to_pydatetime()),
                              quotes['apertura'], quotes['cierre'],
                              quotes['low'], quotes['high']),
                      ticksize=3)



ax2 = plt.subplot2grid((8,6), (5, 0), colspan=5) # plt.subplot(5, 1, 1, rowspan=3)
plt.plot( zip(date2num(quotes.index.to_pydatetime())), quotes['ema[5]'])
plt.plot( zip(date2num(quotes.index.to_pydatetime())), quotes['ema[50]'])


ax.xaxis.set_major_locator(mondays)
ax.xaxis.set_major_formatter(daysFmt)
ax.autoscale_view()
ax.xaxis.grid(True, 'major')
ax.grid(True)
コード例 #6
0
ファイル: ABuMarketDrawing.py プロジェクト: Yaroglek/abu
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 mpl_finance as mpf
    except ImportError:
        # 2.2 才会有
        # noinspection PyUnresolvedReferences, PyDeprecation
        import 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 mpldates.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 mpldates.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()
コード例 #7
0
fig.subplots_adjust(bottom=0.5)
mpf.candlestick_ochl(ax,
                     mat_wdyx,
                     width=0.6,
                     colorup='g',
                     colordown='r',
                     alpha=1.0)
plt.grid(True)
# 设置日期刻度旋转的角度
plt.xticks(rotation=30)
plt.title('wanda yuanxian 17')
plt.xlabel('Date')
plt.ylabel('Price')
# x轴的刻度为日期
ax.xaxis_date()
fig, ax = plt.subplots(figsize=(15, 5))
mpf.plot_day_summary_oclh(ax, mat_wdyx, colorup='g', colordown='r')
plt.grid(True)
ax.xaxis_date()
plt.title('wandayuanxian 17')
plt.ylabel('Price')

fig, (ax1, ax2) = plt.subplots(2, sharex=True, figsize=(15, 8))
mpf.candlestick_ochl(ax1, mat_wdyx, width=1.0, colorup='g', colordown='r')
ax1.set_title('wandayuanxian')
ax1.set_ylabel('Price')
ax1.grid(True)
ax1.xaxis_date()
plt.bar(mat_wdyx[:, 0] - 0.25, mat_wdyx[:, 5], width=0.5)
ax2.set_ylabel('Volume')
ax2.grid(True)
コード例 #8
0
quotes = pd.read_csv('data/yahoofinance-INTC-19950101-20040412.csv',
                     index_col=0,
                     parse_dates=True,
                     infer_datetime_format=True)

"""
dateparse = lambda x: pd.datetime.strptime(x, '%Y%m%d')
quotes = pd.read_csv(
    '/Users/momantang/work/cobrass/data/000001.sh.csv',
    parse_dates=['trade_date'],
)
# select desired range of dates
# quotes = quotes[(quotes.index >= date1) & (quotes.index <= date2)]
print(quotes.dtypes)

fig, ax = plt.subplots()
plot_day_summary_oclh(ax,
                      zip(quotes['trade_date'], quotes['open'],
                          quotes['close'], quotes['low'], quotes['high']),
                      ticksize=3)
ax.xaxis.set_major_locator(mondays)
ax.xaxis.set_major_formatter(daysFmt)
ax.autoscale_view()
ax.xaxis.grid(True, 'major')
ax.grid(True)

fig.autofmt_xdate()

plt.show()