Welcome to quantlib’s documentation!¶
Tutorial¶
Wind Data¶
直接从万得SQL数据库查询数据,需要设置数据库连接信息。
配置信息¶
使用万得数据库需要配置数据库对应的连接信息。
配置文件``~/.quantlib/config.cfg``:
基本用法¶
股票基本信息¶
from quant.data import wind
wind.get_stock_basics()
量价数据¶
wind.get_wind_data("AShareEODPrices", "s_dq_pctchange")
格式为wind.get_wind_data(表名,列名),会以trade_dt为index,s_info_windcode为column重新排列数据。
日衍生数据¶
# 获取A股个股市值
wind.get_wind_data("AShareEODDerivativeIndicator", "s_val_mv")
万得数据库原始表¶
wind.get_wind_table("AShareEODPrices", ["s_info_windcode", "trade_dt", "s_dq_adjclose", "s_dq_adjopen"])
获取指数权重¶
# 获取中证500指数的免费权重
wind.get_index_weight("AIndexHS300FreeWeight", "000905.SH")
获取A股特殊处理信息¶
# AShareST表示通过entry_dt和remove_dt来维护股票进入ST和离开ST的时间的
# arrange_entry_table把该信息重新整理成以交易日为行、股票为列的“交易日”表
# 最后把剩下的NA用False填充
wind.arrange_entry_table("AShareST").fillna(False)
获取分析师预测数据¶
# 获取预测一年的平均每股收益
wind.get_consensus_data('eps_avg', 1)
获取股票行业分类¶
# 获取中国A股中信行业分类 (一级分类)
wind.get_stock_industries("AShareIndustriesClassCITICS", 1)
quant.backtest¶
起步¶
一个简单的股票回测程序只需要继承一个抽象策略类,定义一个选股策略就可以,一个简单的例子是:
from quant.backtest.stock.strategy import AbstractStrategy
class SimpleStrategy(AbstractStrategy):
start_date = "2017-03-01"
def handle(self, today, universe):
self.change_position({universe[0]: 0.1})
这个简单的策略定义了从2017年3月开始回测,每天选择可选股票池中的第一只股票买入10%的仓位。 运行``SimpleStrategy().run()``运行回测,几秒钟后,会输出简单的年化收益率、年化波动率和夏普率信息。 同时,还会生成一个以策略名和运行时间命名的网页,记录着回测的详细信息。如果是在视窗环境下的话,浏览器会自动打开该网页。如图所示。

回测方法¶
quantlib提供`quant.backtest.strategy.Strategy`类作为所有策略的基类。用户可以继承该类并通过重载`__init__`方法和`handle`方法来自定义策略的行为。 另外,quantlib也提供SimpleStrategy和ConstraintStrategy来提供通用而方便的回测功能
SimpleStrategy¶
SimpleStrategy(predicted, name=None, buy_count=50, mods=None)
通过传入一个`DataFrame`对象,`SimpleStrategy`每期做多分数最高的`buy_count`只股票
ConstraintStrategy¶
`ConstraintStrategy`根据传入的DataFrame的值、及一系列约束条件,来优化出在给定风险暴露的前提下 期望收益率最大的组合,并买入该组合。
import numpy as np
import pandas as pd
from quant.backtest.strategy import ConstraintStrategy
from quant.backtest.common.mods import AbstractMod
from quant.common.settings import CONFIG
CONFIG.BENCHMARK = "000905.SH"
config = {
"factors": {
"Beta": 1.0,
"Size": 0.5,
"BookToPrice": 0.5,
"ResidualVolatility": 0.5,
"NonLinearSize": 0.5,
"Liquidity": 0.5,
"Leverage": 0.5,
"Momentum": 0.5
},
"industries": {
"Automobile": 0.05,
"LightIndustry": 0.05,
"Medical": 0.05,
"FundamentalChemistry": 0.05,
"Media": 0.05,
"BuildingMaterials": 0.05,
"ElectricDevice": 0.05,
"Construction": 0.05,
"ElectronicComponents": 0.05,
"RealEstate": 0.05,
"Food": 0.05,
"Retail": 0.05,
"Petroleum": 0.05,
"Composite": 0.05,
"Computer": 0.05,
"Communication": 0.05,
"Mechanism": 0.05,
"Iron": 0.05,
"NonbankFinance": 0.05,
"Transportation": 0.05,
"Public": 0.05,
"Agriculture": 0.05,
"Military": 0.05,
"ElectricalAppliance": 0.05,
"Clothing": 0.05,
"NonferrousMetal": 0.05,
"Bank": 0.05,
"Tourism": 0.05,
"Coal": 0.05
},
"stocks": 0.02
}
data = pd.DataFrame(...)
strategy = ConstraintStrategy(config, data, name="technical_ZZ500")
strategy.run()
以上代码在约束单只股票最大持仓2%、行业暴露5%、风格暴露0.5的前提下优化目标收益率最大的持仓比例并进行回测。
模块¶
本回测框架提供一些可选模块来支持扩展特性,同时也允许用户自定义模块。默认提供的模块有:
Mod Name | Purpose |
---|---|
NoSTUniverse* | Remove ST stocks from universe |
NoIPOUniverse* | Remove new stocks from universe |
NoUpLimitUniverse* | Remove stocks that reach up-limit from universe |
ActivelyTraded* | Remove inactive stocks (daily amount<10million) |
ShowBasicResults* | Show simple statistic infomation after backtest |
Abigale* | Generate analytical details for abigale2 |
Output | Save position information to ‘output.h5’ |
Visualizer | Show details of backtest in webpage (abigale is preferred) |
默认以上所有模块都会自动被加载,用户也可以在策略类的mods属性中定义自己要使用的模块,如:
class Strategy(AbstractStrategy):
mods = ["ShowBasicResults"]
则以上策略只会显示简单的回测信息,且不会对可选股票池作任何变化。
开发者¶
To be expected.
API¶
quant.barra¶
基类¶
Descriptor¶
Beta¶
-
class
quant.barra.factors.beta.
BetaDescriptor
¶ Beta
Computed as the slope coefficient in a time-series regression of excess stock return, \(r_t - r_{ft}\), against the cap-weighted excess return of the estimation universe \(R_t\),
\[r_t-r_{ft} = \alpha + \beta R_t + e_t\]The regression coefficients are estimated over the trailing 252 trading days of returns with a half-life of 63 trading days.
RSTR¶
-
class
quant.barra.factors.momentum.
RSTR
¶ Relative strength
Computed as the sum of excess log returns over the trailing T = 504 trading days with a lag of L=21 tradingdays,
\[RSTR = \Sigma_{t=L}^{T+L}w_t[ln(1+r_t)-ln(1+r_{ft})]\]where \(r_t\) is the stock return on day t, \(r_{ft}\) is the risk-free return, and \(w_t\) is an exponential weight with a half-life of 126 trading days.
LnCap¶
-
class
quant.barra.factors.size.
LnCap
¶ Natural log of market cap
Given by the logarithm of the total market capitalization of the firm.
BToP¶
-
class
quant.barra.factors.book_to_price.
B2P
¶ Book-to-price ratio
Last reported book value of common equity divided by current market capitalization.
EPFWD¶
-
class
quant.barra.factors.earnings_yield.
EPFWD
¶ Predicted earnings-to-price ratio
Given by the 12-month forward-looking earnings divided by the current market capitalization. Forward-looking earnings are defined as a weighted average between the average analyst-predicted earnings for the current and next fiscal years.
CEToP¶
-
class
quant.barra.factors.earnings_yield.
CEToP
¶ Cash earnings-to-price ratio
Given by the trailing 12-month cash earnings divided by current price.
EToP¶
-
class
quant.barra.factors.earnings_yield.
EToP
¶ Trailing earnings-to-price ratio
Given by the trailing 12-month earnings divided by the current market capitalization. Trailing earnings are defined as the last reported fiscal-year earnings plus the difference between current interim figure and the comparative interim figure from the previous year.
EGRLF¶
-
class
quant.barra.factors.growth.
EGRLF
¶ Long-term predicted earnings growth
Long-term (3-5 years) earnings growth forecasted by analysts.
EGRSF¶
-
class
quant.barra.factors.growth.
EGSRLF
¶ Short-term predicted earnings growth
Short-term (1 year) earnings growth forecasted by analysts.
EGRO¶
-
class
quant.barra.factors.growth.
EGSRO
¶ Earnings growth (trailing five years)
Annual reported earnings per share are regressed against time over the past five fiscal years. The slope coefficient is then divided by the average annual earnings per share to obtain the earnings growth.
MLEV¶
-
class
quant.barra.factors.leverage.
MLEV
¶ Market leverage
Computed as MLEV = (ME + PE + LD) / ME where ME is the market value of common equity on the last trading day, PE is the most recent book value of preferred equity, and LD is the most recent book value of long-term debt.
BLEV¶
-
class
quant.barra.factors.leverage.
BLEV
¶ Book leverage
Computed as BLEV = (BE + PE + LD) / ME where BE is the book value of common equity on the last trading day, PE is the most recent book value of preferred equity, and LD is the most recent book value of long-term debt.
DToA¶
-
class
quant.barra.factors.leverage.
DToA
¶ Debt-to-assets
Computed as
\[DTOA = TD / TA\]where TD is the book value of total debt (long-term debt and current liabilities), and TA is most recent book value of total assets.
STOM¶
-
class
quant.barra.factors.liquidity.
STOM
¶ Share turnover, one month
Computed as the log of the sum of daily turnover during the previous 21 trading days,
\[STOM = ln[\Sigma_{t=1}^{21}\frac{V_t}{S_t}]\]where Vt is the trading volume on day t , and St is the number of shares outstanding.
STOQ¶
-
class
quant.barra.factors.liquidity.
STOQ
¶ Share turnover, trailing 3 months
Let STOM_t be the share turnover for month t , with each month consisting of 21 trading days. The quarterly share turnover is defined by
\[STOQ = ln[\frac{1}{T}\Sigma_{t=1}{T}exp\{STOM_t\}]\]where T = 3 months.
STOA¶
-
class
quant.barra.factors.liquidity.
STOA
¶ Share turnover, trailing 12 months
Let STOM_t be the share turnover for month t , with each month consisting of 21 trading days. The quarterly share turnover is defined by
\[STOQ = ln[\frac{1}{T}\Sigma_{t=1}{T}exp\{STOM_t\}]\]where T = 12 months.