Bohrium
robot
新建

空间站广场

论文
Notebooks
比赛
课程
Apps
我的主页
我的Notebooks
我的论文库
我的足迹

我的工作空间

任务
节点
文件
数据集
镜像
项目
数据库
公开
《量化投资》(二)量化投资策略:案例代码实现
量化交易
量化交易
chenwj
发布于 2023-09-27
推荐镜像 :Basic Image:ubuntu20.04-py3.10-cuda11.6
推荐机型 :c2_m4_cpu
1
《量化投资》(二)量化投资策略:案例代码实现
投资标的
调仓频率
投资信号建模
案例实战
投资策略与回测方案
安装依赖与加载数据
简单收益率与连续复利收益率
Profit and Loss 曲线

《量化投资》(二)量化投资策略:案例代码实现

代码
文本

Open In Bohrium

作者:Weijie Chen
时间:2023年11月6日

推荐镜像:ubuntu:20.04-py3.10-cuda11.6
推荐计算资源:CPU
内容:本教程主要基于孙健、吴岚、赵朝熠 编著的《量化投资》中的章节案例进行实现,帮助读者在纸质书以外有更好的实操体验,并能够直接运用本教程的代码进行自由的探索。
本教程
纯属娱乐
,不能对任何投资进行推荐或提供实际法律意见。如需投资建议,请先了解相关市场情况,并考虑自己的投资目标、风险承受能力等因素,在做出决策前请咨询投资专业人员。
使用方式:您可在 Bohrium Notebook 上直接运行。您可以点击界面上方蓝色按钮 开始连接,选择 ubuntu:20.04-py3.10-cuda11.6 镜像及任何一款节点配置,稍等片刻即可运行。如您遇到任何问题,请联系 bohrium@dp.tech
共享协议:本作品采用知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议进行许可。

代码
文本

专业性的金融投资都是一个从研究开始道最终落实资产配置的过程,量化投资与传统的投资方式的重要区别有以下三个方面:

  • 研究阶段的主要研究工具时应用数学、统计学和机器学习等非传统金融的工具,研究中更多地采用微观的市场交易数据
  • 资产配置策略的生成和实施都是基于计算机程序的自动过程
  • 策略表现的波动与传统投资比较常常是可控的、较低的

因此,量化投资应该是基于清晰的研究逻辑、程序化的配置和交易执行程序的投资全过程。

代码
文本

本章将开始介绍量化投资策略统一的组成要素:投资标的、调仓频率和投资信号,以及用于衡量策略的优劣的一系列常见评判指标

代码
文本

投资标的

代码
文本

投资标的是指投资者希望投资的资产,例如期货、期权和股票等。一般而言,投资着应当首先选择希望投资的自唱,再在选定的资产大类中选取适当的资产池,最后对资产池中的资产进行投资。不同大类的资产有不同的市场特征,因此投资者在面对不同资产大类时需要采取不同的投资理念和投资方法。

代码
文本

调仓频率

代码
文本

调仓频率是指投资者更换自己持仓的频率。在构建量化投资策略时,设定合适的调仓频率也十分重要,不同频率需要不同的投资理念与投资技术。调仓频率并没有统一的分类标准。除非特殊说明,本文将按照如下标准划分调仓频率:

  • 低频:周、月、年
  • 中频:小时、日
  • 高频:秒、分钟
代码
文本

低频投资者通常遵循价值投资的观念,他们往往依据宏观经济政策和基本面来指导投资。例如,如果投资者认为当前国家政策对医药板块利好,则该投资者可以选取一段时间内长期持有医药股,实现低频投资。

代码
文本

中频投资者对宏观政策与基本面的关注度弱于低频投资者,他们往往更关注一些日频技术指标的变化情况,对资产价格走势进行一些数学与统计分析。此外,中频投资者也可能从每日新闻中获取日频的投资信号。例如,如果互联网上突然出现对钢铁行业利好的新闻,螺纹钢期货的投资者可能会在一段时间内持有螺纹钢期货的多头,实现中频投资。

代码
文本

高频投资者往往不需要关注宏观政策与基本面,他们对高频数据(例如市场订单簿数据、下单和成交数据等)更为关注。例如,一位豆粕期货高频投资者发现当前交易所中买入某豆粕期货的订单量突然增加,他很可能立刻对此作出反应,例如可能会迅速向交易所发出一系列买单,随后在市场上的买入订单量上升到一定程度后在迅速卖出。

代码
文本

投资信号建模

代码
文本

投资信号主要是指与投资者实际操作有关的信号,例如投资者应当在何时、以多少资金、买入或卖出何种证券,买入卖出证券以后在什么时候平仓等等。投资信号的生成时量化投资的核心。 模型通常有两种来源:

  • 基于投资者对市场的认知
  • 基于数学与统计方法
代码
文本

案例实战

代码
文本

通过一个简单的投资实例,来深入理解量化投资策略的组成要素与回测方法中的评价指标。

本文将考察一种最简单的投资策略——“买入并持有”策略,将其应用于平安银行(000001)与万科A(000002)两只股票之上,并构造两者的等权重投资组合。

代码
文本

投资策略与回测方案

  • 投资标的:两只股票:平安银行(000001)与万科A(000002)

  • 初始资金:10万元

  • 具体策略:考察3种“买入并持有”策略

    (1)全部资金买入平安银行并持有到最终时刻

    (2)全部资金买入万科A并持有到最终时刻

    (3)将5万投资与平安银行,将5万投资与万科A,并持有到最终时刻

  • 调仓频率:买入并持有策略无需调仓

  • 回测时段:2011年初至2020年末

代码
文本

安装依赖与加载数据

代码
文本
[1]
!git clone https://github.com/tracyone/program_font
!pip install akshare pandas -i https://pypi.tuna.tsinghua.edu.cn/simple
!pip install scikit-learn numpy matplotlib statsmodels -i https://pypi.tuna.tsinghua.edu.cn/simple
fatal: destination path 'program_font' already exists and is not an empty directory.
Looking in indexes: https://pypi.tuna.tsinghua.edu.cn/simple
Collecting akshare
  Downloading https://pypi.tuna.tsinghua.edu.cn/packages/f2/68/48b6a560cc1b47c8c213c0b040fc16307550da9fd716f4135d25737736db/akshare-1.11.68-py3-none-any.whl (1.0 MB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 1.0/1.0 MB 11.9 MB/s eta 0:00:00a 0:00:01
Requirement already satisfied: pandas in /opt/mamba/lib/python3.10/site-packages (1.5.3)
Requirement already satisfied: beautifulsoup4>=4.9.1 in /opt/mamba/lib/python3.10/site-packages (from akshare) (4.11.2)
Collecting openpyxl>=3.0.3
  Downloading https://pypi.tuna.tsinghua.edu.cn/packages/6a/94/a59521de836ef0da54aaf50da6c4da8fb4072fb3053fa71f052fd9399e7a/openpyxl-3.1.2-py2.py3-none-any.whl (249 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 250.0/250.0 kB 25.0 MB/s eta 0:00:00
Collecting pypinyin>=0.35.0
  Downloading https://pypi.tuna.tsinghua.edu.cn/packages/00/fc/3e82bf38739a7b2c4f699245ce6c84ff254723c678c2cdc5d2ecbddf9afb/pypinyin-0.49.0-py2.py3-none-any.whl (1.4 MB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 1.4/1.4 MB 29.9 MB/s eta 0:00:0000:01
Requirement already satisfied: requests>=2.22.0 in /opt/mamba/lib/python3.10/site-packages (from akshare) (2.28.1)
Collecting jsonpath>=0.82
  Downloading https://pypi.tuna.tsinghua.edu.cn/packages/cf/a1/693351acd0a9edca4de9153372a65e75398898ea7f8a5c722ab00f464929/jsonpath-0.82.2.tar.gz (10 kB)
  Preparing metadata (setup.py) ... done
Collecting html5lib>=1.0.1
  Downloading https://pypi.tuna.tsinghua.edu.cn/packages/6c/dd/a834df6482147d48e225a49515aabc28974ad5a4ca3215c18a882565b028/html5lib-1.1-py2.py3-none-any.whl (112 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 112.2/112.2 kB 21.9 MB/s eta 0:00:00
Requirement already satisfied: tqdm>=4.43.0 in /opt/mamba/lib/python3.10/site-packages (from akshare) (4.64.1)
Collecting py-mini-racer>=0.6.0
  Downloading https://pypi.tuna.tsinghua.edu.cn/packages/29/a9/8ce0ca222ef04d602924a1e099be93f5435ca6f3294182a30574d4159ca2/py_mini_racer-0.6.0-py2.py3-none-manylinux1_x86_64.whl (5.4 MB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 5.4/5.4 MB 27.6 MB/s eta 0:00:0000:0100:01
Requirement already satisfied: decorator>=4.4.2 in /opt/mamba/lib/python3.10/site-packages (from akshare) (5.1.1)
Collecting lxml>=4.2.1
  Downloading https://pypi.tuna.tsinghua.edu.cn/packages/3c/d2/11533f0bc47ff4d828a20cfb702f3453fe714bd5b475fcdc8cec6e6b7dcf/lxml-4.9.3-cp310-cp310-manylinux_2_28_x86_64.whl (7.9 MB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 7.9/7.9 MB 35.5 MB/s eta 0:00:0000:0100:01
Collecting xlrd>=1.2.0
  Downloading https://pypi.tuna.tsinghua.edu.cn/packages/a6/0c/c2a72d51fe56e08a08acc85d13013558a2d793028ae7385448a6ccdfae64/xlrd-2.0.1-py2.py3-none-any.whl (96 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 96.5/96.5 kB 16.2 MB/s eta 0:00:00
Requirement already satisfied: urllib3>=1.25.8 in /opt/mamba/lib/python3.10/site-packages (from akshare) (1.26.11)
Collecting akracer>=0.0.11
  Downloading https://pypi.tuna.tsinghua.edu.cn/packages/15/86/6ef05f0b51a36dbec2b260da7a93ed0096dea32e708e127c5051b875af2d/akracer-0.0.13-py3-none-any.whl (10.1 MB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 10.1/10.1 MB 35.1 MB/s eta 0:00:0000:010:01
Collecting tabulate>=0.8.6
  Downloading https://pypi.tuna.tsinghua.edu.cn/packages/40/44/4a5f08c96eb108af5cb50b41f76142f0afa346dfa99d5296fe7202a11854/tabulate-0.9.0-py3-none-any.whl (35 kB)
Requirement already satisfied: pytz>=2020.1 in /opt/mamba/lib/python3.10/site-packages (from pandas) (2022.7.1)
Requirement already satisfied: python-dateutil>=2.8.1 in /opt/mamba/lib/python3.10/site-packages (from pandas) (2.8.2)
Requirement already satisfied: numpy>=1.21.0 in /opt/mamba/lib/python3.10/site-packages (from pandas) (1.24.2)
Requirement already satisfied: soupsieve>1.2 in /opt/mamba/lib/python3.10/site-packages (from beautifulsoup4>=4.9.1->akshare) (2.4)
Requirement already satisfied: webencodings in /opt/mamba/lib/python3.10/site-packages (from html5lib>=1.0.1->akshare) (0.5.1)
Requirement already satisfied: six>=1.9 in /opt/mamba/lib/python3.10/site-packages (from html5lib>=1.0.1->akshare) (1.16.0)
Collecting et-xmlfile
  Downloading https://pypi.tuna.tsinghua.edu.cn/packages/96/c2/3dd434b0108730014f1b96fd286040dc3bcb70066346f7e01ec2ac95865f/et_xmlfile-1.1.0-py3-none-any.whl (4.7 kB)
Requirement already satisfied: idna<4,>=2.5 in /opt/mamba/lib/python3.10/site-packages (from requests>=2.22.0->akshare) (3.4)
Requirement already satisfied: certifi>=2017.4.17 in /opt/mamba/lib/python3.10/site-packages (from requests>=2.22.0->akshare) (2022.9.24)
Requirement already satisfied: charset-normalizer<3,>=2 in /opt/mamba/lib/python3.10/site-packages (from requests>=2.22.0->akshare) (2.1.1)
Building wheels for collected packages: jsonpath
  Building wheel for jsonpath (setup.py) ... done
  Created wheel for jsonpath: filename=jsonpath-0.82.2-py3-none-any.whl size=5616 sha256=2614424d65dc985295639daf5fa54c9de6bbc114c4ee2040a2dac1e08cdcd09c
  Stored in directory: /root/.cache/pip/wheels/28/fb/b5/a64ec562a7c8250eb875515cd5acdd8fc10a5625d1b096f25c
Successfully built jsonpath
Installing collected packages: py-mini-racer, jsonpath, xlrd, tabulate, pypinyin, lxml, html5lib, et-xmlfile, akracer, openpyxl, akshare
Successfully installed akracer-0.0.13 akshare-1.11.68 et-xmlfile-1.1.0 html5lib-1.1 jsonpath-0.82.2 lxml-4.9.3 openpyxl-3.1.2 py-mini-racer-0.6.0 pypinyin-0.49.0 tabulate-0.9.0 xlrd-2.0.1
WARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv
Looking in indexes: https://pypi.tuna.tsinghua.edu.cn/simple
Collecting scikit-learn
  Downloading https://pypi.tuna.tsinghua.edu.cn/packages/d0/0b/26ad95cf0b747be967b15fb71a06f5ac67aba0fd2f9cd174de6edefc4674/scikit_learn-1.3.2-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (10.8 MB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 10.8/10.8 MB 31.9 MB/s eta 0:00:0000:0100:01
Requirement already satisfied: numpy in /opt/mamba/lib/python3.10/site-packages (1.24.2)
Collecting matplotlib
  Downloading https://pypi.tuna.tsinghua.edu.cn/packages/49/74/544b327ca211fe2c484aa6fb3264d6cf8ee994594c86ab110cfd9cf0eb2b/matplotlib-3.8.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (11.6 MB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 11.6/11.6 MB 35.3 MB/s eta 0:00:0000:0100:01
Collecting statsmodels
  Downloading https://pypi.tuna.tsinghua.edu.cn/packages/d5/22/62831c11096ef030e35424326716d47d65d5f7eb323966c9e4725324770d/statsmodels-0.14.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (10.1 MB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 10.1/10.1 MB 24.1 MB/s eta 0:00:0000:010:01
Requirement already satisfied: scipy>=1.5.0 in /opt/mamba/lib/python3.10/site-packages (from scikit-learn) (1.10.1)
Collecting joblib>=1.1.1
  Downloading https://pypi.tuna.tsinghua.edu.cn/packages/10/40/d551139c85db202f1f384ba8bcf96aca2f329440a844f924c8a0040b6d02/joblib-1.3.2-py3-none-any.whl (302 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 302.2/302.2 kB 43.7 MB/s eta 0:00:00
Collecting threadpoolctl>=2.0.0
  Downloading https://pypi.tuna.tsinghua.edu.cn/packages/81/12/fd4dea011af9d69e1cad05c75f3f7202cdcbeac9b712eea58ca779a72865/threadpoolctl-3.2.0-py3-none-any.whl (15 kB)
Collecting pyparsing>=2.3.1
  Downloading https://pypi.tuna.tsinghua.edu.cn/packages/39/92/8486ede85fcc088f1b3dba4ce92dd29d126fd96b0008ea213167940a2475/pyparsing-3.1.1-py3-none-any.whl (103 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 103.1/103.1 kB 23.7 MB/s eta 0:00:00
Collecting fonttools>=4.22.0
  Downloading https://pypi.tuna.tsinghua.edu.cn/packages/d7/a2/87f8aba1cac5523d212aefb4fbbdd7a9c24e7cac9ad8f7128f3c41f4762d/fonttools-4.44.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (4.5 MB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 4.5/4.5 MB 38.1 MB/s eta 0:00:0000:0100:01
Collecting cycler>=0.10
  Downloading https://pypi.tuna.tsinghua.edu.cn/packages/e7/05/c19819d5e3d95294a6f5947fb9b9629efb316b96de511b418c53d245aae6/cycler-0.12.1-py3-none-any.whl (8.3 kB)
Collecting pillow>=8
  Downloading https://pypi.tuna.tsinghua.edu.cn/packages/e5/b9/5c6ad3241f1ccca4b781dfeddbab2dac4480f95aedc351a0e60c9f4c8aa9/Pillow-10.1.0-cp310-cp310-manylinux_2_28_x86_64.whl (3.6 MB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 3.6/3.6 MB 38.9 MB/s eta 0:00:00a 0:00:01
Requirement already satisfied: packaging>=20.0 in /opt/mamba/lib/python3.10/site-packages (from matplotlib) (23.0)
Collecting kiwisolver>=1.3.1
  Downloading https://pypi.tuna.tsinghua.edu.cn/packages/6f/40/4ab1fdb57fced80ce5903f04ae1aed7c1d5939dda4fd0c0aa526c12fe28a/kiwisolver-1.4.5-cp310-cp310-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (1.6 MB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 1.6/1.6 MB 34.3 MB/s eta 0:00:0000:01
Collecting contourpy>=1.0.1
  Downloading https://pypi.tuna.tsinghua.edu.cn/packages/58/56/e2c43dcfa1f9c7db4d5e3d6f5134b24ed953f4e2133a4b12f0062148db58/contourpy-1.2.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (310 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 310.7/310.7 kB 45.0 MB/s eta 0:00:00
Requirement already satisfied: python-dateutil>=2.7 in /opt/mamba/lib/python3.10/site-packages (from matplotlib) (2.8.2)
Collecting patsy>=0.5.2
  Downloading https://pypi.tuna.tsinghua.edu.cn/packages/2a/e4/b3263b0e353f2be7b14f044d57874490c9cef1798a435f038683acea5c98/patsy-0.5.3-py2.py3-none-any.whl (233 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 233.8/233.8 kB 47.6 MB/s eta 0:00:00
Requirement already satisfied: pandas>=1.0 in /opt/mamba/lib/python3.10/site-packages (from statsmodels) (1.5.3)
Requirement already satisfied: pytz>=2020.1 in /opt/mamba/lib/python3.10/site-packages (from pandas>=1.0->statsmodels) (2022.7.1)
Requirement already satisfied: six in /opt/mamba/lib/python3.10/site-packages (from patsy>=0.5.2->statsmodels) (1.16.0)
Installing collected packages: threadpoolctl, pyparsing, pillow, patsy, kiwisolver, joblib, fonttools, cycler, contourpy, scikit-learn, matplotlib, statsmodels
Successfully installed contourpy-1.2.0 cycler-0.12.1 fonttools-4.44.0 joblib-1.3.2 kiwisolver-1.4.5 matplotlib-3.8.1 patsy-0.5.3 pillow-10.1.0 pyparsing-3.1.1 scikit-learn-1.3.2 statsmodels-0.14.0 threadpoolctl-3.2.0
WARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv
代码
文本
[2]
import akshare as ak
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from itertools import cycle
from statsmodels.tsa.stattools import coint

import matplotlib
matplotlib.font_manager.fontManager.addfont("/data/program_font/simhei.ttf")
plt.rcParams['font.sans-serif']='SimHei'
plt.rcParams['axes.unicode_minus'] = False
/opt/mamba/lib/python3.10/site-packages/akshare/__init__.py:2598: UserWarning: 为了支持更多特性,请将 Pandas 升级到 2.1.0 及以上版本!
  warnings.warn(
代码
文本
[78]
# 平安银行
target1="000001"
stock1 = ak.stock_zh_a_hist(symbol=target1, period="daily", start_date="20101231", end_date='20201231', adjust="hfq")
stock1.index = pd.to_datetime(stock1['日期'])
stock1.head()
日期 开盘 收盘 最高 最低 成交量 成交额 振幅 涨跌幅 涨跌额 换手率
日期
2010-12-31 2010-12-31 883.27 889.74 894.44 877.98 240891 3.783178e+08 1.86 0.80 7.06 0.78
2011-01-04 2011-01-04 891.50 903.26 912.66 881.51 358841 5.733437e+08 3.50 1.52 13.52 1.16
2011-01-05 2011-01-05 901.50 897.97 909.73 896.79 237463 3.798691e+08 1.43 -0.59 -5.29 0.76
2011-01-06 2011-01-06 897.97 890.91 906.79 884.45 206531 3.271489e+08 2.49 -0.79 -7.06 0.67
2011-01-07 2011-01-07 890.33 926.19 947.94 884.45 770482 1.263299e+09 7.13 3.96 35.28 2.48
代码
文本
[79]
# 万科A
target2="000002"
stock2 = ak.stock_zh_a_hist(symbol=target2, period="daily", start_date="20101231", end_date='20201231', adjust="hfq")
stock2.index = pd.to_datetime(stock2['日期'])
stock2.head()
日期 开盘 收盘 最高 最低 成交量 成交额 振幅 涨跌幅 涨跌额 换手率
日期
2010-12-31 2010-12-31 1097.49 1107.96 1110.58 1089.63 641895 5.243133e+08 1.91 0.83 9.16 0.66
2011-01-04 2011-01-04 1114.50 1183.89 1207.45 1109.27 1888161 1.645667e+09 8.86 6.85 75.93 1.95
2011-01-05 2011-01-05 1179.96 1187.81 1207.45 1161.63 1256163 1.112759e+09 3.87 0.33 3.92 1.30
2011-01-06 2011-01-06 1194.36 1189.12 1207.45 1169.49 791284 7.002034e+08 3.20 0.11 1.31 0.82
2011-01-07 2011-01-07 1189.12 1195.67 1236.25 1181.27 1447216 1.307916e+09 4.62 0.55 6.55 1.50
代码
文本
[80]
data = pd.merge(stock1["收盘"], stock2["收盘"], left_index=True, right_index=True)
data.columns = ["平安银行", "万科A"]
代码
文本
[81]
#构建组合portfolio
factor = (50000/data["万科A"][0])/(50000/data["平安银行"][0]+50000/data["万科A"][0])
data['portfolio'] = (1-factor)*data["平安银行"]+(factor)*data["万科A"]
data.head()
平安银行 万科A portfolio
日期
2010-12-31 889.74 1107.96 986.931301
2011-01-04 903.26 1183.89 1028.247604
2011-01-05 897.97 1187.81 1027.059574
2011-01-06 890.91 1189.12 1023.727423
2011-01-07 926.19 1195.67 1046.211592
代码
文本
[82]
# 上证指数
indexA = ak.index_zh_a_hist(symbol="000001", period="daily", start_date="20101231", end_date='20201231')
indexA.index = pd.to_datetime(indexA['日期'])
indexA.head()
日期 开盘 收盘 最高 最低 成交量 成交额 振幅 涨跌幅 涨跌额 换手率
日期
2010-12-31 2010-12-31 2759.16 2808.08 2808.93 2758.13 94574606 1.097282e+11 1.84 1.76 48.51 0.21
2011-01-04 2011-01-04 2825.33 2852.65 2855.40 2810.11 122603786 1.470993e+11 1.61 1.59 44.57 0.27
2011-01-05 2011-01-05 2833.12 2838.59 2850.49 2824.30 115080018 1.366056e+11 0.92 -0.49 -14.06 0.26
2011-01-06 2011-01-06 2838.44 2824.20 2853.88 2816.95 93262308 1.143931e+11 1.30 -0.51 -14.39 0.21
2011-01-07 2011-01-07 2820.67 2838.80 2868.00 2807.87 130892453 1.393085e+11 2.13 0.52 14.60 0.29
代码
文本
[83]
data = pd.merge(data, indexA["收盘"], left_index = True, right_index = True)
data.columns = ["平安银行", "万科A", "portfolio", "上证指数"]
data.head()
平安银行 万科A portfolio 上证指数
日期
2010-12-31 889.74 1107.96 986.931301 2808.08
2011-01-04 903.26 1183.89 1028.247604 2852.65
2011-01-05 897.97 1187.81 1027.059574 2838.59
2011-01-06 890.91 1189.12 1023.727423 2824.20
2011-01-07 926.19 1195.67 1046.211592 2838.80
代码
文本

简单收益率与连续复利收益率

假设投资者初始持有的总资产价值为,经过T期的投资后,资产总价值变为

  • 简单收益率

  • 连续复利收益率

代码
文本
[88]
def cal_annual_log_return(data):
log_return = np.log(data)-np.log(data.shift(1))
annual_log_return_mean = log_return.resample('y').mean() * 252
annual_log_return_std = log_return.resample('y').std() * np.sqrt(252)
return annual_log_return_mean.values[1:], annual_log_return_std.values[1:]
代码
文本
[91]
all_year_crr1, all_year_crr_std1 = cal_annual_log_return(data["平安银行"])
all_year_crr2, all_year_crr_std2 = cal_annual_log_return(data["万科A"])
all_year_crr3, all_year_crr_std3 = cal_annual_log_return(data["portfolio"])
all_year_crr0, all_year_crr_std0 = cal_annual_log_return(data["上证指数"])
代码
文本
[92]
plt.plot(np.arange(2011,2021), all_year_crr1, label="平安银行")
plt.plot(np.arange(2011,2021), all_year_crr2, label="万科A")
plt.plot(np.arange(2011,2021), all_year_crr3, label="等权重组合")
plt.plot(np.arange(2011,2021), all_year_crr0, label="上证指数")
plt.title("各年平均收益率(%)")
plt.legend()
plt.grid()
plt.show()
代码
文本
[93]
plt.plot(np.arange(2011,2021), all_year_crr_std1, label="平安银行")
plt.plot(np.arange(2011,2021), all_year_crr_std2, label="万科A")
plt.plot(np.arange(2011,2021), all_year_crr_std3, label="等权重组合")
plt.plot(np.arange(2011,2021), all_year_crr_std0, label="上证指数")
plt.title("各年收益率标准差(%)")
plt.legend()
plt.grid()
plt.show()
代码
文本

沿纵向比较可以发现,等权重组合的收益率标准差通常低于单独持有平安银行或者单独持有万科A的标准差;而上证指数收益率标准差在这十年内大部分时间都低于三种策略的标准差。因此,我们可以总结出一个规律:适当增加投资组合中的资产,有助于降低投资组合整体的风险。

代码
文本

Profit and Loss 曲线

代码
文本
[102]
# PNL曲线

log_return = np.log(data)-np.log(data.shift(1))
money_list = np.exp(log_return).cumprod()
money_list = money_list*10

plt.figure(figsize = (20,10))
plt.grid()
plt.plot(money_list['portfolio'], linewidth = 5, label = '等权重组合')
plt.plot(money_list['平安银行'], linewidth = 4, linestyle = '-.', label = '平安银行')
plt.plot(money_list['万科A'], linewidth = 4, linestyle = ':', label = '万科A')
plt.plot(money_list['上证指数'], linewidth = 3, linestyle = '--', label = '上证指数')
plt.ylabel(r'资金量 $V_t$ (万元)', fontsize = 30)
plt.xlabel(r'时间', fontsize = 30)
plt.legend(fontsize = 30, loc = 'upper left')
plt.show()
代码
文本

从10年间累计收益来看,等权重组合的收益介于单独持有万科和单独持有平安银行之间;而上证指数10年间几乎没有显著的收益!!!A股10年3000点不是梦!!!

代码
文本
[ ]

代码
文本
量化交易
量化交易
点个赞吧
本文被以下合集收录
量化交易
sai_xu
更新于 2024-06-29
3 篇1 人关注
推荐阅读
公开
基于Torchmd实现伞型采样计算自由能
notebookMDPyTorchfree energyTutorial
notebookMDPyTorchfree energyTutorial
许晓虎
发布于 2023-11-10
9 赞7 转存文件
公开
CALYPSO_SaaS 快速上手
CALYPSO中文Tutorial工作流
CALYPSO中文Tutorial工作流
小锡兵
发布于 2023-08-01
1 赞28 转存文件