0%

之前一直是通过matplotlib来画图的,数据量大了以后,画图的速度较慢。

如果使用plotly,效率较高,主要是通过浏览器来渲染图片的,通过js效果,还可以随意放大缩小查看细节。

基本绘图

折线图

1
2
3
import plotly.express as px
fig1 = px.line(df["balance"])
fig1.show()

或者更简便一些

1
2
import plotly.express as px
px.line(df["balance"])

柱状图

1
px.bar(df["pnl"])

散点图

1
px.scatter(df["drawdown"])

对象方式绘图

创建绘图区域

1
2
3
4
5
6
7
8
9
10
import plotly.graph_objects as go
from plotly.subplots import make_subplots

# 创建绘图区域, 4行1列
fig = make_subplots(
rows=4,
cols=1,
subplot_titles=["累计盈亏", "净值回撤", "交易盈亏", "盈亏分布"],
vertical_spacing=0.06
)

创建四幅子图

Scatter取代了Line

1
2
3
4
5
6
7
8
9
10
# 绘制资金曲线

balance_line = go.Scatter(
x=df.index,
y=df["balance"],
mode="lines",
name="累计盈亏"
)

highlevel_scatter = go.Scatter(x=df.index, y=df["highlevel"], name="高水位")

这个有填充的效果

1
2
3
4
5
6
7
8
9
# 绘制回撤区域
drawdown_scatter = go.Scatter(
x=df.index,
y=df["drawdown"],
fillcolor="red",
fill='tozeroy',
mode="lines",
name="回撤"
)
1
2
# 绘制交易盈亏
pnl_bar = go.Bar(y=df["pnl"], name="交易盈亏")
1
2
# 绘制盈亏分布
pnl_histogram = go.Histogram(x=df["pnl"], nbinsx=100, name="盈亏分布")

把子图添加到画布上面

1
2
3
4
5
6
7
8
9
10
# 绘制图表
fig.add_trace(balance_line, row=1, col=1)
fig.add_trace(highlevel_scatter, row=1, col=1)
fig.add_trace(drawdown_scatter, row=2, col=1)
fig.add_trace(pnl_bar, row=3, col=1)
fig.add_trace(pnl_histogram, row=4, col=1)

fig.update_layout(height=1000, width=1000)

fig.show() # 可以省略

安装异常

1
2
Failed to build pyqlib
ERROR: Could not build wheels for pyqlib, which is required to install pyproject.toml-based projects
1
2
3
4
5
6
7
C:\Users\simon\AppData\Local\Temp\pip-build-env-uuivrj87\overlay\Lib\site-packages\Cython\Compiler\Main.py:381: FutureWarning: Cython directive 'language_level' not set, using '3str' for now (Py3). This has changed from earlier releases! File: D:\development\python\qlib\qlib\data\_libs\rolling.pyx
tree = Parsing.p_module(s, pxd, full_module_name)
error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/
[end of output]

note: This error originates from a subprocess, and is likely not a problem with pip.
ERROR: Failed building wheel for pyqlib

需要安装”Microsoft C++ Build Tools”。

需要更新安装 cython

1
pip install cython --upgrade

可以使用 for 循环的,就叫做可迭代对象,叫Iterable。

使用next()的,叫Iterator。

生成器,只是在next()时,再生成数据,不过早的占用内存。

装饰器的实现方案。

输入函数,返回函数。

不带参数的,带参数的,带返回值的,在装饰器上传入参数的。