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

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

?????????

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

????

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

????

???????????

import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
def 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/

    你可能感兴趣的文章
    nodejs服务端实现post请求
    查看>>
    nodejs框架,原理,组件,核心,跟npm和vue的关系
    查看>>
    nodejs模块——fs模块
    查看>>
    Nodejs模块、自定义模块、CommonJs的概念和使用
    查看>>
    nodejs生成多层目录和生成文件的通用方法
    查看>>
    nodejs端口被占用原因及解决方案
    查看>>
    Nodejs简介以及Windows上安装Nodejs
    查看>>
    nodejs系列之express
    查看>>
    nodejs系列之Koa2
    查看>>
    Nodejs连接mysql
    查看>>
    nodejs连接mysql
    查看>>
    NodeJs连接Oracle数据库
    查看>>
    nodejs配置express服务器,运行自动打开浏览器
    查看>>
    Nodemon 深入解析与使用
    查看>>
    NodeSession:高效且灵活的Node.js会话管理工具
    查看>>
    node~ http缓存
    查看>>
    node不是内部命令时配置node环境变量
    查看>>
    node中fs模块之文件操作
    查看>>
    Node中同步与异步的方式读取文件
    查看>>
    Node中的Http模块和Url模块的使用
    查看>>