推荐几个超实用的量化 Python 库,顺便附上代码示例,保准让你看得爽、用得爽!

一、NumPy

咱量化分析的 “顶梁柱”,数组操作那叫一个酸爽,矩阵运算快得飞起。

代码示例 1:简单数组运算

1
2
3
4
5
6
7
8
9
10
11
12
13
import numpy as np

# 创建一个价格数组
prices = np.array([100, 102, 101, 105, 108])
print(f"股票价格:{prices}")

# 计算简单回报率
returns = np.diff(prices) / prices[:-1]
print(f"简单回报率:{returns}")

# 计算平均回报率
avg_return = np.mean(returns)
print(f"平均回报率:{avg_return:.2%}")

代码示例 2:矩阵点积运算

1
2
3
4
5
6
7
8
9
10
11
import numpy as np

# 创建两个矩阵
a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6], [7, 8]])
print(f"矩阵 <br/>A:\n{a}")
print(f"矩阵 b:\n{b}")

# 计算矩阵点积
dot_product = np.dot(a, b)
print(f"矩阵点积:\n{dot_product}")

二、Pandas

金融时间序列分析的 “神器”,能把杂乱无章的数据收拾得妥妥帖帖。

代码示例 1:创建金融数据 DataFrame

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import pandas as pd

# 创建金融数据字典
data = {
'Open': [100, 101, 102],
'High': [103, 104, 105],
'Low': [99, 100, 101],
'Close': [102, 103, 104],
'Volume': [10000, 15000, 12000]
}

# 将字典转换为 DataFrame
df = pd.DataFrame(data)
print(f"金融数据 DataFrame:\n{df}")

# 添加日期索引
df['Date'] = pd.date_range(start='2024-01-01', periods=3)
df.set_index('Date', inplace=True)
print(f"带日期索引的 DataFrame:\n{df}")

代码示例 2:计算滚动窗口均值

1
2
3
4
5
6
7
8
9
10
11
12
13
import pandas as pd

# 创建价格数据
data = {'Price': [100, 102, 101, 105, 108, 106, 107]}
df = pd.DataFrame(data)

# 计算 3 日滚动均值
df['3-day MA'] = df['Price'].rolling(window=3).mean()
print(f"3 日滚动均值:\n{df}")

# 计算 5 日滚动均值
df['5-day MA'] = df['Price'].rolling(window=5).mean()
print(f"5 日滚动均值:\n{df}")

三、Matplotlib

咱画图的 “看家法宝”,能把枯燥的数据变成绚丽的图表,让分析结果一目了然。

代码示例 1:绘制价格时间序列图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import matplotlib.pyplot as plt

# 股票价格数据
prices = [100, 102, 101, 105, 108, 106, 107, 109, 112, 110]
dates = list(range(1, 11)) # 简单的日期索引

# 绘制价格时间序列图
plt.plot(dates, prices, marker='o', linestyle='-', color='b', label='股票价格')
plt.title('股票价格走势')
plt.xlabel('日期')
plt.ylabel('价格')
plt.grid(True)
plt.legend()
plt.show()

代码示例 2:绘制柱状图

1
2
3
4
5
6
7
8
9
10
11
12
13
import matplotlib.pyplot as plt

# 数据类别和值
categories = ['股票', '债券', '黄金', '外汇']
values = [10, 15, 7, 12]

# 绘制柱状图
plt.bar(categories, values, color=['blue', 'green', 'orange', 'purple'])
plt.title('投资组合分布')
plt.xlabel('资产类别')
plt.ylabel('投资比例')
plt.grid(axis='y')
plt.show()

四、TA-Lib

技术分析的 “大杀器”,各种技术指标应有尽有,调用起来那叫一个爽。

代码示例 1:计算相对强弱指数(RSI)

1
2
3
4
5
6
7
8
9
10
11
import talib as ta
import numpy as np

# 生成随机价格数据
np.random.seed(42)
prices = np.random.random(100) * 100 # 生成 100 个随机价格,范围 0-100
print(f"随机价格数据:\n{prices}")

# 计算 RSI(相对强弱指数)
rsi = ta.RSI(prices, timeperiod=14)
print(f"RSI 指标:\n{rsi}")

代码示例 2:计算移动平均线

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import talib as ta
import numpy as np

# 生成随机价格数据
np.random.seed(42)
prices = np.random.random(100) * 100 # 生成 100 个随机价格,范围 0-100

# 计算简单移动平均线(SMA)
sma = ta.SMA(prices, timeperiod=10)
print(f"简单移动平均线:\n{sma}")

# 计算指数移动平均线(EMA)
ema = ta.EMA(prices, timeperiod=10)
print(f"指数移动平均线:\n{ema}")

五、Zipline

回测的 “专业户”,能让你轻松模拟交易策略,看看它到底行不行。

代码示例 1:简单买入策略

1
2
3
4
5
6
7
8
9
10
11
12
13
from zipline import run_algorithm
from zipline.api import order, symbol

# 初始化函数
def initialize(context):
context.asset = symbol('AAPL') # 设置目标股票为苹果公司

# 每日处理函数
def handle_data(context, data):
order(context.asset, 10) # 每天买入 10 股苹果股票

# 运行算法(实际使用时需设置好参数)
# run_algorithm(start='2024-01-01', end='2024-12-31', initialize=initialize, handle_data=handle_data, capital_base=100000)

代码示例 2:移动平均线交叉策略

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
from zipline import run_algorithm
from zipline.api import order_target, record, symbol
import pandas as pd

# 初始化函数
def initialize(context):
context.asset = symbol('AAPL') # 设置目标股票为苹果公司
context.short_window = 20 # 设置短期窗口
context.long_window = 40 # 设置长期窗口

# 每日处理函数
def handle_data(context, data):
# 获取历史价格数据
prices = data.history(context.asset, 'price', bar_count=context.long_window, frequency='1d')

# 计算短期和长期移动平均线
short_ma = prices[-context.short_window:].mean()
long_ma = prices.mean()

# 执行交易逻辑
if short_ma > long_ma:
order_target(context.asset, 100) # 买入信号,目标持有 100 股
elif short_ma < long_ma:
order_target(context.asset, 0) # 卖出信号,清仓

# 记录数据供后续分析
record(AAPL_price=data.current(context.asset, 'price'), short_ma=short_ma, long_ma=long_ma)

# 运行算法(实际使用时需设置好参数)
# run_algorithm(start='2024-01-01', end='2024-12-31', initialize=initialize, handle_data=handle_data, capital_base=100000)

以上就是本期量化 Python 库推荐及代码示例啦,希望能帮到你,要是觉得不错,记得给个👍哦!咱们下次继续整活儿!

相关阅读

扫一扫,领红包

美团红包

🎓 AI 编程实战课程

程序员晚枫专注AI编程培训,通过 《30讲 · AI编程训练营》,让小白也能用AI做出实际项目。帮你从零上手!