Backtrader中文笔记之Analyzers Reference
AnnualReturn
年利润
class backtrader.analyzers.AnnualReturn()
This analyzer calculates the AnnualReturns by looking at the beginning and end of the year
这个分析器通过观察一年的开始和结束来计算年收益
Params:
- (None)
Member Attributes:
有两个属性
源码:
if cur_year not in self.ret: # finish calculating pending data annualret = (value_end / value_start) - 1.0 self.rets.append(annualret) self.ret[cur_year] = annualret
-
rets
: list of calculated annual returns - rets: 用列表的形式返回年度收益清单
-
ret
: dictionary (key: year) of annual returns - ret:用字典(key: year)的形式返回年度收益清单
get_analysis:
- Returns a dictionary of annual returns (key: year)
- 用字典(key: year)的形式返回年度收益清单
Calmar
class backtrader.analyzers.Calmar()
This analyzer calculates the CalmarRatio timeframe which can be different from the one used in the underlying data Params:
-
timeframe
(default:None
) IfNone
thetimeframe
of the 1st data in the system will be usedPass
TimeFrame.NoTimeFrame
to consider the entire dataset with no time constraints -
compression
(default:None
)Only used for sub-day timeframes to for example work on an hourly timeframe by specifying “TimeFrame.Minutes” and 60 as compression
If
None
then the compression of the 1st data of the system will be used -
None
-
fund
(default:None
)If
None
the actual mode of the broker (fundmode - True/False) will be autodetected to decide if the returns are based on the total net asset value or on the fund value. Seeset_fundmode
in the broker documentationSet it to
True
orFalse
for a specific behavior
- ``get_analysis``()
Returns a OrderedDict with a key for the time period and the corresponding rolling Calmar ratio
- ``calmar`` the latest calculated calmar ratio()
Calmar比率(Calmar Ratio) 描述的是收益和最大回撤之间的关系。计算方式为年化收益率与历史最大回撤之间的比率。Calmar比率数值越大,基金的业绩表现越好。反之,基金的业绩表现越差。
DrawDown
class backtrader.analyzers.DrawDown()
This analyzer calculates trading system drawdowns stats such as drawdown values in %s and in dollars, max drawdown in %s and in dollars, drawdown length and drawdown max length
Params:
-
fund
(default:None
)If
None
the actual mode of the broker (fundmode - True/False) will be autodetected to decide if the returns are based on the total net asset value or on the fund value. Seeset_fundmode
in the broker documentationSet it to
True
orFalse
for a specific behavior
- ``get_analysis``()
Returns a dictionary (with . notation support and subdctionaries) with drawdown stats as values, the following keys/attributes are available:
-
drawdown
- drawdown value in 0.xx % -
moneydown
- drawdown value in monetary units -
len
- drawdown length -
max.drawdown
- max drawdown value in 0.xx % -
max.moneydown
- max drawdown value in monetary units -
max.len
- max drawdown length
TimeDrawDown
class backtrader.analyzers.TimeDrawDown()
This analyzer calculates trading system drawdowns on the chosen timeframe which can be different from the one used in the underlying data Params:
-
timeframe
(default:None
) IfNone
thetimeframe
of the 1st data in the system will be usedPass
TimeFrame.NoTimeFrame
to consider the entire dataset with no time constraints -
compression
(default:None
)Only used for sub-day timeframes to for example work on an hourly timeframe by specifying “TimeFrame.Minutes” and 60 as compression
If
None
then the compression of the 1st data of the system will be used -
None
-
fund
(default:None
)If
None
the actual mode of the broker (fundmode - True/False) will be autodetected to decide if the returns are based on the total net asset value or on the fund value. Seeset_fundmode
in the broker documentationSet it to
True
orFalse
for a specific behavior
- ``get_analysis``()
Returns a dictionary (with . notation support and subdctionaries) with drawdown stats as values, the following keys/attributes are available:
-
drawdown
- drawdown value in 0.xx % -
maxdrawdown
- drawdown value in monetary units -
maxdrawdownperiod
- drawdown length
- Those are available during runs as attributes()
-
dd
-
maxdd
-
maxddlen
GrossLeverage
总杠杆
class backtrader.analyzers.GrossLeverage()
This analyzer calculates the Gross Leverage of the current strategy on a timeframe basis
Params:
-
fund
(default:None
)If
None
the actual mode of the broker (fundmode - True/False) will be autodetected to decide if the returns are based on the total net asset value or on the fund value. Seeset_fundmode
in the broker documentationSet it to
True
orFalse
for a specific behavior
- get_analysis()
Returns a dictionary with returns as values and the datetime points for each return as keys
每个bar都有数据
PositionsValue
持仓的价值
class backtrader.analyzers.PositionsValue()
This analyzer reports the value of the positions of the current set of datas
Params:
-
timeframe (default:
None
) IfNone
then the timeframe of the 1st data of the system will be used -
compression (default:
None
)Only used for sub-day timeframes to for example work on an hourly timeframe by specifying “TimeFrame.Minutes” and 60 as compression
If
None
then the compression of the 1st data of the system will be used -
headers (default:
False
)Add an initial key to the dictionary holding the results with the names of the datas (‘Datetime’ as key
-
cash (default:
False
)Include the actual cash as an extra position (for the header ‘cash’ will be used as name)
- get_analysis()
Returns a dictionary with returns as values and the datetime points for each return as keys
逐条写入,每个bar的数据都有输出
PyFolio
class backtrader.analyzers.PyFolio()
This analyzer uses 4 children analyzers to collect data and transforms it in to a data set compatible with pyfolio
Children Analyzer
-
TimeReturn
Used to calculate the returns of the global portfolio value
-
PositionsValue
Used to calculate the value of the positions per data. It sets the
headers
andcash
parameters toTrue
-
Transactions
Used to record each transaction on a data (size, price, value). Sets the
headers
parameter toTrue
-
GrossLeverage
Keeps track of the gross leverage (how much the strategy is invested)
Params:
These are passed transparently to the children * timeframe (default: `bt.TimeFrame.Days`) If `None` then the timeframe of the 1st data of the system will be used * compression (default: 1\`) If `None` then the compression of the 1st data of the system will be used
Both timeframe
and compression
are set following the default behavior of pyfolio
which is working with daily data and upsample it to obtaine values like yearly returns.
- get_analysis()
Returns a dictionary with returns as values and the datetime points for each return as keys
get_pf_items()
Returns a tuple of 4 elements which can be used for further processing with
`pyfolio` returns, positions, transactions, gross_leverage
Because the objects are meant to be used as direct input to pyfolio
this method makes a local import of pandas
to convert the internal backtrader results to pandas DataFrames which is the expected input by, for example, pyfolio.create_full_tear_sheet
The method will break if pandas
is not installed
输出数据给专业的第三方金融模块用
模块:pyfolio
LogReturnsRolling
class backtrader.analyzers.LogReturnsRolling()
This analyzer calculates rolling returns for a given timeframe and compression
Params:
-
timeframe
(default:None
) IfNone
thetimeframe
of the 1st data in the system will be usedPass
TimeFrame.NoTimeFrame
to consider the entire dataset with no time constraints -
compression
(default:None
)Only used for sub-day timeframes to for example work on an hourly timeframe by specifying “TimeFrame.Minutes” and 60 as compression
If
None
then the compression of the 1st data of the system will be used -
data
(default:None
)Reference asset to track instead of the portfolio value.
NOTE: this data must have been added to a
cerebro
instance withaddata
,resampledata
orreplaydata
-
firstopen
(default:True
)When tracking the returns of a
data
the following is done when crossing a timeframe boundary, for exampleYears
:- Last
close
of previous year is used as the reference price to see the return in the current year
The problem is the 1st calculation, because the data has** no previous** closing price. As such and when this parameter is
True
the opening price will be used for the 1st calculation.This requires the data feed to have an
open
price (forclose
the standard [0] notation will be used without reference to a field price)Else the initial close will be used.
- Last
-
fund
(default:None
)If
None
the actual mode of the broker (fundmode - True/False) will be autodetected to decide if the returns are based on the total net asset value or on the fund value. Seeset_fundmode
in the broker documentationSet it to
True
orFalse
for a specific behavior
- get_analysis()
Returns a dictionary with returns as values and the datetime points for each return as keys
PeriodStats
周期统计
class backtrader.analyzers.PeriodStats()
Calculates basic statistics for given timeframe
Params:
-
timeframe
(default:Years
) IfNone
thetimeframe
of the 1st data in the system will be usedPass
TimeFrame.NoTimeFrame
to consider the entire dataset with no time constraints -
compression
(default:1
)Only used for sub-day timeframes to for example work on an hourly timeframe by specifying “TimeFrame.Minutes” and 60 as compression
If
None
then the compression of the 1st data of the system will be used -
fund
(default:None
)If
None
the actual mode of the broker (fundmode - True/False) will be autodetected to decide if the returns are based on the total net asset value or on the fund value. Seeset_fundmode
in the broker documentationSet it to
True
orFalse
for a specific behavior
get_analysis
returns a dictionary containing the keys:
-
average
-
stddev
-
positive
-
negative
-
nochange
-
best
-
worst
If the parameter zeroispos
is set to True
, periods with no change will be counted as positive
Returns
class backtrader.analyzers.Returns()
Total, Average, Compound and Annualized Returns calculated using a logarithmic approach
See:
Params:
-
timeframe
(default:None
)If
None
thetimeframe
of the 1st data in the system will be usedPass
TimeFrame.NoTimeFrame
to consider the entire dataset with no time constraints -
compression
(default:None
)Only used for sub-day timeframes to for example work on an hourly timeframe by specifying “TimeFrame.Minutes” and 60 as compression
If
None
then the compression of the 1st data of the system will be used -
tann
(default:None
)Number of periods to use for the annualization (normalization) of the
namely:
-
days: 252
-
weeks: 52
-
months: 12
-
years: 1
-
-
fund
(default:None
)If
None
the actual mode of the broker (fundmode - True/False) will be autodetected to decide if the returns are based on the total net asset value or on the fund value. Seeset_fundmode
in the broker documentationSet it to
True
orFalse
for a specific behavior
- get_analysis()
Returns a dictionary with returns as values and the datetime points for each return as keys
The returned dict the following keys:
-
rtot
: Total compound return -
ravg
: Average return for the entire period (timeframe specific) -
rnorm
: Annualized/Normalized return -
rnorm100
: Annualized/Normalized return expressed in 100%
SharpeRatio
class backtrader.analyzers.SharpeRatio()
This analyzer calculates the SharpeRatio of a strategy using a risk free asset which is simply an interest rate
Params:
-
timeframe
: (default:TimeFrame.Years
) -
compression
(default:1
)Only used for sub-day timeframes to for example work on an hourly timeframe by specifying “TimeFrame.Minutes” and 60 as compression
-
riskfreerate
(default: 0.01 -> 1%)Expressed in annual terms (see
convertrate
below) -
convertrate
(default:True
)Convert the
riskfreerate
from annual to monthly, weekly or daily rate. Sub-day conversions are not supported -
factor
(default:None
)If
None
, the conversion factor for the riskfree rate from annual to the chosen timeframe will be chosen from a predefined tableDays: 252, Weeks: 52, Months: 12, Years: 1
Else the specified value will be used
-
annualize
(default:False
)If
convertrate
isTrue
, the SharpeRatio will be delivered in thetimeframe
of choice.In most occasions the SharpeRatio is delivered in annualized form. Convert the
riskfreerate
from annual to monthly, weekly or daily rate. Sub-day conversions are not supported -
stddev_sample
(default:False
)If this is set to
True
the standard deviation will be calculated decreasing the denominator in the mean by1
. This is used when calculating the standard deviation if it’s considered that not all samples are used for the calculation. This is known as the Bessels’ correction -
daysfactor
(default:None
)Old naming for
factor
. If set to anything else thanNone
and thetimeframe
isTimeFrame.Days
it will be assumed this is old code and the value will be used -
legacyannual
(default:False
)Use the
AnnualReturn
return analyzer, which as the name implies only works on years -
fund
(default:None
)If
None
the actual mode of the broker (fundmode - True/False) will be autodetected to decide if the returns are based on the total net asset value or on the fund value. Seeset_fundmode
in the broker documentationSet it to
True
orFalse
for a specific behavior
- get_analysis()
Returns a dictionary with key “sharperatio” holding the ratio
SharpeRatio_A
class backtrader.analyzers.SharpeRatio_A()
Extension of the SharpeRatio which returns the Sharpe Ratio directly in annualized form
The following param has been changed from SharpeRatio
annualize
(default:True
)
SQN
class backtrader.analyzers.SQN()
SQN or SystemQualityNumber. Defined by Van K. Tharp to categorize trading systems.
-
1.6 - 1.9 Below average
-
2.0 - 2.4 Average
-
2.5 - 2.9 Good
-
3.0 - 5.0 Excellent
-
5.1 - 6.9 Superb
-
7.0 - Holy Grail?
The formula:
- SquareRoot(NumberTrades) * Average(TradesProfit) / StdDev(TradesProfit)
The sqn value should be deemed reliable when the number of trades >= 30
- get_analysis()
Returns a dictionary with keys “sqn” and “trades” (number of considered trades)
TimeReturn
class backtrader.analyzers.TimeReturn()
This analyzer calculates the Returns by looking at the beginning and end of the timeframe
这个分析器通过查看时间框架的开始和结束来计算回报
Params:
-
timeframe
(default:None
) IfNone
thetimeframe
of the 1st data in the system will be usedPass
TimeFrame.NoTimeFrame
to consider the entire dataset with no time constraints -
compression
(default:None
)Only used for sub-day timeframes to for example work on an hourly timeframe by specifying “TimeFrame.Minutes” and 60 as compression
If
None
then the compression of the 1st data of the system will be used -
data
(default:None
)Reference asset to track instead of the portfolio value.
NOTE: this data must have been added to a
cerebro
instance withaddata
,resampledata
orreplaydata
-
firstopen
(default:True
)When tracking the returns of a
data
the following is done when crossing a timeframe boundary, for exampleYears
:- Last
close
of previous year is used as the reference price to see the return in the current year
The problem is the 1st calculation, because the data has** no previous** closing price. As such and when this parameter is
True
the opening price will be used for the 1st calculation.This requires the data feed to have an
open
price (forclose
the standard [0] notation will be used without reference to a field price)Else the initial close will be used.
- Last
-
fund
(default:None
)If
None
the actual mode of the broker (fundmode - True/False) will be autodetected to decide if the returns are based on the total net asset value or on the fund value. Seeset_fundmode
in the broker documentationSet it to
True
orFalse
for a specific behavior
- get_analysis()
Returns a dictionary with returns as values and the datetime points for each return as keys
TradeAnalyzer
交易分析
class backtrader.analyzers.TradeAnalyzer()
Provides statistics on closed trades (keeps also the count of open ones)
-
Total Open/Closed Trades
-
Streak Won/Lost Current/Longest
-
ProfitAndLoss Total/Average
-
Won/Lost Count/ Total PNL/ Average PNL / Max PNL
-
Long/Short Count/ Total PNL / Average PNL / Max PNL
- Won/Lost Count/ Total PNL/ Average PNL / Max PNL
-
Length (bars in the market)
-
Total/Average/Max/Min
-
Won/Lost Total/Average/Max/Min
-
Long/Short Total/Average/Max/Min
-
Won/Lost Total/Average/Max/Min
-
NOTE: The analyzer uses an “auto”dict for the fields, which means that if no trades are executed, no statistics will be generated.
In that case there will be a single field/subfield in the dictionary returned by get_analysis
, namely:
- dictname[‘total’][‘total’] which will have a value of 0 (the field is also reachable with dot notation dictname.total.total
Transactions
交易
class backtrader.analyzers.Transactions()
This analyzer reports the transactions occurred with each an every data in the system
这个分析器报告系统中每个数据发生的事务
It looks at the order execution bits to create a Position
starting from 0 during each next
cycle.
The result is used during next to record the transactions
Params:
-
headers (default:
True
)Add an initial key to the dictionary holding the results with the names of the datas
This analyzer was modeled to facilitate the integration with
pyfolio
and the header names are taken from the samples used for it:
-
'date', 'amount', 'price', 'sid', 'symbol', 'value'
- get_analysis()
Returns a dictionary with returns as values and the datetime points for each return as keys
VWR
class backtrader.analyzers.VWR()
Variability-Weighted Return: Better SharpeRatio with Log Returns
Alias:
- VariabilityWeightedReturn
See:
Params:
-
timeframe
(default:None
) IfNone
then the complete return over the entire backtested period will be reportedPass
TimeFrame.NoTimeFrame
to consider the entire dataset with no time constraints -
compression
(default:None
)Only used for sub-day timeframes to for example work on an hourly timeframe by specifying “TimeFrame.Minutes” and 60 as compression
If
None
then the compression of the 1st data of the system will be used -
tann
(default:None
)Number of periods to use for the annualization (normalization) of the average returns. If
None
, then standardt
values will be used, namely:-
days: 252
-
weeks: 52
-
months: 12
-
years: 1
-
-
tau
(default:2.0
)factor for the calculation (see the literature)
-
sdev_max
(default:0.20
)max standard deviation (see the literature)
-
fund
(default:None
)If
None
the actual mode of the broker (fundmode - True/False) will be autodetected to decide if the returns are based on the total net asset value or on the fund value. Seeset_fundmode
in the broker documentationSet it to
True
orFalse
for a specific behavior
- get_analysis()
Returns a dictionary with returns as values and the datetime points for each return as keys
The returned dict contains the following keys:
vwr
: Variability-Weighted Return