博客
关于我
用Matplotlib和Gym优雅地呈现股票交易智体
阅读量:350 次
发布时间:2019-03-04

本文共 5888 字,大约阅读时间需要 19 分钟。

?????????

????????????????Matplotlib???????????????????????????????????????????????

????

?????matplotlib?????????????????????????????????

????

???????????

import numpy as npimport matplotlibimport matplotlib.pyplot as pltimport matplotlib.dates as mdatesdef date2num(date):    converter = mdates.strpdate2num('%Y-%m-%d')    return converter(date)class StockTradingGraph:    """A stock trading visualization using matplotlib made to render    OpenAI gym environments"""        def __init__(self, df, title=None):        self.df = df        self.net_worths = np.zeros(len(df['Date']))        fig = plt.figure()        fig.suptitle(title)        self.net_worth_ax = plt.subplot2grid((6, 1), (0, 0), rowspan=2, colspan=1)        self.price_ax = plt.subplot2grid((6, 1), (2, 0), rowspan=8, colspan=1, sharex=self.net_worth_ax)        self.volume_ax = self.price_ax.twinx()        plt.subplots_adjust(left=0.11, bottom=0.24, right=0.90, top=0.90, wspace=0.2, hspace=0)        plt.show(block=False)def render(self, current_step, net_worth, trades, window_size=40):    self.net_worths[current_step] = net_worth    window_start = max(current_step - window_size, 0)    step_range = range(window_start, current_step + 1)    dates = np.array([date2num(x) for x in self.df['Date'].values[step_range]])    self._render_net_worth(current_step, net_worth, step_range, dates)    self._render_price(current_step, net_worth, dates, step_range)    self._render_volume(current_step, net_worth, dates, step_range)    self._render_trades(current_step, trades, step_range)    self.price_ax.set_xticklabels(self.df['Date'].values[step_range], rotation=45, horizontalalignment='right')    plt.setp(self.net_worth_ax.get_xticklabels(), visible=False)    plt.pause(0.001)def _render_net_worth(self, current_step, net_worth, step_range, dates):    self.net_worth_ax.clear()    self.net_worth_ax.plot_date(dates, self.net_worths[step_range], '-')    self.net_worth_ax.legend()    legend = self.net_worth_ax.legend(loc=2, ncol=2, prop={'size': 8})    legend.get_frame().set_alpha(0.4)    last_date = date2num(self.df['Date'].values[current_step])    last_net_worth = self.net_worths[current_step]    self.net_worth_ax.annotate('{0:.2f}'.format(net_worth),                             (last_date, last_net_worth),                            xytext=(last_date, last_net_worth),                            bbox=dict(boxstyle='round', fc='w', ec='k', lw=1),                            color="black",                             fontsize="small")    self.net_worth_ax.set_ylim(        min(self.net_worths[np.nonzero(self.net_worths)]) / 1.25,        max(self.net_worths) * 1.25)def _render_price(self, current_step, net_worth, dates, step_range):    self.price_ax.clear()    candlesticks = zip(dates,                        self.df['Open'].values[step_range],                        self.df['Close'].values[step_range],                        self.df['High'].values[step_range],                        self.df['Low'].values[step_range])    candlestick(self.price_ax, candlesticks, width=1, colorup=UP_COLOR, colordown=DOWN_COLOR)    last_date = date2num(self.df['Date'].values[current_step])    last_close = self.df['Close'].values[current_step]    last_high = self.df['High'].values[current_step]    self.price_ax.annotate('{0:.2f}'.format(last_close),                         (last_date, last_close),                         xytext=(last_date, last_high),                         bbox=dict(boxstyle='round', fc='w', ec='k', lw=1),                         color="black",                         fontsize="small")    ylim = self.price_ax.get_ylim()    self.price_ax.set_ylim(ylim[0] - (ylim[1] - ylim[0]) * VOLUME_CHART_HEIGHT, ylim[1])def _render_volume(self, current_step, net_worth, dates, step_range):    self.volume_ax.clear()    volume = np.array(self.df['Volume'].values[step_range])    pos = self.df['Open'].values[step_range] - self.df['Close'].values[step_range] < 0    neg = self.df['Open'].values[step_range] - self.df['Close'].values[step_range] > 0    self.volume_ax.bar(dates[pos], volume[pos], color=UP_COLOR, alpha=0.4, width=1, align='center')    self.volume_ax.bar(dates[neg], volume[neg], color=DOWN_COLOR, alpha=0.4, width=1, align='center')    self.volume_ax.set_ylim(0, max(volume) / VOLUME_CHART_HEIGHT)    self.volume_ax.yaxis.set_ticks([])def _render_trades(self, current_step, trades, step_range):    for trade in trades:        if trade['step'] in step_range:            date = date2num(self.df['Date'].values[trade['step']])            high = self.df['High'].values[trade['step']]            low = self.df['Low'].values[trade['step']]            if trade['type'] == 'buy':                high_low = low                color = UP_TEXT_COLOR            else:                high_low = high                color = DOWN_TEXT_COLOR            total = '{0:.2f}'.format(trade['total'])            self.price_ax.annotate('$' + total,                                 (date, high_low),                                 xytext=(date, high_low),                                 color=color,                                 fontsize=8,                                 arrowprops=(dict(color=color)))

????

  • date2num ??????????????????????

  • StockTradingGraph ????????????????

    • __init__???????????????????????
    • render???????????????
  • render ??????????????????

    • ????
    • ???????????
    • ?????
    • ????
  • **`render????????????????????

    • _render_net_worth?????
    • _render_price?????
    • _render_volume??????
    • _render_trades?????
  • ????

    • date2num??? matplotlib.dates ??????????????????????
    • StockTradingGraph????????????????????????????
    • render???????????????????????
    • **`render???????????????????????????????????

    ????

  • ????????????????? numpy?matplotlib ? mpl_finance?
  • ?????????? StockTradingGraph ???
  • ??????? render ?????????????????
  • ??????? plt.pause(0.001) ?????????????
  • ??

    ????????????????????????????????????????????BTC????????????????????????????

    转载地址:http://iiwr.baihongyu.com/

    你可能感兴趣的文章
    Numpy如何使用np.umprod重写range函数中i的python
    查看>>
    numpy学习笔记3-array切片
    查看>>
    numpy数组替换其中的值(如1替换为255)
    查看>>
    numpy数组索引-ChatGPT4o作答
    查看>>
    numpy最大值和最大值索引
    查看>>
    NUMPY矢量化np.prod不能构造具有超过32个操作数的ufunc
    查看>>
    Numpy矩阵与通用函数
    查看>>
    numpy绘制热力图
    查看>>
    numpy转PIL 报错TypeError: Cannot handle this data type
    查看>>
    Numpy闯关100题,我闯了95关,你呢?
    查看>>
    nump模块
    查看>>
    Nutch + solr 这个配合不错哦
    查看>>
    NuttX 构建系统
    查看>>
    NutUI:京东风格的轻量级 Vue 组件库
    查看>>
    NutzCodeInsight 2.0.7 发布,为 nutz-sqltpl 提供友好的 ide 支持
    查看>>
    NutzWk 5.1.5 发布,Java 微服务分布式开发框架
    查看>>
    NUUO网络视频录像机 css_parser.php 任意文件读取漏洞复现
    查看>>
    NUUO网络视频录像机 upload.php 任意文件上传漏洞复现
    查看>>
    Nuxt Time 使用指南
    查看>>
    NuxtJS 接口转发详解:Nitro 的用法与注意事项
    查看>>