前面 ,我们大致捋了一下思路,与演进步骤。 以及各个组件之间的差异(Backtrader与vnpy、Tushare与AKShare)。 最终决定先从基于Backtrader+AKShare开始我们的计划。

环境准备

版本依赖

  1. 目前 AKShare 仅支持 Python 3.7(64 位) 及以上版本, 这里推荐 Python 3.8.5(64 位) 版本
  2. 由于 Backtrader 的问题,此处要求 pip install matplotlib==3.2.2
  3. matplotlib 要求 FreeType version>=2.3、libpng

Ubuntu

准备一台虚拟机,安装UbuntuDesk镜像

系统安装完毕后,安装常用工具

sudo apt install -y vim libpng-dev zlib1g-dev

Python

正常情况下,Ubuntu系统是自带Python的。因为

# python3 --version
> Python 3.9.5

pip

# apt install python3-pip -y

AKShare

# pip install akshare -i http://mirrors.aliyun.com/pypi/simple/ --trusted-host=mirrors.aliyun.com --user --upgrade

后期更新命令

# pip install akshare --upgrade -i https://pypi.org/simple

Backtrader

pip install backtrader

FreeType

使用pip安装的是2.2.0,不满足matplotlib的要求。只能自己编译安装了

pip install freetype-py # 下载安装的是老版本的

源码编译

  • 处理依赖
pip install docwriter virtualenv -i http://mirrors.aliyun.com/pypi/simple/ --trusted-host=mirrors.aliyun.com
  • 下载源码
wget https://nchc.dl.sourceforge.net/project/freetype/freetype2/2.10.4/freetype-2.10.4.tar.xz
tar -Jxf freetype-2.10.4.tar.xz
  • 编译前准备
cd freetype-2.10.4/
./configure

./configure最好没有警告输出,如果有警告,尽量都处理掉

  • 编译

-j4的参数是设置CPU核心数

make -j4 && make install

matplotlib

用于输出图形

pip install matplotlib==3.2.2

测试

from datetime import datetime

import backtrader as bt  # 升级到最新版
import matplotlib.pyplot as plt  # 由于 Backtrader 的问题,此处要求 pip install matplotlib==3.2.2
import akshare as ak  # 升级到最新版
import pandas as pd

plt.rcParams["font.sans-serif"] = ["SimHei"]
plt.rcParams["axes.unicode_minus"] = False

# 利用 AKShare 获取股票的后复权数据,这里只获取前 6 列
stock_hfq_df = ak.stock_zh_a_hist(symbol="000001", adjust="hfq").iloc[:, :6]
# 处理字段命名,以符合 Backtrader 的要求
stock_hfq_df.columns = [
    'date',
    'open',
    'close',
    'high',
    'low',
    'volume',
]
# 把 date 作为日期索引,以符合 Backtrader 的要求
stock_hfq_df.index = pd.to_datetime(stock_hfq_df['date'])


class MyStrategy(bt.Strategy):
    """
    主策略程序
    """
    params = (("maperiod", 20),)  # 全局设定交易策略的参数

    def __init__(self):
        """
        初始化函数
        """
        self.data_close = self.datas[0].close  # 指定价格序列
        # 初始化交易指令、买卖价格和手续费
        self.order = None
        self.buy_price = None
        self.buy_comm = None
        # 添加移动均线指标
        self.sma = bt.indicators.SimpleMovingAverage(
            self.datas[0], period=self.params.maperiod
        )

    def next(self):
        """
        执行逻辑
        """
        if self.order:  # 检查是否有指令等待执行,
            return
        # 检查是否持仓
        if not self.position:  # 没有持仓
            if self.data_close[0] > self.sma[0]:  # 执行买入条件判断:收盘价格上涨突破20日均线
                self.order = self.buy(size=100)  # 执行买入
        else:
            if self.data_close[0] < self.sma[0]:  # 执行卖出条件判断:收盘价格跌破20日均线
                self.order = self.sell(size=100)  # 执行卖出


cerebro = bt.Cerebro()  # 初始化回测系统
start_date = datetime(1991, 4, 3)  # 回测开始时间
end_date = datetime(2020, 6, 16)  # 回测结束时间
data = bt.feeds.PandasData(dataname=stock_hfq_df, fromdate=start_date, todate=end_date)  # 加载数据
cerebro.adddata(data)  # 将数据传入回测系统
cerebro.addstrategy(MyStrategy)  # 将交易策略加载到回测系统中
start_cash = 1000000
cerebro.broker.setcash(start_cash)  # 设置初始资本为 100000
cerebro.broker.setcommission(commission=0.002)  # 设置交易手续费为 0.2%
cerebro.run()  # 运行回测系统

port_value = cerebro.broker.getvalue()  # 获取回测结束后的总资金
pnl = port_value - start_cash  # 盈亏统计

print(f"初始资金: {start_cash}\n回测期间:{start_date.strftime('%Y%m%d')}:{end_date.strftime('%Y%m%d')}")
print(f"总资金: {round(port_value, 2)}")
print(f"净收益: {round(pnl, 2)}")

cerebro.plot(style='candlestick')  # 画图

更多参考