一个使用 Python 3.11 + uv + talipp 构建的简单回测框架。
- 使用 uv 进行快速依赖管理和脚本运行
- 集成 talipp 技术指标库
- 简单易用的回测引擎
- 完整的性能指标计算
- 支持自定义交易策略
确保已安装 uv,然后:
# 克隆或进入项目目录 cd TeBacktest # 依赖已经配置好,uv 会自动安装
从 Binance Vision 下载 BTCUSDT 30分钟K线数据(2022-09 至 2025-09):
uv run download_data.py
数据将保存到 data/raw/ 目录。
uv run main.py
- 在
strategies/目录下创建新的策略文件 - 继承
Strategy基类 - 实现
init()和next()方法
示例:
from backtest.strategy import Strategy from talipp.indicators import SMA import pandas as pd class MyStrategy(Strategy): def __init__(self): super().__init__(name="MyStrategy") self.sma = None def init(self, data: pd.DataFrame): # 初始化指标 self.sma = SMA(20) for _, row in data.iterrows(): self.sma.add(float(row["close"])) def next(self, index: int, row: pd.Series): # 生成交易信号 if len(self.sma) < 20: return None current_price = row["close"] sma_value = self.sma[-1] if current_price > sma_value: return "buy" elif current_price < sma_value: return "sell" return None
TeBacktest/
├── backtest/ # 回测核心模块
│ ├── __init__.py
│ ├── data_loader.py # 数据加载器
│ ├── engine.py # 回测引擎
│ ├── strategy.py # 策略基类
│ └── metrics.py # 性能指标
├── strategies/ # 交易策略
│ ├── __init__.py
│ └── ma_crossover.py # MA交叉策略示例
├── data/ # 数据目录
│ └── raw/ # 原始K线数据
├── download_data.py # 数据下载脚本
├── main.py # 主程序
└── pyproject.toml # 项目配置
内置的移动平均线交叉策略包含:
- 快速/慢速移动平均线交叉
- RSI 过滤器(避免超买区域买入)
- 可配置参数:
fast_period: 快速MA周期(默认10)slow_period: 慢速MA周期(默认30)rsi_period: RSI周期(默认14)rsi_overbought: RSI超买阈值(默认75)
回测完成后会显示以下指标:
- 总收益率
- 总交易次数
- 胜率
- 平均盈利/亏损
- 盈亏比
- 最大回撤
- 夏普比率
- Python 3.11+
- pandas
- talipp
- requests
MIT