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

本文涉及的产品
实时计算 Flink 版,1000CU*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+Flink搭建GitHub实时数据大屏
通过使用Flink、Hologres构建实时数仓,并通过Hologres对接BI分析工具(以DataV为例),实现海量数据实时分析.
实时计算 Flink 实战课程
如何使用实时计算 Flink 搞定数据处理难题?实时计算 Flink 极客训练营产品、技术专家齐上阵,从开源 Flink功能介绍到实时计算 Flink 优势详解,现场实操,5天即可上手! 欢迎开通实时计算 Flink 版: https://cn.aliyun.com/product/bigdata/sc Flink Forward Asia 介绍: Flink Forward 是由 Apache 官方授权,Apache Flink Community China 支持的会议,通过参会不仅可以了解到 Flink 社区的最新动态和发展计划,还可以了解到国内外一线大厂围绕 Flink 生态的生产实践经验,是 Flink 开发者和使用者不可错过的盛会。 去年经过品牌升级后的 Flink Forward Asia 吸引了超过2000人线下参与,一举成为国内最大的 Apache 顶级项目会议。结合2020年的特殊情况,Flink Forward Asia 2020 将在12月26日以线上峰会的形式与大家见面。
相关文章
|
2月前
|
数据采集 机器学习/深度学习 人工智能
Python:现代编程的首选语言
Python:现代编程的首选语言
267 102
|
2月前
|
数据采集 机器学习/深度学习 算法框架/工具
Python:现代编程的瑞士军刀
Python:现代编程的瑞士军刀
297 104
|
2月前
|
人工智能 自然语言处理 算法框架/工具
Python:现代编程的首选语言
Python:现代编程的首选语言
249 103
|
29天前
|
Python
Python编程:运算符详解
本文全面详解Python各类运算符,涵盖算术、比较、逻辑、赋值、位、身份、成员运算符及优先级规则,结合实例代码与运行结果,助你深入掌握Python运算符的使用方法与应用场景。
161 3
|
29天前
|
数据处理 Python
Python编程:类型转换与输入输出
本教程介绍Python中输入输出与类型转换的基础知识,涵盖input()和print()的使用,int()、float()等类型转换方法,并通过综合示例演示数据处理、错误处理及格式化输出,助你掌握核心编程技能。
366 3
|
1月前
|
并行计算 安全 计算机视觉
Python多进程编程:用multiprocessing突破GIL限制
Python中GIL限制多线程性能,尤其在CPU密集型任务中。`multiprocessing`模块通过创建独立进程,绕过GIL,实现真正的并行计算。它支持进程池、队列、管道、共享内存和同步机制,适用于科学计算、图像处理等场景。相比多线程,多进程更适合利用多核优势,虽有较高内存开销,但能显著提升性能。合理使用进程池与通信机制,可最大化效率。
239 3
|
29天前
|
Java 调度 数据库
Python threading模块:多线程编程的实战指南
本文深入讲解Python多线程编程,涵盖threading模块的核心用法:线程创建、生命周期、同步机制(锁、信号量、条件变量)、线程通信(队列)、守护线程与线程池应用。结合实战案例,如多线程下载器,帮助开发者提升程序并发性能,适用于I/O密集型任务处理。
207 0
|
2月前
|
机器学习/深度学习 人工智能 数据挖掘
Python:现代编程的首选语言
Python:现代编程的首选语言
188 82
|
2月前
|
数据采集 机器学习/深度学习 人工智能
Python:现代编程的多面手
Python:现代编程的多面手
75 0
|
2月前
|
存储 人工智能 算法
Python实现简易成语接龙小游戏:从零开始的趣味编程实践
本项目将中国传统文化与编程思维相结合,通过Python实现成语接龙游戏,涵盖数据结构、算法设计与简单AI逻辑,帮助学习者在趣味实践中掌握编程技能。
303 0