Python 金融编程第二版(GPT 重译)(三)(5)

本文涉及的产品
实时计算 Flink 版,5000CU*H 3个月
简介: Python 金融编程第二版(GPT 重译)(三)

Python 金融编程第二版(GPT 重译)(三)(4)https://developer.aliyun.com/article/1559338


交互式 2D 绘图

matplotlib 允许创建静态位图对象或 PDF 格式的绘图。如今,有许多可用于基于 D3.js 标准创建交互式绘图的库。这些绘图可以实现缩放和悬停效果以进行数据检查,还可以轻松嵌入到网页中。

一个流行的平台和绘图库是Plotly。它专门用于数据科学的可视化,并在全球范围内广泛使用。Plotly 的主要优点是其与 Python 生态系统的紧密集成以及易于使用 — 特别是与 pandasDataFrame 对象和包装器包 Cufflinks 结合使用时。

对于某些功能,需要使用 Plotly 的免费帐户,用户可以在平台本身 http://plot.ly 下注册。一旦授予凭据,它们应该被本地存储以供以后永久使用。所有相关详细信息都在使用 Plotly for Python 入门 中找到。

本节仅关注选定的方面,因为 Cufflinks 专门用于从存储在 DataFrame 对象中的数据创建交互式绘图。

基本绘图

要从 Jupyter Notebook 上下文开始,需要一些导入,并且应该打开 notebook 模式

In [42]: import pandas as pd
In [43]: import cufflinks as cf  ![1](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/1.png)
In [44]: import plotly.offline as plyo  ![2](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/2.png)
In [45]: plyo.init_notebook_mode(connected=True)  ![3](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/3.png)


导入 Cufflinks


导入 Plotly 的离线绘图功能。


打开笔记本绘图模式。

提示

使用Plotly,还可以选择在Plotly服务器上呈现绘图。然而,笔记本模式通常更快,特别是处理较大数据集时。但是,像Plotly的流图服务之类的一些功能仅通过与服务器通信才可用。

后续示例再次依赖随机数,这次存储在具有DatetimeIndexDataFrame对象中,即作为时间序列数据。

In [46]: a = np.random.standard_normal((250, 5)).cumsum(axis=0)  ![1](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/1.png)
In [47]: index = pd.date_range('2019-1-1',  ![2](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/2.png)
                               freq='B',  ![3](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/3.png)
                               periods=len(a)) ![4](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/4.png)
In [48]: df = pd.DataFrame(100 + 5 * a,  ![5](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/5.png)
                           columns=list('abcde'),  ![6](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/6.png)
                           index=index)  ![7](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/7.png)
In [49]: df.head()  ![8](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/8.png)
Out[49]:                      a           b           c          d           e
         2019-01-01  109.037535   98.693865  104.474094  96.878857  100.621936
         2019-01-02  107.598242   97.005738  106.789189  97.966552  100.175313
         2019-01-03  101.639668  100.332253  103.183500  99.747869  107.902901
         2019-01-04   98.500363  101.208283  100.966242  94.023898  104.387256
         2019-01-07   93.941632  103.319168  105.674012  95.891062   86.547934


标准正态分布的(伪)随机数。


DatetimeIndex对象的开始日期。


频率(“business daily“)。


所需周期数。


原始数据进行线性转换。


将列标题作为单个字符。


DatetimeIndex对象。


前五行的数据。

CufflinksDataFrame类添加了一个新方法:df.iplot()。此方法在后台使用Plotly创建交互式图。本节中的代码示例都利用了将交互式图下载为静态位图的选项,然后将其嵌入到文本中。在 Jupyter Notebook 环境中,创建的绘图都是交互式的。下面代码的结果显示为<<>>。

In [50]: plyo.iplot(  ![1](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/1.png)
             df.iplot(asFigure=True),  ![2](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/2.png)
             # image ='png', ![3](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/3.png)
             filename='ply_01'  ![4](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/4.png)
         )


这利用了Plotly的离线(笔记本模式)功能。


使用参数asFigure=True调用df.iplot()方法以允许本地绘图和嵌入。


image选项还提供了绘图的静态位图版本。


指定要保存的位图的文件名(文件类型扩展名会自动添加)。


图 7-22. 使用PlotlypandasCufflinks绘制时间序列数据的线图

matplotlib一般或pandas绘图功能一样,可用于自定义此类绘图的多个参数(参见图 7-23):

In [51]: plyo.iplot(
             df[['a', 'b']].iplot(asFigure=True,
                      theme='polar',  ![1](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/1.png)
                      title='A Time Series Plot',  ![2](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/2.png)
                      xTitle='date',  ![3](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/3.png)
                      yTitle='value',  ![4](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/4.png)
                      mode={'a': 'markers', 'b': 'lines+markers'},  ![5](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/5.png)
                      symbol={'a': 'dot', 'b': 'diamond'},  ![6](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/6.png)
                      size=3.5,  ![7](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/7.png)
                      colors={'a': 'blue', 'b': 'magenta'},  ![8](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/8.png)
                                 ),
             # image ='png',
             filename='ply_02'
         )


选择绘图的主题(绘图样式)。


添加标题。


添加 x 标签。


添加 y 标签。


按列定义绘图模式(线条、标记等)。


按列定义要用作标记的符号。


为所有标记固定大小。


按列指定绘图颜色


图 7-23. DataFrame 对象的两列线图及自定义

matplotlib 类似,Plotly 允许使用多种不同的绘图类型。通过 Cufflinks 可用的绘图有:chart, scatter, bar, box, spread, ratio, heatmap, surface, histogram, bubble, bubble3d, scatter3d, scattergeo, ohlc, candle, piechoroplet。作为与线图不同的绘图类型的示例,请考虑直方图(参见[链接即将到来]):

In [52]: plyo.iplot(
             df.iplot(kind='hist',  ![1](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/1.png)
                      subplots=True,  ![2](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/2.png)
                      bins=15,  ![3](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/3.png)
                      asFigure=True),
             # image ='png',
             filename='ply_03'
         )


指定绘图类型。


每列需要单独的子图。


设置 bins 参数(要使用的桶=要绘制的条形图)。


图 7-24. DataFrame 对象的每列直方图

金融图表

当处理金融时间序列数据时,PlotyCufflinkspandas 的组合特别强大。Cufflinks 提供了专门的功能,用于创建典型的金融图,并添加典型的金融图表元素,例如相对强度指标(RSI),这只是一个例子。为此,创建了一个持久的 QuantFig 对象,可以像使用 CufflinksDataFrame 对象一样绘制。

此子部分使用真实的金融数据集:欧元/美元汇率的时间序列数据(来源:FXCM Forex Capital Markets Ltd.)。

In [53]: # data from FXCM Forex Capital Markets Ltd.
         raw = pd.read_csv('../../source/fxcm_eur_usd_eod_data.csv',
                          index_col=0, parse_dates=True)  ![1](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/1.png)
In [54]: raw.info()  ![2](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/2.png)
         <class 'pandas.core.frame.DataFrame'>
         DatetimeIndex: 2820 entries, 2007-06-03 to 2017-05-31
         Data columns (total 10 columns):
         Time          2820 non-null object
         OpenBid       2820 non-null float64
         HighBid       2820 non-null float64
         LowBid        2820 non-null float64
         CloseBid      2820 non-null float64
         OpenAsk       2820 non-null float64
         HighAsk       2820 non-null float64
         LowAsk        2820 non-null float64
         CloseAsk      2820 non-null float64
         TotalTicks    2820 non-null int64
         dtypes: float64(8), int64(1), object(1)
         memory usage: 242.3+ KB
In [55]: quotes = raw[['OpenAsk', 'HighAsk', 'LowAsk', 'CloseAsk']]  ![3](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/3.png)
         quotes = quotes.iloc[-60:]  ![4](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/4.png)
         quotes.tail()  ![5](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/5.png)
Out[55]:             OpenAsk  HighAsk   LowAsk  CloseAsk
         Date
         2017-05-27  1.11808  1.11808  1.11743   1.11788
         2017-05-28  1.11788  1.11906  1.11626   1.11660
         2017-05-29  1.11660  1.12064  1.11100   1.11882
         2017-05-30  1.11882  1.12530  1.11651   1.12434
         2017-05-31  1.12434  1.12574  1.12027   1.12133


从逗号分隔值(CSV)文件中读取财务数据。


结果 DataFrame 对象包含多列和超过 2,800 行数据。


DataFrame 对象中选择四列(开-高-低-收)。


仅用于可视化的少量数据行。


结果数据集 quotes 的最后五行。

在实例化期间,QuantFig 对象将 DataFrame 对象作为输入,并允许进行一些基本的自定义。然后使用 qf.iplot() 方法绘制存储在 QuantFig 对象 qf 中的数据(参见图 7-25)。

In [56]: qf = cf.QuantFig(
                  quotes,  ![1](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/1.png)
                  title='EUR/USD Exchange Rate',  ![2](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/2.png)
                  legend='top',  ![3](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/3.png)
                  name='EUR/USD'  ![4](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/4.png)
         )
In [57]: plyo.iplot(
             qf.iplot(asFigure=True),
             # image ='png',
             filename='qf_01'
         )


DataFrame 对象传递给 QuantFig 构造函数。


添加图标题。


图例放置在图的顶部。


这给数据集起了个名字。


图 7-25. EUR/USD 数据的 OHLC 图

添加典型的金融图表元素,如 Bollinger 带,通过 QuantFig 对象的不同可用方法进行 (见图 7-26)。

In [58]: qf.add_bollinger_bands(periods=15,  ![1](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/1.png)
                                boll_std=2)  ![2](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/2.png)
In [59]: plyo.iplot(qf.iplot(asFigure=True),
              # image='png',
              filename='qf_02')


Bollinger 带的周期数。


用于带宽的标准偏差数。


图 7-26. EUR/USD 数据的 OHLC 图,带有 Bollinger 带

添加了某些金融指标,如 RSI,作为一个子图 (见图 7-27)。

In [60]: qf.add_rsi(periods=14,  ![1](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/1.png)
                   showbands=False)  ![2](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/2.png)
In [61]: plyo.iplot(
              qf.iplot(asFigure=True),
              # image='png',
              filename='qf_03'
         )


修复了 RSI 周期。


不显示上限或下限带。


图 7-27. EUR/USD 数据的 OHLC 图,带有 Bollinger 带和 RSI

结论

当涉及到 Python 中的数据可视化时,matplotlib 可以被认为是基准和工作马。它与 NumPypandas 紧密集成。基本功能易于方便地访问。然而,另一方面,matplotlib 是一个相当强大的库,具有一种相对复杂的 API。这使得在本章中无法对 matplotlib 的所有功能进行更广泛的概述。

本章介绍了在许多金融背景下有用的 matplotlib 的 2D 和 3D 绘图的基本功能。其他章节提供了如何在可视化中使用这个基本库的更多示例。

除了 matplotlib,本章还涵盖了 PlotlyCufflinks 的组合。这种组合使得创建交互式 D3.js 图表成为一件方便的事情,因为通常只需在 DataFrame 对象上进行一次方法调用。所有的技术细节都在后端处理。此外,Cufflinks 通过 QuantFig 对象提供了一种创建带有流行金融指标的典型金融图表的简单方法。

进一步阅读

matplotlib 的主要资源可以在网络上找到:

现在已经成为一种标准的例程去参考画廊,寻找合适的可视化示例,并从相应的示例代码开始。

PlotlyCufflinks 的主要资源也可以在线找到:

¹ 想了解可用的绘图类型概述,请访问matplotlib gallery

# image=‘png’,

filename=‘qf_02’)

[外链图片转存中...(img-ECPzFeZ4-1717935621984)]
Bollinger 带的周期数。
[外链图片转存中...(img-jBiuvj1H-1717935621985)]
用于带宽的标准偏差数。
[外链图片转存中...(img-zs176EML-1717935621985)]
###### 图 7-26\. EUR/USD 数据的 OHLC 图,带有 Bollinger 带
添加了某些金融指标,如 RSI,作为一个子图 (见图 7-27)。
```py
In [60]: qf.add_rsi(periods=14,  ![1](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/1.png)
                   showbands=False)  ![2](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/2.png)
In [61]: plyo.iplot(
              qf.iplot(asFigure=True),
              # image='png',
              filename='qf_03'
         )

[外链图片转存中…(img-FNuhWBIa-1717935621985)]

修复了 RSI 周期。

[外链图片转存中…(img-N5TcWdyb-1717935621985)]

不显示上限或下限带。

[外链图片转存中…(img-3j5w3LDD-1717935621985)]

图 7-27. EUR/USD 数据的 OHLC 图,带有 Bollinger 带和 RSI

结论

当涉及到 Python 中的数据可视化时,matplotlib 可以被认为是基准和工作马。它与 NumPypandas 紧密集成。基本功能易于方便地访问。然而,另一方面,matplotlib 是一个相当强大的库,具有一种相对复杂的 API。这使得在本章中无法对 matplotlib 的所有功能进行更广泛的概述。

本章介绍了在许多金融背景下有用的 matplotlib 的 2D 和 3D 绘图的基本功能。其他章节提供了如何在可视化中使用这个基本库的更多示例。

除了 matplotlib,本章还涵盖了 PlotlyCufflinks 的组合。这种组合使得创建交互式 D3.js 图表成为一件方便的事情,因为通常只需在 DataFrame 对象上进行一次方法调用。所有的技术细节都在后端处理。此外,Cufflinks 通过 QuantFig 对象提供了一种创建带有流行金融指标的典型金融图表的简单方法。

进一步阅读

matplotlib 的主要资源可以在网络上找到:

现在已经成为一种标准的例程去参考画廊,寻找合适的可视化示例,并从相应的示例代码开始。

PlotlyCufflinks 的主要资源也可以在线找到:

¹ 想了解可用的绘图类型概述,请访问matplotlib gallery

相关实践学习
基于Hologres轻松玩转一站式实时仓库
本场景介绍如何利用阿里云MaxCompute、实时计算Flink和交互式分析服务Hologres开发离线、实时数据融合分析的数据大屏应用。
Linux入门到精通
本套课程是从入门开始的Linux学习课程,适合初学者阅读。由浅入深案例丰富,通俗易懂。主要涉及基础的系统操作以及工作中常用的各种服务软件的应用、部署和优化。即使是零基础的学员,只要能够坚持把所有章节都学完,也一定会受益匪浅。
相关文章
|
2天前
|
存储 机器学习/深度学习 关系型数据库
Python 金融编程第二版(四)(5)
Python 金融编程第二版(四)
8 0
|
2天前
|
存储 SQL 数据库
Python 金融编程第二版(四)(4)
Python 金融编程第二版(四)
8 0
|
2天前
|
SQL 存储 数据库
Python 金融编程第二版(四)(3)
Python 金融编程第二版(四)
8 0
|
2天前
|
存储 分布式计算 数据可视化
Python 金融编程第二版(四)(2)
Python 金融编程第二版(四)
10 0
|
2天前
|
存储 SQL 数据可视化
Python 金融编程第二版(四)(1)
Python 金融编程第二版(四)
9 0
|
2天前
|
存储 SQL 数据库
Python 金融编程第二版(GPT 重译)(四)(4)
Python 金融编程第二版(GPT 重译)(四)
13 3
|
2天前
|
存储 NoSQL 索引
Python 金融编程第二版(GPT 重译)(一)(4)
Python 金融编程第二版(GPT 重译)(一)
11 2
|
2天前
|
存储 机器学习/深度学习 关系型数据库
Python 金融编程第二版(GPT 重译)(四)(5)
Python 金融编程第二版(GPT 重译)(四)
10 2
|
2天前
|
数据可视化 Python
Python 金融编程第二版(GPT 重译)(三)(4)
Python 金融编程第二版(GPT 重译)(三)
11 2
|
2天前
|
存储 算法 数据可视化
Python 金融编程第二版(GPT 重译)(一)(1)
Python 金融编程第二版(GPT 重译)(一)
13 1