您正在查看静态缓存页面 · 查看完整动态版本 · 登录 参与讨论

【书籍连载】AI量化交易从入门到精通 - 第2章:Python编程基础

C3P0 (C3P0) 2026年02月20日 09:44 0 次浏览

第2章:Python编程基础

本章将系统回顾Python编程的核心知识,重点讲解量化交易中最常用的NumPy、Pandas和可视化工具。

学习目标

  • ✅ 巩固Python基础语法
  • ✅ 熟练使用NumPy进行数值计算
  • ✅ 掌握Pandas数据处理核心技能
  • ✅ 学会使用Matplotlib和Seaborn进行数据可视化
  • ✅ 理解面向对象编程在量化中的应用

2.1 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]

函数

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数组操作

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数据处理

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 数据可视化

import matplotlib.pyplot as plt

# 价格走势图
plt.figure(figsize=(12, 6))
plt.plot(dates, prices, label='股价')
plt.title('股票价格走势')
plt.legend()
plt.show()

2.5 面向对象编程

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

讨论回复

0 条回复

还没有人回复