# 第2章:Python编程基础
> 本章将系统回顾Python编程的核心知识,重点讲解量化交易中最常用的NumPy、Pandas和可视化工具。
## 学习目标
- ✅ 巩固Python基础语法
- ✅ 熟练使用NumPy进行数值计算
- ✅ 掌握Pandas数据处理核心技能
- ✅ 学会使用Matplotlib和Seaborn进行数据可视化
- ✅ 理解面向对象编程在量化中的应用
## 2.1 Python基础语法回顾
### 数据结构
```python
# 列表
stocks = ["600000", "000001", "000002"]
prices = [10.5, 11.0, 10.8, 11.2, 10.9]
# 字典
stock_info = {
"code": "600000",
"name": "浦发银行",
"price": 10.5
}
# 列表推导式
positive_returns = [r for r in returns if r > 0]
```
### 函数
```python
def calculate_return(buy_price, sell_price):
"""计算收益率"""
return (sell_price - buy_price) / buy_price * 100
# 使用
ret = calculate_return(10.0, 11.0)
print(f"收益率:{ret:.2f}%")
```
## 2.2 NumPy数组操作
```python
import numpy as np
# 创建数组
prices = np.array([10.5, 11.0, 10.8, 11.2, 10.9])
# 统计计算
print(f"平均值:{np.mean(prices)}")
print(f"标准差:{np.std(prices)}")
# 向量化计算
returns = (prices[1:] - prices[:-1]) / prices[:-1]
```
## 2.3 Pandas数据处理
```python
import pandas as pd
# 创建DataFrame
df = pd.DataFrame({
'code': ['600000', '000001', '000002'],
'price': [10.5, 15.2, 20.1],
'volume': [1000000, 800000, 600000]
})
# 计算移动平均
df['ma5'] = df['price'].rolling(5).mean()
# 分组统计
grouped = df.groupby('industry')['price'].mean()
```
## 2.4 数据可视化
```python
import matplotlib.pyplot as plt
# 价格走势图
plt.figure(figsize=(12, 6))
plt.plot(dates, prices, label='股价')
plt.title('股票价格走势')
plt.legend()
plt.show()
```
## 2.5 面向对象编程
```python
class Stock:
def __init__(self, code, name, price):
self.code = code
self.name = name
self.price = price
self.position = 0
def buy(self, shares):
self.position += shares
cost = shares * self.price
return cost
# 使用
stock = Stock("600000", "浦发银行", 10.5)
stock.buy(1000)
```
## 实战案例
完整的策略回测框架实现,包含:
- 策略基类设计
- 回测引擎实现
- 绩效指标计算
---
*本文节选自《AI量化交易从入门到精通》第2章*
*完整内容请访问代码仓:book_writing/part1_basics/part2_python/README.md*
登录后可参与表态
讨论回复
1 条回复
小凯 (C3P0)
#1
02-20 12:54
登录后可参与表态