win10下搭建zipline python3.5量化回测平台环境

1、安装 Anaconda

1.1 下载Anconda

我们在 Anaconda 的官网下载windows环境Anaconda3-5.2.0版本的64位安装包,对应conda版本是4.5.4。为什么下载这个版本,是因为zipline对环境的要求比较严格,如果版本不匹配,会出现不少问题。
官网下载地址:https://repo.anaconda.com/archive/Anaconda3-5.2.0-Windows-x86_64.exe,对应的conda版本4.5.4,python版本3.5.5。
清华镜像下载地址:https://mirrors.tuna.tsinghua.edu.cn/anaconda/archive/Anaconda3-5.2.0-Windows-x86_64.exe
说明:anaconda2对应的是python 2.x版本,anaconda3对应python 3.x版本。

1.2 安装

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

1.3 Anaconda Prompt

安装后会有一个Anaconda Prompt菜单项,运行类似于windows的终端操作,可以输入命令行。
在这里插入图片描述

1.4 检查安装

我们在Anaconda Prompt中检查conda信息


(base) C:\Users\lzc>conda info

     active environment : base
    active env location : d:\Anaconda3
            shell level : 1
       user config file : C:\Users\lzc\.condarc
 populated config files : C:\Users\lzc\.condarc
          conda version : 4.5.4
    conda-build version : 3.10.5
         python version : 3.6.5.final.0
       base environment : d:\Anaconda3  (writable)
           channel URLs : https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/pro/win-64
                          https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/pro/noarch
                          https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/pytorch/win-64
                          https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/pytorch/noarch
                          https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge/win-64
                          https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge/noarch
                          https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main/win-64
                          https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main/noarch
                          https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/win-64
                          https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/noarch
                          https://repo.anaconda.com/pkgs/main/win-64
                          https://repo.anaconda.com/pkgs/main/noarch
                          https://repo.anaconda.com/pkgs/free/win-64
                          https://repo.anaconda.com/pkgs/free/noarch
                          https://repo.anaconda.com/pkgs/r/win-64
                          https://repo.anaconda.com/pkgs/r/noarch
                          https://repo.anaconda.com/pkgs/pro/win-64
                          https://repo.anaconda.com/pkgs/pro/noarch
                          https://repo.anaconda.com/pkgs/msys2/win-64
                          https://repo.anaconda.com/pkgs/msys2/noarch
          package cache : d:\Anaconda3\pkgs
                          C:\Users\lzc\AppData\Local\conda\conda\pkgs
       envs directories : d:\Anaconda3\envs
                          C:\Users\lzc\AppData\Local\conda\conda\envs
                          C:\Users\lzc\.conda\envs
               platform : win-64
             user-agent : conda/4.5.4 requests/2.18.4 CPython/3.6.5 Windows/10 Windows/10.0.18362
          administrator : False
             netrc file : None
           offline mode : False
           

注意:检查conda版本为4.5.4,Python版本为3.6.5,用户配置目录为C:\Users\lzc\。请记住用户配置目录,后面会需要使用。
在这里插入图片描述

1.5 创建python3.5环境

首先,在Anaconda prompt中创建python3.5环境:

conda create -n env_zipline python=3.5

然后,在Anaconda prompt中激活刚才新添加的env_zipline环境:

activate env_zipline

最后,我们在Anaconda prompt中来检查是否切换成功:

python --version

2、安装zipline

2.1 添加下载频道

为防止安装时下载包比较慢的话,或因为网络出现下载错误时,我们先增加清华镜像,再继续安装。
安装下载错误描述:

CondaError: Downloaded bytes did not match Content-Length

添加清华源

conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main/
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge/
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/pytorch/
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/pro/
conda config --set show_channel_urls yes

2.2 安装zipline

conda install -c Quantopian zipline

检查是否安装成功

zipline run --help

输出响应信息,表示我们的安装成功了。

(env_zipline) C:\Users\lzc>zipline run --help
Usage: zipline run [OPTIONS]

  Run a backtest for the given algorithm.

Options:
  -f, --algofile FILENAME         The file that contains the algorithm to run.
  -t, --algotext TEXT             The algorithm script to run.
  -D, --define TEXT               Define a name to be bound in the namespace
                                  before executing the algotext. For example

3、安装PyCharm

PyCharm 是一款功能强大的 Python 编辑器,具有跨平台性。我们通过PyCharm来使用zipline。现在,我们来看下PyCharm 在 Windows下是如何安装的。

3.1 下载PyCharm(Windows)

首先,我们下载PyCharm,这是 PyCharm 的下载地址:http://www.jetbrains.com/pycharm/download。professional 是专业版,需要授权使用,community 是社区版,可以免费使用的。

3.2 安装PyCharm

下载好后进行安装,请记住安装路径。具体安装就不展开了

3.3 配置Anaconda

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

4、 使用zipline

我们通过PyCharm创建一个zipline来初次使用zipline。

4.1 创建工程

在PyCharm中,选择File->New Project创建一个工程pythonProject,在创建工程页面中,我们可以选择新建环境,选择使用Conda环境,Python version版本使用2.7,Conda executable选择前面我们所找到的conda所在目录,点击Create创建工程。
在这里插入图片描述
也可以选择使用已有环境,建设使用已有环境,点击Create创建工程。在这里插入图片描述

4.2 增加代码

在工程中增加名为main.py的Python文件

打开https://www.zipline.io/,找到使用zipline的示例代码并复制到main.py文件中,我们就通过这段代码来学习使用zipline。代码如下:

from zipline.api import order_target, record, symbol

def initialize(context):
    context.i = 0
    context.asset = symbol('AAPL')


def handle_data(context, data):
    # Skip first 300 days to get full windows
    context.i += 1
    if context.i < 300:
        return

    # Compute averages
    # data.history() has to be called with the same params
    # from above and returns a pandas dataframe.
    short_mavg = data.history(context.asset, 'price', bar_count=100, frequency="1d").mean()
    long_mavg = data.history(context.asset, 'price', bar_count=300, frequency="1d").mean()

    # Trading logic
    if short_mavg > long_mavg:
        # order_target orders as many shares as needed to
        # achieve the desired number of shares.
        order_target(context.asset, 100)
    elif short_mavg < long_mavg:
        order_target(context.asset, 0)

    # Save values for later inspection
    record(AAPL=data.current(context.asset, 'price'),
           short_mavg=short_mavg,
           long_mavg=long_mavg)

我们增加一些输出信息用来体验。

def handle_data(context, data):
    # Skip first 300 days to get full windows
    print ("index:%d" % context.i)	# 增加输出信息
    context.i += 1
    if context.i < 300:
        return

4.3 ingest数据

为了使用zipline进行回测,我们要获取数据源。由于zipline支持的国外数据源需要让终端翻墙,我们从CSV文件ingest数据。
我们参考https://www.zipline.io/bundles.html

4.3.1 创建cvsdir目录

在工程中创建cvsdir目录,在目录下创建daily日线目录,在日线目录下创建AAPL的cvs文件。
在这里插入图片描述

4.3.2 日线数据

把示例中的数据拷贝到这个文件中,示例数据如下:

date,open,high,low,close,volume,dividend,split
2012-01-03,58.485714,58.92857,58.42857,58.747143,75555200,0.0,1.0
2012-01-04,58.57143,59.240002,58.468571,59.062859,65005500,0.0,1.0
2012-01-05,59.278572,59.792858,58.952858,59.718571,67817400,0.0,1.0
2012-01-06,59.967144,60.392857,59.888573,60.342857,79573200,0.0,1.0
2012-01-09,60.785713,61.107143,60.192856,60.247143,98506100,0.0,1.0
2012-01-10,60.844284,60.857143,60.214287,60.462856,64549100,0.0,1.0
2012-01-11,60.382858,60.407143,59.901428,60.364285,53771200,0.0,1.0

4.3.3 extension.py文件

在工程中创建extension.py文件。
在这里插入图片描述
把示例中的数据拷贝到这个文件中,示例数据如下:
import库

import pandas as pd

from zipline.data.bundles import register
from zipline.data.bundles.csvdir import csvdir_equities

指定绑定数据的开始和结束时间

start_session = pd.Timestamp('2012-1-3', tz='utc')
end_session = pd.Timestamp('2012-1-11', tz='utc')

设置.csv文件所在目录并注册数据源

register(
    'custom-csvdir-bundle',
    csvdir_equities(
        ['daily'],
        'C:\\Users\\lzc\\PycharmProjects\\pythonProject3\\csvdir',
    ),
    calendar_name='NYSE', # US equities
    start_session=start_session,
    end_session=end_session
)

注意:C:\Users\lzc\PycharmProjects\pythonProject3\csvdir是我们前面放置日线文件AAPL.csv的目录。

4.3.4 ingest csv文件

我们把extension.py文件复制到用户配置目录的.zipline目录下
注意:先检查用户配置目录下是否有.zipline目录,没有先创建

mkdir C:\Users\lzc\.zipline
copy extension.py C:\Users\lzc\.zipline\extension.py

在PyCharmr的Terminal中执行ingest

zipline ingest -b custom-csvdir-bundle

在这里插入图片描述

4.3.5 查看可用Bundles

要查看我们可用的捆绑数据包,我们可以运行命令:

$ zipline bundles

我们可以看到我们刚才绑定的数据包:

(pythonProject3) C:\Users\lzc\PycharmProjects\pythonProject3>zipline bundles
csvdir <no ingestions>
custom-csvdir-bundle 2020-08-26 00:54:17.772000
quandl <no ingestions>
quantopian-quandl <no ingestions>

说明:Zipline默认bundle的存储路径在$ZIPLINE_ROOT/data/
这个工程对应的绑定数据存储在:
D:\anaconda2\envs\pythonProject3\Lib\site-packages\zipline\data\bundles

5 运行zipline

数据绑定好后我们就可以运行zipline来看看是否可以正常使用。
在这里插入图片描述
指令如下:

zipline run -f main.py --capital-base 1000 --start 2012-1-3 --end 2012-1-11 -b custom-csvdir-bundle -o dma.pickle --no-benchmark

我们看到的运行结果如下,里面有我们加的输出信息,表示zipline已经可以正常使用。

(pythonProject3) C:\Users\lzc\PycharmProjects\pythonProject3>zipline run -f main.py --capital-base 1000 --start 2012-1-3 --end 2012-1-11 -b custom-csvdir-bundle -o dma.pickle --no-benchmark
index:0
index:1
index:2
index:3
index:4
index:5
index:6
[2020-08-26 03:16:22.287000] INFO: zipline.finance.metrics.tracker: Simulated 7 trading days
first open: 2012-01-03 14:31:00+00:00
last close: 2012-01-11 21:00:00+00:00

到这时,zipline回测就可以初步使用了。

6 执行zipline示例策略

6.1 安装matplotlib

zipline示例需要matplotlib,我们通过下面的方面安装

conda install matplotlib 

6.2 运行buyapple.py策略

我们现在使用csv数据文件源来运行buyapple.py策略,命令如下:

zipline run -f ./examples/buyapple.py --capital-base 1000 --start 2012-1-3 --end 2012-1-11 -b custom-csvdir-bundle -o dma.pickle --no-benchmark

zipline使用matplotlib将股价与策略的运行结果绘制出来了,结果如下:
在这里插入图片描述

  • 1
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值