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

简介: Python 金融编程第二版(GPT 重译)(二)

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


复杂选择

数据选择通常通过在列值上制定条件来完成,并可能逻辑地组合多个这样的条件。考虑以下数据集。

In [71]: data = np.random.standard_normal((10, 2))  ![1](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/1.png)
In [72]: df = pd.DataFrame(data, columns=['x', 'y'])  ![2](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/2.png)
In [73]: df.info()  ![2](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/2.png)
         <class 'pandas.core.frame.DataFrame'>
         RangeIndex: 10 entries, 0 to 9
         Data columns (total 2 columns):
         x    10 non-null float64
         y    10 non-null float64
         dtypes: float64(2)
         memory usage: 240.0 bytes
In [74]: df.head()  ![3](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/3.png)
Out[74]:           x         y
         0  1.189622 -1.690617
         1 -1.356399 -1.232435
         2 -0.544439 -0.668172
         3  0.007315 -0.612939
         4  1.299748 -1.733096
In [75]: df.tail()  ![4](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/4.png)
Out[75]:           x         y
         5 -0.983310  0.357508
         6 -1.613579  1.470714
         7 -1.188018 -0.549746
         8 -0.940046 -0.827932
         9  0.108863  0.507810


具有标准正态分布随机数的ndarray对象。


具有相同随机数的DataFrame对象。


通过head()方法获得前五行。


通过tail()方法获得最后五行。

下面的代码说明了 Python 的比较运算符和逻辑运算符在两列值上的应用。

In [76]: df['x'] > 0.5  ![1](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/1.png)
Out[76]: 0     True
         1    False
         2    False
         3    False
         4     True
         5    False
         6    False
         7    False
         8    False
         9    False
         Name: x, dtype: bool
In [77]: (df['x'] > 0) & (df['y'] < 0)  ![2](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/2.png)
Out[77]: 0     True
         1    False
         2    False
         3     True
         4     True
         5    False
         6    False
         7    False
         8    False
         9    False
         dtype: bool
In [78]: (df['x'] > 0) | (df['y'] < 0)  ![3](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/3.png)
Out[78]: 0     True
         1     True
         2     True
         3     True
         4     True
         5    False
         6    False
         7     True
         8     True
         9     True
         dtype: bool


检查x列中的值是否大于 0.5。


检查x列中的值是否为正y列中的值是否为负。


检查x列中的值是否为正y列中的值是否为负。

使用结果布尔Series对象,复杂数据(行)的选择很简单。

In [79]: df[df['x'] > 0]  ![1](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/1.png)
Out[79]:           x         y
         0  1.189622 -1.690617
         3  0.007315 -0.612939
         4  1.299748 -1.733096
         9  0.108863  0.507810
In [80]: df[(df['x'] > 0) & (df['y'] < 0)]  ![2](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/2.png)
Out[80]:           x         y
         0  1.189622 -1.690617
         3  0.007315 -0.612939
         4  1.299748 -1.733096
In [81]: df[(df.x > 0) | (df.y < 0)]  ![3](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/3.png)
Out[81]:           x         y
         0  1.189622 -1.690617
         1 -1.356399 -1.232435
         2 -0.544439 -0.668172
         3  0.007315 -0.612939
         4  1.299748 -1.733096
         7 -1.188018 -0.549746
         8 -0.940046 -0.827932
         9  0.108863  0.507810


所有x列的值大于 0.5 的行。


所有x列的值为正y列的值为负的行。


所有列中 x 的值为正列中 y 的值为负的所有行(这里通过各自的属性访问列)。

比较运算符也可以一次应用于完整的 DataFrame 对象。

In [82]: df > 0  ![1](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/1.png)
Out[82]:        x      y
         0   True  False
         1  False  False
         2  False  False
         3   True  False
         4   True  False
         5  False   True
         6  False   True
         7  False  False
         8  False  False
         9   True   True
In [83]: df[df > 0]  ![2](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/2.png)
Out[83]:           x         y
         0  1.189622       NaN
         1       NaN       NaN
         2       NaN       NaN
         3  0.007315       NaN
         4  1.299748       NaN
         5       NaN  0.357508
         6       NaN  1.470714
         7       NaN       NaN
         8       NaN       NaN
         9  0.108863  0.507810


DataFrame 对象中哪些值是正数?


选择所有这样的值,并在所有其他位置放置 NaN

连接、合并和拼接

本节介绍了在形式上为 DataFrame 对象的两个简单数据集组合的不同方法。这两个简单数据集是:

In [84]: df1 = pd.DataFrame(['100', '200', '300', '400'],
                             index=['a', 'b', 'c', 'd'],
                             columns=['A',])
In [85]: df1
Out[85]:      A
         a  100
         b  200
         c  300
         d  400
In [86]: df2 = pd.DataFrame(['200', '150', '50'],
                             index=['f', 'b', 'd'],
                             columns=['B',])
In [87]: df2
Out[87]:      B
         f  200
         b  150
         d   50

拼接

拼接或附加基本上意味着将行从一个 DataFrame 对象添加到另一个 DataFrame 对象。这可以通过 append() 方法或 pd.concat() 函数完成。一个主要问题是如何处理索引值。

In [88]: df1.append(df2)  ![1](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/1.png)
Out[88]:      A    B
         a  100  NaN
         b  200  NaN
         c  300  NaN
         d  400  NaN
         f  NaN  200
         b  NaN  150
         d  NaN   50
In [89]: df1.append(df2, ignore_index=True)  ![2](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/2.png)
Out[89]:      A    B
         0  100  NaN
         1  200  NaN
         2  300  NaN
         3  400  NaN
         4  NaN  200
         5  NaN  150
         6  NaN   50
In [90]: pd.concat((df1, df2))  ![3](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/3.png)
Out[90]:      A    B
         a  100  NaN
         b  200  NaN
         c  300  NaN
         d  400  NaN
         f  NaN  200
         b  NaN  150
         d  NaN   50
In [91]: pd.concat((df1, df2), ignore_index=True)  ![4](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/4.png)
Out[91]:      A    B
         0  100  NaN
         1  200  NaN
         2  300  NaN
         3  400  NaN
         4  NaN  200
         5  NaN  150
         6  NaN   50


将来自 df2 的数据附加为 df1 的新行。


做同样的事情,但忽略了索引。


具有与第一个相同的效果,并且…


第二个追加操作,分别。

连接

在连接这两个数据集时,DataFrame 对象的顺序也很重要,但方式不同。只使用第一个 DataFrame 对象的索引值。这种默认行为称为左连接

In [92]: df1.join(df2)  ![1](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/1.png)
Out[92]:      A    B
         a  100  NaN
         b  200  150
         c  300  NaN
         d  400   50
In [93]: df2.join(df1)  ![2](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/2.png)
Out[93]:      B    A
         f  200  NaN
         b  150  200
         d   50  400


df1 的索引值相关。


df2 相关的索引值。

一共有四种不同的连接方法可用,每种方法都会导致索引值和相应数据行的处理方式不同。

In [94]: df1.join(df2, how='left')  ![1](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/1.png)
Out[94]:      A    B
         a  100  NaN
         b  200  150
         c  300  NaN
         d  400   50
In [95]: df1.join(df2, how='right')  ![2](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/2.png)
Out[95]:      A    B
         f  NaN  200
         b  200  150
         d  400   50
In [96]: df1.join(df2, how='inner')  ![3](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/3.png)
Out[96]:      A    B
         b  200  150
         d  400   50
In [97]: df1.join(df2, how='outer')  ![4](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/4.png)
Out[97]:      A    B
         a  100  NaN
         b  200  150
         c  300  NaN
         d  400   50
         f  NaN  200


左连接是默认操作。


右连接与颠倒 DataFrame 对象的顺序相同。


内连接仅保留那些在两个索引中都找到的索引值。


外连接保留来自两个索引的所有索引值。

也可以基于空的 DataFrame 对象进行连接。在这种情况下,列会被顺序创建,导致行为类似于左连接。

In [98]: df = pd.DataFrame()
In [99]: df['A'] = df1  ![1](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/1.png)
In [100]: df
Out[100]:      A
          0  NaN
          1  NaN
          2  NaN
          3  NaN
In [101]: df['B'] = df2  ![2](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/2.png)
In [102]: df
Out[102]:      A    B
          0  NaN  NaN
          1  NaN  NaN
          2  NaN  NaN
          3  NaN  NaN


df1 作为第一列 A


df2 作为第二列 B

利用字典组合数据集的方式产生了类似外连接的结果,因为列是同时创建的。

In [103]: df = pd.DataFrame({'A': df1['A'], 'B': df2['B']})  ![1](https://gitee.com/OpenDocCN/ibooker-quant-zh/raw/master/docs/py-fin-2e/img/1.png)
In [104]: df
Out[104]:      A    B
          a  100  NaN
          b  200  150
          c  300  NaN
          d  400   50
          f  NaN  200


DataFrame 对象的列被用作 dict 对象中的值。


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

相关文章
|
28天前
|
数据采集 数据可视化 数据挖掘
金融波动率的多模型建模研究:GARCH族与HAR模型的Python实现与对比分析
本文探讨了金融资产波动率建模中的三种主流方法:GARCH、GJR-GARCH和HAR模型,基于SPY的实际交易数据进行实证分析。GARCH模型捕捉波动率聚类特征,GJR-GARCH引入杠杆效应,HAR整合多时间尺度波动率信息。通过Python实现模型估计与性能比较,展示了各模型在风险管理、衍生品定价等领域的应用优势。
251 66
金融波动率的多模型建模研究:GARCH族与HAR模型的Python实现与对比分析
|
4月前
|
数据采集 人工智能 自然语言处理
AI Agent 金融助理0-1 Tutorial 利用Python实时查询股票API的FinanceAgent框架构建股票(美股/A股/港股) AI Finance Agent
金融领域Finance AI Agents方面的工作,发现很多行业需求和用户输入的 query都是和查询股价/行情/指数/财报汇总/金融理财建议相关。如果需要准确的 金融实时数据就不能只依赖LLM 来生成了。常规的方案包括 RAG (包括调用API )再把对应数据和prompt 一起拼接送给大模型来做文本生成。稳定的一些商业机构的金融数据API基本都是收费的,如果是以科研和demo性质有一些开放爬虫API可以使用。这里主要介绍一下 FinanceAgent,github地址 https://github.com/AI-Hub-Admin/FinanceAgent
|
5月前
|
机器学习/深度学习 数据采集 TensorFlow
使用Python实现智能金融市场预测
使用Python实现智能金融市场预测
60 0
|
6月前
|
人工智能 API Python
Openai python调用gpt测试代码
这篇文章提供了使用OpenAI的Python库调用GPT-4模型进行聊天的测试代码示例,包括如何设置API密钥、发送消息并接收AI回复。
|
7月前
|
机器学习/深度学习 存储 TensorFlow
使用Python实现深度学习模型:智能金融风控与信用评估
【7月更文挑战第25天】 使用Python实现深度学习模型:智能金融风控与信用评估
11284 7
|
7月前
|
数据可视化 Python
时间序列分析是一种统计方法,用于分析随时间变化的数据序列。在金融、经济学、气象学等领域,时间序列分析被广泛用于预测未来趋势、检测异常值、理解周期性模式等。在Python中,`statsmodels`模块是一个强大的工具,用于执行各种时间序列分析任务。
时间序列分析是一种统计方法,用于分析随时间变化的数据序列。在金融、经济学、气象学等领域,时间序列分析被广泛用于预测未来趋势、检测异常值、理解周期性模式等。在Python中,`statsmodels`模块是一个强大的工具,用于执行各种时间序列分析任务。
|
7月前
|
机器学习/深度学习 监控 算法
Python数据分析与机器学习在金融风控中的应用
Python数据分析与机器学习在金融风控中的应用
163 12
|
7月前
|
存储 机器学习/深度学习 关系型数据库
Python 金融编程第二版(四)(5)
Python 金融编程第二版(四)
32 0
|
7月前
|
存储 SQL 数据库
Python 金融编程第二版(四)(4)
Python 金融编程第二版(四)
45 0
|
7月前
|
SQL 存储 数据库
Python 金融编程第二版(四)(3)
Python 金融编程第二版(四)
26 0

热门文章

最新文章

推荐镜像

更多