博客
关于我
用Matplotlib和Gym优雅地呈现股票交易智体
阅读量:351 次
发布时间: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/

    你可能感兴趣的文章
    nginx负载均衡的五种算法
    查看>>
    Nginx配置ssl实现https
    查看>>
    Nginx配置TCP代理指南
    查看>>
    Nginx配置代理解决本地html进行ajax请求接口跨域问题
    查看>>
    Nginx配置参数中文说明
    查看>>
    Nginx配置好ssl,但$_SERVER[‘HTTPS‘]取不到值
    查看>>
    Nginx配置实例-负载均衡实例:平均访问多台服务器
    查看>>
    NIFI大数据进阶_连接与关系_设置数据流负载均衡_设置背压_设置展现弯曲_介绍以及实际操作---大数据之Nifi工作笔记0027
    查看>>
    Nio ByteBuffer组件读写指针切换原理与常用方法
    查看>>
    NIO Selector实现原理
    查看>>
    nio 中channel和buffer的基本使用
    查看>>
    NISP一级,NISP二级报考说明,零基础入门到精通,收藏这篇就够了
    查看>>
    Nitrux 3.8 发布!性能全面提升,带来非凡体验
    查看>>
    NI笔试——大数加法
    查看>>
    NLP 基于kashgari和BERT实现中文命名实体识别(NER)
    查看>>
    NLP学习笔记:使用 Python 进行NLTK
    查看>>
    NLP:使用 SciKit Learn 的文本矢量化方法
    查看>>
    Nmap扫描教程之Nmap基础知识
    查看>>
    Nmap端口扫描工具Windows安装和命令大全(非常详细)零基础入门到精通,收藏这篇就够了
    查看>>
    NMAP网络扫描工具的安装与使用
    查看>>