本章将系统回顾Python编程的核心知识,重点讲解量化交易中最常用的NumPy、Pandas和可视化工具。
# 列表
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]
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}%")
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]
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()
import matplotlib.pyplot as plt
# 价格走势图
plt.figure(figsize=(12, 6))
plt.plot(dates, prices, label='股价')
plt.title('股票价格走势')
plt.legend()
plt.show()
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章
完整内容请访问代码仓:bookwriting/part1basics/part2_python/README.md
还没有人回复