Strategies¶
IndexTracking holds an index in full or through an optimised or sampled subset. See Strategies.
strategy ¶
Strategies: what a backtest holds, whatever the vehicle that holds it.
A bare index definition passed to Backtest.run is tracked in full.
IndexTracking holds an index another way: through an optimised subset or a
stratified sample (see beacon.strategy.tracking), synthetically, through a
substitute basket and a total return swap (see beacon.strategy.synthetic),
or through cash and rolled index futures (see beacon.strategy.futures).
ActiveStrategy builds its own portfolio from a signal, against a benchmark
(see beacon.strategy.active).
ActiveStep
dataclass
¶
ActiveStep(
date: Timestamp,
weights: dict[str, float],
benchmark: dict[str, float],
tracking_error: float,
active_share: float,
scores: dict[str, float] = dict(),
unmeasured: tuple[str, ...] = tuple(),
risk_contributions: dict[str, float] = dict(),
exposures: dict[str, float] = dict(),
)
What an active strategy did at one rebalance.
Attributes:
| Name | Type | Description |
|---|---|---|
date |
Timestamp
|
The rebalance date. |
weights |
dict[str, float]
|
The weights the portfolio traded to. |
benchmark |
dict[str, float]
|
The benchmark's weights that day. |
tracking_error |
float
|
The ex-ante annualised tracking error to the benchmark, from the day's covariance. |
active_share |
float
|
Half the summed absolute differences from the benchmark. |
scores |
dict[str, float]
|
Each candidate's signal score. |
unmeasured |
tuple[str, ...]
|
Candidates held at their benchmark weight because their history was too short to measure. |
risk_contributions |
dict[str, float]
|
Each holding's share of the portfolio's variance, adding up to one over the names the construction placed. |
exposures |
dict[str, float]
|
What the construction reports, such as a factor tilt's active exposure to each factor. |
ActiveStrategy ¶
ActiveStrategy(
benchmark: AnyIndexDefinition,
signal: Signal | None = None,
construction: Construction | None = None,
constraints: Sequence[ActiveConstraint] = (),
universe: Sequence[str] | None = None,
screen: Expression | None = None,
rebalancing: str = "MONTHLY",
lookback_days: int = DEFAULT_LOOKBACK_DAYS,
minimum_observations: int = MINIMUM_OBSERVATIONS,
name: str = "Active strategy",
)
A strategy that builds its own portfolio from a signal, against a benchmark.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
benchmark
|
AnyIndexDefinition
|
The index it is measured against. |
required |
signal
|
Signal | None
|
What it believes about each name. Not needed by a construction that does not use scores. |
None
|
construction
|
Construction | None
|
How it builds the portfolio; |
None
|
constraints
|
Sequence[ActiveConstraint]
|
What the portfolio must also satisfy. |
()
|
universe
|
Sequence[str] | None
|
The names it may hold; the benchmark's constituents when None. |
None
|
screen
|
Expression | None
|
A condition every holding must pass, such as
|
None
|
rebalancing
|
str
|
|
'MONTHLY'
|
lookback_days
|
int
|
Trading days of returns the covariance is estimated over. |
DEFAULT_LOOKBACK_DAYS
|
minimum_observations
|
int
|
The fewest returns a name needs to be measured. |
MINIMUM_OBSERVATIONS
|
name
|
str
|
What the strategy is called. |
'Active strategy'
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If rebalancing is not one of the four, or the construction needs a signal and none is given. |
rebalance_dates ¶
The first session of each period from start to end.
steps ¶
steps(
benchmark: IndexResult,
start: str,
end: str,
context: StrategyContext,
) -> list[ActiveStep]
The portfolio at each rebalance from start to end.
rebalanced ¶
rebalanced(
date: Timestamp,
benchmark: dict[str, float],
previous: dict[str, float],
context: StrategyContext,
) -> ActiveStep
One rebalance: the portfolio for benchmark on date.
BlackLitterman ¶
BlackLitterman(
risk_aversion: float = 2.5,
tau: float = 0.05,
alpha_per_score: float = 0.02,
confidence: float = 1.0,
)
Bases: Construction
The benchmark's implied returns, moved by the scores as views.
The prior is the return each name must be expected to earn for the
benchmark to be the best portfolio: risk_aversion x Σ x benchmark.
Each scored name is a view that it will earn its prior plus its score
times alpha_per_score, held with an uncertainty in proportion to the
prior's (tau x Σ) over confidence. The two are blended in the
usual way, and the portfolio is the best trade-off of the blended returns
against variance at the same risk aversion. With no scores it is the
benchmark.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
risk_aversion
|
float
|
The market's risk aversion, which sets the prior and the trade-off. |
2.5
|
tau
|
float
|
How uncertain the prior is, as a share of the covariance. |
0.05
|
alpha_per_score
|
float
|
How far one score moves a view, as a decimal a year. |
0.02
|
confidence
|
float
|
How much the views are believed against the prior: higher moves the blend further toward them. |
1.0
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If any setting is not positive. |
blended ¶
The blended expected returns, aligned to the problem's names.
MaximumDiversification ¶
Bases: Construction
The highest diversification ratio: the holdings' weighted average volatility over the portfolio's own. Benchmark-free, and needs no signal.
MaximumSharpe ¶
Bases: Construction
The highest expected excess return per unit of risk.
Each name's expected excess return is base_return plus its score times alpha_per_score: the signal says which names should earn more than the average, and the base return how much an average name earns over cash.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
base_return
|
float
|
The expected annual excess return of a name with an average score, as a decimal. |
0.05
|
alpha_per_score
|
float
|
The expected annual return of one score, as a decimal. |
0.02
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If base_return is not positive or alpha_per_score is negative. |
MinimumVariance ¶
Bases: Construction
The least risky portfolio: the lowest variance the constraints allow. Benchmark-free, and needs no signal.
RiskParity ¶
Bases: Construction
Each name contributing a set share of the portfolio's risk: equal shares by default (equal risk contribution), or budgets. A name's contribution is its weight times its covariance with the portfolio, over the portfolio's variance. Benchmark-free, and needs no signal.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
budgets
|
Mapping[str, float] | None
|
Each name's share of the risk, scaled to add up to one over the names that may be held; a name left out has none. None for equal shares. |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If a budget is negative or none is positive. |
StrategyContext
dataclass
¶
What a strategy may read at a rebalance.
Attributes:
| Name | Type | Description |
|---|---|---|
fetcher |
DataFetcher
|
The run's data. |
currency |
str
|
The book's currency, which returns and money fields are in. |
ActiveConstraint ¶
Bases: ABC
A constraint on an active portfolio.
build
abstractmethod
¶
The optimiser constraints this becomes for problem.
ActiveProblem
dataclass
¶
ActiveProblem(
assets: list[str],
benchmark: ndarray,
covariance: ndarray,
sectors: dict[str, str] = dict(),
previous: dict[str, float] = dict(),
holdable: tuple[str, ...] = (),
inputs: dict[str, dict[str, float]] = dict(),
)
One rebalance's problem, aligned to its names.
Attributes:
| Name | Type | Description |
|---|---|---|
assets |
list[str]
|
The names the solve allocates over, in order. |
benchmark |
ndarray
|
Their benchmark weights. |
covariance |
ndarray
|
Their annualised covariance. |
sectors |
dict[str, str]
|
Each name's sector, for sector bounds. |
previous |
dict[str, float]
|
The last rebalance's weights, for a turnover limit. |
holdable |
tuple[str, ...]
|
The names that may be held; every name when empty. |
inputs |
dict[str, dict[str, float]]
|
Anything else the construction asked to be read, by what it is and then by name, such as a factor's exposures. |
ActiveShare ¶
Bases: ActiveConstraint
An active share in a range.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
minimum
|
float | None
|
The least, as a decimal, or None. |
None
|
maximum
|
float | None
|
The most, as a decimal, or None. |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If neither is given, or they are outside 0 to 1 or cross. |
HoldingsLimit ¶
Bases: ActiveConstraint
No more than maximum names held.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
maximum
|
int
|
The most names. |
required |
RelativePositionBounds ¶
Bases: ActiveConstraint
Each name within within of its benchmark weight.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
within
|
float
|
The largest difference, as a decimal. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If within is negative. |
RelativeSectorBounds ¶
Bases: ActiveConstraint
Each sector's weight within within of the benchmark's.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
within
|
float
|
The largest difference, as a decimal: 0.05 for 5 points. |
required |
scheme
|
str
|
The classification sectors are read from. |
'SECTOR'
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If within is negative. |
TrackingErrorBudget ¶
Bases: ActiveConstraint
An ex-ante tracking error to the benchmark of at most maximum.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
maximum
|
float
|
The annualised limit, as a decimal: 0.03 for 3%. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If maximum is not positive. |
TurnoverLimit ¶
Bases: ActiveConstraint
At most maximum traded one way from the last rebalance's weights. The first rebalance, with nothing held, is not limited.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
maximum
|
float
|
The one-way limit, as a decimal. |
required |
Construction ¶
Bases: ABC
How an active portfolio is built from scores, a benchmark and a covariance.
inputs ¶
inputs(
names: list[str],
date: Timestamp,
context: StrategyContext,
) -> dict[str, dict[str, float]]
Anything else it needs read for the rebalance, by name, which
reaches it as problem.inputs. Nothing by default.
report ¶
What it reports about the portfolio it built, beyond the weights. Nothing by default.
build
abstractmethod
¶
build(
problem: ActiveProblem,
alpha: ndarray,
rules: list[Constraint],
hint: ndarray,
) -> np.ndarray
The weights, aligned to the problem's names.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
problem
|
ActiveProblem
|
The names, benchmark and covariance. |
required |
alpha
|
ndarray
|
Each name's score; 0 for a name that cannot be held. |
required |
rules
|
list[Constraint]
|
The constraints, including long-only bounds and full investment. |
required |
hint
|
ndarray
|
A feasible place to start, invested as much as the portfolio is to be. |
required |
FactorTilts ¶
Bases: Construction
Target active exposures to factors, as close to the benchmark as they allow.
Each factor is a signal: its standardised scores are the names' exposures to it, so a value factor is a value signal. The portfolio's active exposure to a factor is its active weights times the exposures. It minimises its active variance plus strength times the squared misses from the targets, so the targets are met as nearly as the constraints and the risk allow.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
factors
|
Mapping[str, Signal]
|
Each factor by name, as a |
required |
targets
|
Mapping[str, float]
|
Each factor's target active exposure, in scores; a factor with no target is aimed at zero. |
required |
strength
|
float
|
How hard the targets pull against the tracking error. |
1.0
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If there are no factors, a target names no factor, or strength is not positive. |
MaxAlpha ¶
Bases: Construction
The most exposure to the scores within a tracking-error budget.
Solved through its equivalent trade-off: maximising exposure within a budget has the same answer as maximising exposure less some risk aversion times the active variance. The risk aversion is found by bisection so the tracking error meets the budget, or falls short of it when the other constraints keep the portfolio closer to the benchmark anyway. Each step is a quadratic problem the optimiser solves reliably, where the linear objective against a quadratic limit did not.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tracking_error
|
float
|
The ex-ante annualised budget, as a decimal. |
0.03
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If tracking_error is not positive. |
MeanVariance ¶
Bases: Construction
The best trade-off of expected active return against active variance.
Expected active return is each name's score times alpha_per_score; the portfolio maximises it less risk_aversion times the active variance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
risk_aversion
|
float
|
How heavily active variance counts: higher holds closer to the benchmark. |
10.0
|
alpha_per_score
|
float
|
The expected annual return of one score, as a decimal. |
0.02
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If either is not positive. |
TopN ¶
Bases: Construction
The top n names by score, equal weighted or weighted by score: a simple rule the optimised constructions can be judged against.
Names with a score of zero or below are weighted equally among
themselves under "signal" when every chosen score is. The weights are
then moved as little as the strategy's constraints require.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n
|
int
|
How many names to hold. |
20
|
weighting
|
str
|
|
EQUAL
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If n is below 1 or the weighting is not one of the two. |
Factor ¶
Factor(
name: str,
signals: Signal | Sequence[Signal],
weights: Sequence[float] | None = None,
transform: str | None = None,
higher_is_better: bool = True,
standardise: bool = True,
centre: str = CAP_WEIGHTED,
centre_by: str | Sequence[str] | None = None,
scale_within_groups: bool = False,
returns: str | None = None,
)
Bases: Signal
A factor: a standardised score from one or more signals.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
What the factor is called, such as |
required |
signals
|
Signal | Sequence[Signal]
|
One signal, or several whose scores are averaged. |
required |
weights
|
Sequence[float] | None
|
Each signal's weight in the average; equal when None. |
None
|
transform
|
str | None
|
|
None
|
higher_is_better
|
bool
|
Whether a larger score is more exposed; False negates it. |
True
|
standardise
|
bool
|
Whether the values are centred and scaled; False takes them as they are. |
True
|
centre
|
str
|
|
CAP_WEIGHTED
|
centre_by
|
str | Sequence[str] | None
|
Grouping fields to centre within, such as |
None
|
scale_within_groups
|
bool
|
Scale by each group's spread rather than the universe's. |
False
|
returns
|
str | None
|
A series in the data whose closes are the factor's level. |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the name is empty, there are no signals, the weights do not match them or are negative or all 0, or a choice is unknown. |
values ¶
Each name's score, None where it has none.
scores ¶
Each name's score, standardised across names; 0 where it has none.
exposures ¶
exposures(
names: list[str],
date: Timestamp,
context: StrategyContext,
universe: list[str] | None = None,
inputs: FactorInputs | None = None,
) -> dict[str, float]
Each of names' score, standardised across universe (names when None); 0 where it has none.
scored ¶
Each name's score before missing values become 0.
FuturesReplication ¶
FuturesReplication(
roll_days: int = DEFAULT_ROLL_DAYS,
roll_cost_bps: float = 0.0,
dividend_yield: float | None = None,
multiplier: float = DEFAULT_MULTIPLIER,
whole_contracts: bool = True,
band: float = DEFAULT_BAND,
cost_per_contract: float = 0.0,
trading_cost_bps: float = 0.0,
underlying: str | None = None,
prices: str | None = None,
mispricing_bps: float = 0.0,
mispricing_half_life: float = 10.0,
mispricing_seed: int = 0,
)
Bases: Replication
Cash, with the index held through rolled futures.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
roll_days
|
int
|
Sessions before expiry the position rolls. |
DEFAULT_ROLL_DAYS
|
roll_cost_bps
|
float
|
What each roll costs, in basis points of the notional. |
0.0
|
dividend_yield
|
float | None
|
The index's annual dividend yield the futures are priced with. None estimates it. |
None
|
multiplier
|
float
|
The value of one index point per contract. |
DEFAULT_MULTIPLIER
|
whole_contracts
|
bool
|
Hold a whole number of contracts, or fractional ones. |
True
|
band
|
float
|
How far the exposure may drift before it is resized between rebalances, as a share of the net assets. |
DEFAULT_BAND
|
cost_per_contract
|
float
|
What each contract traded costs. |
0.0
|
trading_cost_bps
|
float
|
What a trade between rolls costs, in basis points of the notional it trades. |
0.0
|
underlying
|
str | None
|
The index the futures are on, when not the fund's: a
market series' identifier, or in Python an |
None
|
prices
|
str | None
|
A series in the data with the held contract's price. |
None
|
mispricing_bps
|
float
|
The typical size of the assumed mispricing. |
0.0
|
mispricing_half_life
|
float
|
The sessions it takes on average to halve. |
10.0
|
mispricing_seed
|
int
|
The seed its draws are made from. |
0
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If a setting is out of range. |
roll_cost_bps
property
¶
What each roll costs, in basis points of the notional.
dividend_yield
property
¶
The dividend yield given, or None to estimate it.
trading_cost_bps
property
¶
What a trade between rolls costs, in basis points of its notional.
mispricing_half_life
property
¶
The sessions the mispricing takes on average to halve.
IndexFutures
dataclass
¶
IndexFutures(
roll_days: int = DEFAULT_ROLL_DAYS,
roll_cost_bps: float = 0.0,
dividend_yield: float | None = None,
multiplier: float = DEFAULT_MULTIPLIER,
whole_contracts: bool = True,
band: float = DEFAULT_BAND,
cost_per_contract: float = 0.0,
trading_cost_bps: float = 0.0,
underlying: Any = None,
prices: str | None = None,
mispricing_bps: float = 0.0,
mispricing_half_life: float = 10.0,
mispricing_seed: int = 0,
)
The index futures a fund holds.
Attributes:
| Name | Type | Description |
|---|---|---|
roll_days |
int
|
Sessions before expiry the position rolls to the next contract. |
roll_cost_bps |
float
|
What each roll costs, in basis points of the notional. |
dividend_yield |
float | None
|
The index's annual dividend yield the futures are priced with. None estimates it (zero for an index that reinvests its dividends). |
multiplier |
float
|
The value of one index point per contract, in the book's currency. |
whole_contracts |
bool
|
Hold a whole number of contracts (the default), or fractional ones that carry exactly the target. |
band |
float
|
How far the exposure may drift from its target, as a share of the net assets, before the position is resized between rebalances. |
cost_per_contract |
float
|
What each contract traded costs, in the book's currency: commission and fees. |
trading_cost_bps |
float
|
What a trade between rolls costs, in basis points of the notional it trades: the spread paid. |
underlying |
Any
|
The index the futures are on, when not the fund's: a
market series' identifier, an |
prices |
str | None
|
A series in the data whose close is the price of the contract held each day. |
mispricing_bps |
float
|
The typical size of the assumed mispricing when the data has no price: its standard deviation, in basis points of fair value. |
mispricing_half_life |
float
|
The sessions the mispricing takes on average to halve. |
mispricing_seed |
int
|
The seed its draws are made from. |
underlying_levels ¶
The underlying's levels when given as an index or a series; None for an identifier, which the data is asked for, or for none.
trade_cost ¶
What trading contracts at price costs: per contract, and in basis points of the notional for a trade between rolls.
contracts ¶
How many contracts carry target at price: whole, the nearest number, or fractional, exactly.
FieldSignal ¶
FunctionSignal ¶
FunctionSignal(
function: Callable[
[str, Timestamp, DataFetcher], float | None
],
higher_is_better: bool = True,
)
Bases: Signal
A value from a function of the name, the date and the data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
function
|
Callable[[str, Timestamp, DataFetcher], float | None]
|
Called as |
required |
higher_is_better
|
bool
|
Whether a larger value is better. |
True
|
Momentum ¶
Bases: Signal
Price momentum: the return over a lookback, leaving out the most recent days, where short-term reversal works against it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lookback_days
|
int
|
Trading days the return is measured over. |
252
|
skip_days
|
int
|
The most recent trading days left out. |
21
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If skip_days is not below lookback_days. |
Signal ¶
Bases: ABC
A value for each name at a rebalance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
higher_is_better
|
bool
|
Whether a larger value is a stronger case to hold the name. |
True
|
SwapTerms
dataclass
¶
The total return swap a synthetic fund holds.
Attributes:
| Name | Type | Description |
|---|---|---|
spread_bps |
float
|
The spread the fund pays on the notional, in basis points a year, accrued over calendar days (ACT/360). |
exposure_limit |
float
|
The swap's value owed to the fund, as a share of its net assets, at which the swap is reset. |
SyntheticReplication ¶
SyntheticReplication(
basket: AnyIndexDefinition | Mapping[str, float],
spread_bps: float = 0.0,
exposure_limit: float = UCITS_EXPOSURE_LIMIT,
)
Bases: Replication
A substitute basket held, its return swapped for the index's.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
basket
|
AnyIndexDefinition | Mapping[str, float]
|
What the fund holds: an index definition, calculated over the run and held at its weights, or fixed weights by identifier, which are scaled to add up to one. |
required |
spread_bps
|
float
|
The spread the fund pays on the swap, in basis points a year. |
0.0
|
exposure_limit
|
float
|
The swap's value owed to the fund, as a share of its net assets, at which the swap is reset. 0.10 (UCITS) by default. |
UCITS_EXPOSURE_LIMIT
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the basket is empty or has a weight that is not positive, the spread is not a finite number, or the limit is not above 0 and at most 1. |
spread_bps
property
¶
The spread the fund pays on the swap, in basis points a year.
exposure_limit
property
¶
The share of net assets owed to the fund at which the swap resets.
basket_index
property
¶
The basket's index definition, or None for fixed weights.
with_basket ¶
This replication with its basket index's calculation, whose weights it holds at each rebalance.
FullReplication ¶
IndexTracking ¶
A strategy that holds an index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index
|
AnyIndexDefinition
|
The index to track. |
required |
replication
|
Replication | None
|
How it is held; in full by default. |
None
|
replicated ¶
replicated(
snapshots: dict[Timestamp, dict[str, float]],
context: StrategyContext,
) -> list[ReplicationStep]
The replication at each of the index's rebalances, in date order.
OptimisedReplication ¶
OptimisedReplication(
holdings: int | None = None,
constraints: Sequence[Constraint] = (),
lookback_days: int = DEFAULT_LOOKBACK_DAYS,
minimum_observations: int = MINIMUM_OBSERVATIONS,
)
Bases: Replication
A subset weighted to minimise tracking error to the index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
holdings
|
int | None
|
The most names to hold, or None for no limit. |
None
|
constraints
|
Sequence[Constraint]
|
Further optimiser constraints, such as |
()
|
lookback_days
|
int
|
Trading days of returns the covariance is estimated over. |
DEFAULT_LOOKBACK_DAYS
|
minimum_observations
|
int
|
The fewest returns a name needs to be measured; a name with fewer is held at its index weight. |
MINIMUM_OBSERVATIONS
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If holdings is below 1 or the windows are too short. |
Replication ¶
Bases: ABC
How an index is held: from its weights at a rebalance to the portfolio's.
ReplicationStep
dataclass
¶
ReplicationStep(
date: Timestamp,
weights: dict[str, float],
holdings: int,
tracking_error: float | None = None,
unmeasured: tuple[str, ...] = tuple(),
)
What a replication did at one rebalance.
Attributes:
| Name | Type | Description |
|---|---|---|
date |
Timestamp
|
The rebalance date. |
weights |
dict[str, float]
|
The weights the portfolio traded to. |
holdings |
int
|
How many names they hold. |
tracking_error |
float | None
|
The ex-ante annualised tracking error to the index, for an optimised replication; None when it was not estimated. |
unmeasured |
tuple[str, ...]
|
Names held at their index weight because their history was too short to measure. |
SampledReplication ¶
Bases: Replication
The largest names in each sector and size cell, each cell at its index weight.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
holdings
|
int
|
How many names to hold. |
required |
size_buckets
|
int
|
How many size groups (by market cap) each sector is split into: 3 for terciles. |
3
|
scheme
|
str
|
The classification the sectors are read from. |
'SECTOR'
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If holdings or size_buckets is below 1. |
default_factors ¶
Size (minus log market cap), value (book to price, one over P/B) and momentum (the twelve-month return leaving out the last month).
active ¶
Active strategies: a universe, a signal and a way of building a portfolio from it, measured against a benchmark.
strategy = ActiveStrategy(
benchmark=my_index,
signal=FieldSignal(data.features.fundamentals.earnings_yield),
construction=MaxAlpha(tracking_error=0.03),
constraints=[RelativeSectorBounds(within=0.05), HoldingsLimit(60)])
Backtest(initial_capital=1e8).run(strategy, start="2023-01-03", end="2024-12-31")
At each rebalance the strategy:
- Takes the benchmark's weights in force that day. The benchmark is an index, calculated as any index is, and the run is measured against it.
- Picks its candidates: the
universe(the benchmark's constituents by default), less any failing thescreen, a condition such asdata.market.market_cap > 1e9. A benchmark name that is not a candidate cannot be held. - Scores the candidates with its signal (see
beacon.strategy.signals). - Estimates the covariance from a year of returns, shrunk toward constant correlation. A candidate with too little history is held at its benchmark weight, outside the solve.
- Constructs the long-only, fully invested portfolio, within its
constraints (see
beacon.strategy.constraints), by one of the constructions inbeacon.strategy.constructionsandbeacon.strategy.allocations:MaxAlpha(tracking_error)(the default),MeanVariance,MinimumVariance,MaximumDiversification,RiskParity,MaximumSharpe,BlackLitterman,FactorTiltsorTopN. The constructions share one interface,Construction, so others can be added.
A construction that does not use scores (minimum variance, maximum diversification, risk parity, factor tilts) needs no signal.
Rebalances fall on the first session of each period ("MONTHLY" by
default). Each records the weights, the benchmark's, the ex-ante tracking
error, the active share, each holding's share of the risk and anything the
construction reports in result.active.
Construction ¶
Bases: ABC
How an active portfolio is built from scores, a benchmark and a covariance.
inputs ¶
inputs(
names: list[str],
date: Timestamp,
context: StrategyContext,
) -> dict[str, dict[str, float]]
Anything else it needs read for the rebalance, by name, which
reaches it as problem.inputs. Nothing by default.
report ¶
What it reports about the portfolio it built, beyond the weights. Nothing by default.
build
abstractmethod
¶
build(
problem: ActiveProblem,
alpha: ndarray,
rules: list[Constraint],
hint: ndarray,
) -> np.ndarray
The weights, aligned to the problem's names.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
problem
|
ActiveProblem
|
The names, benchmark and covariance. |
required |
alpha
|
ndarray
|
Each name's score; 0 for a name that cannot be held. |
required |
rules
|
list[Constraint]
|
The constraints, including long-only bounds and full investment. |
required |
hint
|
ndarray
|
A feasible place to start, invested as much as the portfolio is to be. |
required |
MaxAlpha ¶
Bases: Construction
The most exposure to the scores within a tracking-error budget.
Solved through its equivalent trade-off: maximising exposure within a budget has the same answer as maximising exposure less some risk aversion times the active variance. The risk aversion is found by bisection so the tracking error meets the budget, or falls short of it when the other constraints keep the portfolio closer to the benchmark anyway. Each step is a quadratic problem the optimiser solves reliably, where the linear objective against a quadratic limit did not.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tracking_error
|
float
|
The ex-ante annualised budget, as a decimal. |
0.03
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If tracking_error is not positive. |
MeanVariance ¶
Bases: Construction
The best trade-off of expected active return against active variance.
Expected active return is each name's score times alpha_per_score; the portfolio maximises it less risk_aversion times the active variance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
risk_aversion
|
float
|
How heavily active variance counts: higher holds closer to the benchmark. |
10.0
|
alpha_per_score
|
float
|
The expected annual return of one score, as a decimal. |
0.02
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If either is not positive. |
ActiveStep
dataclass
¶
ActiveStep(
date: Timestamp,
weights: dict[str, float],
benchmark: dict[str, float],
tracking_error: float,
active_share: float,
scores: dict[str, float] = dict(),
unmeasured: tuple[str, ...] = tuple(),
risk_contributions: dict[str, float] = dict(),
exposures: dict[str, float] = dict(),
)
What an active strategy did at one rebalance.
Attributes:
| Name | Type | Description |
|---|---|---|
date |
Timestamp
|
The rebalance date. |
weights |
dict[str, float]
|
The weights the portfolio traded to. |
benchmark |
dict[str, float]
|
The benchmark's weights that day. |
tracking_error |
float
|
The ex-ante annualised tracking error to the benchmark, from the day's covariance. |
active_share |
float
|
Half the summed absolute differences from the benchmark. |
scores |
dict[str, float]
|
Each candidate's signal score. |
unmeasured |
tuple[str, ...]
|
Candidates held at their benchmark weight because their history was too short to measure. |
risk_contributions |
dict[str, float]
|
Each holding's share of the portfolio's variance, adding up to one over the names the construction placed. |
exposures |
dict[str, float]
|
What the construction reports, such as a factor tilt's active exposure to each factor. |
ActiveStrategy ¶
ActiveStrategy(
benchmark: AnyIndexDefinition,
signal: Signal | None = None,
construction: Construction | None = None,
constraints: Sequence[ActiveConstraint] = (),
universe: Sequence[str] | None = None,
screen: Expression | None = None,
rebalancing: str = "MONTHLY",
lookback_days: int = DEFAULT_LOOKBACK_DAYS,
minimum_observations: int = MINIMUM_OBSERVATIONS,
name: str = "Active strategy",
)
A strategy that builds its own portfolio from a signal, against a benchmark.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
benchmark
|
AnyIndexDefinition
|
The index it is measured against. |
required |
signal
|
Signal | None
|
What it believes about each name. Not needed by a construction that does not use scores. |
None
|
construction
|
Construction | None
|
How it builds the portfolio; |
None
|
constraints
|
Sequence[ActiveConstraint]
|
What the portfolio must also satisfy. |
()
|
universe
|
Sequence[str] | None
|
The names it may hold; the benchmark's constituents when None. |
None
|
screen
|
Expression | None
|
A condition every holding must pass, such as
|
None
|
rebalancing
|
str
|
|
'MONTHLY'
|
lookback_days
|
int
|
Trading days of returns the covariance is estimated over. |
DEFAULT_LOOKBACK_DAYS
|
minimum_observations
|
int
|
The fewest returns a name needs to be measured. |
MINIMUM_OBSERVATIONS
|
name
|
str
|
What the strategy is called. |
'Active strategy'
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If rebalancing is not one of the four, or the construction needs a signal and none is given. |
rebalance_dates ¶
The first session of each period from start to end.
steps ¶
steps(
benchmark: IndexResult,
start: str,
end: str,
context: StrategyContext,
) -> list[ActiveStep]
The portfolio at each rebalance from start to end.
rebalanced ¶
rebalanced(
date: Timestamp,
benchmark: dict[str, float],
previous: dict[str, float],
context: StrategyContext,
) -> ActiveStep
One rebalance: the portfolio for benchmark on date.
allocations ¶
Constructions that build a portfolio on its own terms rather than around the
benchmark: minimum variance, maximum diversification and risk parity, which
ignore it, and maximum Sharpe and Black-Litterman, which build from expected
returns. See beacon.strategy.constructions for the interface and the rest.
MinimumVariance ¶
Bases: Construction
The least risky portfolio: the lowest variance the constraints allow. Benchmark-free, and needs no signal.
MaximumDiversification ¶
Bases: Construction
The highest diversification ratio: the holdings' weighted average volatility over the portfolio's own. Benchmark-free, and needs no signal.
RiskParity ¶
Bases: Construction
Each name contributing a set share of the portfolio's risk: equal shares by default (equal risk contribution), or budgets. A name's contribution is its weight times its covariance with the portfolio, over the portfolio's variance. Benchmark-free, and needs no signal.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
budgets
|
Mapping[str, float] | None
|
Each name's share of the risk, scaled to add up to one over the names that may be held; a name left out has none. None for equal shares. |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If a budget is negative or none is positive. |
MaximumSharpe ¶
Bases: Construction
The highest expected excess return per unit of risk.
Each name's expected excess return is base_return plus its score times alpha_per_score: the signal says which names should earn more than the average, and the base return how much an average name earns over cash.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
base_return
|
float
|
The expected annual excess return of a name with an average score, as a decimal. |
0.05
|
alpha_per_score
|
float
|
The expected annual return of one score, as a decimal. |
0.02
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If base_return is not positive or alpha_per_score is negative. |
BlackLitterman ¶
BlackLitterman(
risk_aversion: float = 2.5,
tau: float = 0.05,
alpha_per_score: float = 0.02,
confidence: float = 1.0,
)
Bases: Construction
The benchmark's implied returns, moved by the scores as views.
The prior is the return each name must be expected to earn for the
benchmark to be the best portfolio: risk_aversion x Σ x benchmark.
Each scored name is a view that it will earn its prior plus its score
times alpha_per_score, held with an uncertainty in proportion to the
prior's (tau x Σ) over confidence. The two are blended in the
usual way, and the portfolio is the best trade-off of the blended returns
against variance at the same risk aversion. With no scores it is the
benchmark.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
risk_aversion
|
float
|
The market's risk aversion, which sets the prior and the trade-off. |
2.5
|
tau
|
float
|
How uncertain the prior is, as a share of the covariance. |
0.05
|
alpha_per_score
|
float
|
How far one score moves a view, as a decimal a year. |
0.02
|
confidence
|
float
|
How much the views are believed against the prior: higher moves the blend further toward them. |
1.0
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If any setting is not positive. |
blended ¶
The blended expected returns, aligned to the problem's names.
base ¶
What every strategy shares: what it may read at a rebalance, and the returns and covariance it measures risk with.
The covariance is re-estimated at each rebalance from the names' trailing daily returns in the book's currency (a year by default), shrunk toward constant correlation. A name with too few returns to measure is left out of it; each strategy says what it does with such a name.
StrategyContext
dataclass
¶
What a strategy may read at a rebalance.
Attributes:
| Name | Type | Description |
|---|---|---|
fetcher |
DataFetcher
|
The run's data. |
currency |
str
|
The book's currency, which returns and money fields are in. |
trailing_returns ¶
trailing_returns(
names: list[str],
date: Timestamp,
context: StrategyContext,
lookback_days: int = DEFAULT_LOOKBACK_DAYS,
) -> pd.DataFrame
Daily returns in the book's currency over the trading days before and including date, one column per name.
measured ¶
measured(
names: list[str],
returns: DataFrame,
minimum_observations: int = MINIMUM_OBSERVATIONS,
) -> list[str]
The names with enough returns to estimate their risk, in order.
estimated_risk ¶
The shrunk covariance of names, over the days all have returns.
covariance_of ¶
The annualised covariance matrix, aligned to names.
constraints ¶
What an active portfolio must satisfy, mostly measured against its benchmark.
ActiveStrategy(..., constraints=[ActiveShare(minimum=0.3),
RelativeSectorBounds(within=0.05),
HoldingsLimit(60)])
TrackingErrorBudget(maximum): an ex-ante tracking error to the benchmark of at most maximum a year.ActiveShare(minimum, maximum): an active share in the range.RelativeSectorBounds(within): each sector within within of the benchmark's weight in it.RelativePositionBounds(within): each name within within of its benchmark weight.HoldingsLimit(maximum): no more than maximum names.TurnoverLimit(maximum): at most maximum traded one way from the last rebalance's weights.
Active share is half the summed absolute differences from the benchmark's weights. Every portfolio is also long-only and fully invested.
ActiveProblem
dataclass
¶
ActiveProblem(
assets: list[str],
benchmark: ndarray,
covariance: ndarray,
sectors: dict[str, str] = dict(),
previous: dict[str, float] = dict(),
holdable: tuple[str, ...] = (),
inputs: dict[str, dict[str, float]] = dict(),
)
One rebalance's problem, aligned to its names.
Attributes:
| Name | Type | Description |
|---|---|---|
assets |
list[str]
|
The names the solve allocates over, in order. |
benchmark |
ndarray
|
Their benchmark weights. |
covariance |
ndarray
|
Their annualised covariance. |
sectors |
dict[str, str]
|
Each name's sector, for sector bounds. |
previous |
dict[str, float]
|
The last rebalance's weights, for a turnover limit. |
holdable |
tuple[str, ...]
|
The names that may be held; every name when empty. |
inputs |
dict[str, dict[str, float]]
|
Anything else the construction asked to be read, by what it is and then by name, such as a factor's exposures. |
ActiveConstraint ¶
Bases: ABC
A constraint on an active portfolio.
build
abstractmethod
¶
The optimiser constraints this becomes for problem.
TrackingErrorBudget ¶
Bases: ActiveConstraint
An ex-ante tracking error to the benchmark of at most maximum.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
maximum
|
float
|
The annualised limit, as a decimal: 0.03 for 3%. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If maximum is not positive. |
ActiveShare ¶
Bases: ActiveConstraint
An active share in a range.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
minimum
|
float | None
|
The least, as a decimal, or None. |
None
|
maximum
|
float | None
|
The most, as a decimal, or None. |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If neither is given, or they are outside 0 to 1 or cross. |
RelativeSectorBounds ¶
Bases: ActiveConstraint
Each sector's weight within within of the benchmark's.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
within
|
float
|
The largest difference, as a decimal: 0.05 for 5 points. |
required |
scheme
|
str
|
The classification sectors are read from. |
'SECTOR'
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If within is negative. |
RelativePositionBounds ¶
Bases: ActiveConstraint
Each name within within of its benchmark weight.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
within
|
float
|
The largest difference, as a decimal. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If within is negative. |
HoldingsLimit ¶
Bases: ActiveConstraint
No more than maximum names held.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
maximum
|
int
|
The most names. |
required |
TurnoverLimit ¶
Bases: ActiveConstraint
At most maximum traded one way from the last rebalance's weights. The first rebalance, with nothing held, is not limited.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
maximum
|
float
|
The one-way limit, as a decimal. |
required |
constructions ¶
How an active strategy builds its portfolio at each rebalance.
Every construction is long-only and fully invested, and meets the strategy's
constraints (see beacon.strategy.constraints). Each takes the rebalance's
problem (its names, the benchmark's weights and their covariance) and the
signal's scores, and returns the weights.
MaxAlpha(tracking_error): the most exposure to the scores within a tracking-error budget.MeanVariance(risk_aversion): the best trade-off of expected active return against active variance.MinimumVariance(): the least risky portfolio. No signal.MaximumDiversification(): the highest ratio of its holdings' average volatility to its own. No signal.RiskParity(budgets): each name contributing a set share of the risk, equal by default. No signal.MaximumSharpe(base_return, alpha_per_score): the highest expected excess return per unit of risk.BlackLitterman(...): the benchmark's implied returns, moved by the scores as views.FactorTilts(factors, targets): target active exposures to factors, as close to the benchmark as they allow. Its own factors, no signal.TopN(n, weighting): the top n names by score, equal or score weighted.
The benchmark-free and absolute-return constructions (minimum variance,
maximum diversification, risk parity, maximum Sharpe, Black-Litterman) are in
beacon.strategy.allocations. The benchmark-free ones ignore the benchmark's
weights, but the run is still measured against it.
Construction ¶
Bases: ABC
How an active portfolio is built from scores, a benchmark and a covariance.
inputs ¶
inputs(
names: list[str],
date: Timestamp,
context: StrategyContext,
) -> dict[str, dict[str, float]]
Anything else it needs read for the rebalance, by name, which
reaches it as problem.inputs. Nothing by default.
report ¶
What it reports about the portfolio it built, beyond the weights. Nothing by default.
build
abstractmethod
¶
build(
problem: ActiveProblem,
alpha: ndarray,
rules: list[Constraint],
hint: ndarray,
) -> np.ndarray
The weights, aligned to the problem's names.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
problem
|
ActiveProblem
|
The names, benchmark and covariance. |
required |
alpha
|
ndarray
|
Each name's score; 0 for a name that cannot be held. |
required |
rules
|
list[Constraint]
|
The constraints, including long-only bounds and full investment. |
required |
hint
|
ndarray
|
A feasible place to start, invested as much as the portfolio is to be. |
required |
MaxAlpha ¶
Bases: Construction
The most exposure to the scores within a tracking-error budget.
Solved through its equivalent trade-off: maximising exposure within a budget has the same answer as maximising exposure less some risk aversion times the active variance. The risk aversion is found by bisection so the tracking error meets the budget, or falls short of it when the other constraints keep the portfolio closer to the benchmark anyway. Each step is a quadratic problem the optimiser solves reliably, where the linear objective against a quadratic limit did not.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tracking_error
|
float
|
The ex-ante annualised budget, as a decimal. |
0.03
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If tracking_error is not positive. |
MeanVariance ¶
Bases: Construction
The best trade-off of expected active return against active variance.
Expected active return is each name's score times alpha_per_score; the portfolio maximises it less risk_aversion times the active variance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
risk_aversion
|
float
|
How heavily active variance counts: higher holds closer to the benchmark. |
10.0
|
alpha_per_score
|
float
|
The expected annual return of one score, as a decimal. |
0.02
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If either is not positive. |
FactorTilts ¶
Bases: Construction
Target active exposures to factors, as close to the benchmark as they allow.
Each factor is a signal: its standardised scores are the names' exposures to it, so a value factor is a value signal. The portfolio's active exposure to a factor is its active weights times the exposures. It minimises its active variance plus strength times the squared misses from the targets, so the targets are met as nearly as the constraints and the risk allow.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
factors
|
Mapping[str, Signal]
|
Each factor by name, as a |
required |
targets
|
Mapping[str, float]
|
Each factor's target active exposure, in scores; a factor with no target is aimed at zero. |
required |
strength
|
float
|
How hard the targets pull against the tracking error. |
1.0
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If there are no factors, a target names no factor, or strength is not positive. |
TopN ¶
Bases: Construction
The top n names by score, equal weighted or weighted by score: a simple rule the optimised constructions can be judged against.
Names with a score of zero or below are weighted equally among
themselves under "signal" when every chosen score is. The weights are
then moved as little as the strategy's constraints require.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n
|
int
|
How many names to hold. |
20
|
weighting
|
str
|
|
EQUAL
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If n is below 1 or the weighting is not one of the two. |
traded_off ¶
traded_off(
problem: ActiveProblem,
expected: ndarray,
aversion: float,
rules: list[Constraint],
hint: ndarray,
) -> np.ndarray
The weights maximising expected active return less aversion times the active variance.
risk_shares ¶
Each held name's share of the portfolio's variance: its weight times its covariance with the portfolio, over the variance.
solve ¶
solve(
objective: Any,
gradient: Any,
rules: list[Constraint],
problem: ActiveProblem,
hint: ndarray,
) -> np.ndarray
Minimise objective over the problem's names within rules.
average_variance ¶
The covariance's average variance: a constant to divide an objective by, so its size suits the solver whatever the returns' scale.
volatility ¶
The portfolio's volatility, kept above zero.
inverse_volatility ¶
A start in proportion to each holdable name's inverse volatility, invested as the hint is: closer to a risk-balanced answer than the benchmark is.
factors ¶
Factors: what a name is exposed to, such as size, value or momentum, as a standardised score built from one or more signals.
Factor("size", FieldSignal(data.market.market_cap), transform="log",
higher_is_better=False)
Factor("quality", [FieldSignal(data.features.fundamentals.roe),
FieldSignal(data.features.fundamentals.debt_to_equity,
higher_is_better=False)])
Factor("vendor_quality", FieldSignal(data.features.vendor.quality),
standardise=False)
A factor is a signal, so it serves wherever one does: as a factor tilt's factor, or as an active strategy's signal. It differs from a plain signal in how its scores are standardised.
Standardising. Each part's values (made larger-is-better, then
transformed) are centred and scaled across the universe: centred on its
cap-weighted mean by default (centre="cap_weighted"), so the market
portfolio has no exposure and a book's exposure reads as its tilt against the
market, or on its equally weighted mean ("equal"); and scaled by the
standard deviation of the centred values, then capped at 3 either side. With
centre_by naming grouping fields ("sector", or ["region", "sector"])
each name is centred on its own group's mean instead, so its score says how
it stands within its group; the scale stays universe-wide unless
scale_within_groups. A group of fewer than 5 names in the universe is
centred on the group one level up (the region alone, for a region and
sector), and so on to the whole universe. A name outside the universe is
scored on the universe's figures.
Composites. A factor of several parts averages the parts' scores, by weights (equal unless given), over the parts a name has a value for, so a name missing one part is scored on the rest rather than pulled toward 0; the average is then standardised again. A part may itself be a factor, with its own transform and centring.
Imported exposures. standardise=False takes the values as they are,
for exposures a vendor has already standardised and loaded as a feature.
A name with no value scores 0. returns names a series in the data whose closes are the factor's own returns, as a level (a vendor's factor index), for analyses to use in place of returns estimated from the exposures.
FactorInputs
dataclass
¶
FactorInputs(
context: StrategyContext,
date: Timestamp,
names: list[str],
fallbacks: dict[str, dict[Cell, Cell]] = dict(),
_caps: dict[str, float] | None = None,
_raw_caps: dict[str, float | None] | None = None,
_groups: dict[str, dict[str, str | None]] = dict(),
)
What scoring factors on one day reads once and shares: each name's market cap and groups, and the groups that fell back to a wider one.
Attributes:
| Name | Type | Description |
|---|---|---|
context |
StrategyContext
|
The run's data and book currency. |
date |
Timestamp
|
The day. |
names |
list[str]
|
Every name scored. |
fallbacks |
dict[str, dict[Cell, Cell]]
|
For each factor by name, the groups too small to centre on, and the wider group each was centred on instead. |
Factor ¶
Factor(
name: str,
signals: Signal | Sequence[Signal],
weights: Sequence[float] | None = None,
transform: str | None = None,
higher_is_better: bool = True,
standardise: bool = True,
centre: str = CAP_WEIGHTED,
centre_by: str | Sequence[str] | None = None,
scale_within_groups: bool = False,
returns: str | None = None,
)
Bases: Signal
A factor: a standardised score from one or more signals.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
What the factor is called, such as |
required |
signals
|
Signal | Sequence[Signal]
|
One signal, or several whose scores are averaged. |
required |
weights
|
Sequence[float] | None
|
Each signal's weight in the average; equal when None. |
None
|
transform
|
str | None
|
|
None
|
higher_is_better
|
bool
|
Whether a larger score is more exposed; False negates it. |
True
|
standardise
|
bool
|
Whether the values are centred and scaled; False takes them as they are. |
True
|
centre
|
str
|
|
CAP_WEIGHTED
|
centre_by
|
str | Sequence[str] | None
|
Grouping fields to centre within, such as |
None
|
scale_within_groups
|
bool
|
Scale by each group's spread rather than the universe's. |
False
|
returns
|
str | None
|
A series in the data whose closes are the factor's level. |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the name is empty, there are no signals, the weights do not match them or are negative or all 0, or a choice is unknown. |
values ¶
Each name's score, None where it has none.
scores ¶
Each name's score, standardised across names; 0 where it has none.
exposures ¶
exposures(
names: list[str],
date: Timestamp,
context: StrategyContext,
universe: list[str] | None = None,
inputs: FactorInputs | None = None,
) -> dict[str, float]
Each of names' score, standardised across universe (names when None); 0 where it has none.
scored ¶
Each name's score before missing values become 0.
default_factors ¶
Size (minus log market cap), value (book to price, one over P/B) and momentum (the twelve-month return leaving out the last month).
futures ¶
Futures-based replication: cash, with the index held through rolled futures.
IndexTracking(my_index, replication=FuturesReplication(roll_cost_bps=2.0))
The fund holds no securities. Its cash earns the run's cash rate, and a long position in the index's futures, sized to its net assets, carries the index's return. Each contract is priced at fair value from the index level, the cash rate and the index's dividend yield:
F = S x exp((r - q) x T)
with T the time to expiry over calendar days (ACT/365). Profit and loss is settled in cash every day, as variation margin is. Because the futures give up the cash rate and are paid the dividend yield, the fund earns roughly the index's price return plus its dividend yield: its total return, before the cost of rolling.
Contracts expire quarterly, on the third Friday of March, June, September and December, and the position rolls to the next one roll_days sessions before expiry, paying roll_cost_bps on its notional each time: the richness that real rolls pay over fair value.
Prices. Fair value is priced off the fund's own index unless
underlying names another for the futures: a market series by its
identifier, an index built in Beacon (its IndexResult), or a level series.
Futures on another index than the fund tracks carry the gap between the two
as well as their own. With prices naming a series in the data, each day's
close there is the price of the contract held (a front-month series rolled
on the same days); on a day it has none, and with no series, the price is
fair value moved by an assumed mispricing: mean-reverting around 0, its
typical size mispricing_bps (its standard deviation, in basis points of
fair value; 0 by default, so the price is fair value), halving its distance
from 0 in mispricing_half_life sessions on average, drawn from
mispricing_seed so a run repeats.
Trading costs. Every futures trade pays cost_per_contract on each contract it trades (a roll trades two: the old contract sold and the new one bought), and each trade between rolls (opening the position and each resize) pays trading_cost_bps on the notional it trades as well.
The dividend yield. A total return or net total return index already counts its dividends, so its futures carry none. A price index's are estimated at each roll from its constituents' dividends over the trailing twelve months, at their index weights, unless dividend_yield gives one.
Sizing. A contract is worth its price times its multiplier, the value of one index point (50 by default, as an S&P 500 e-mini's is in dollars). The position is sized to the fund's net assets when it opens, at each rebalance and roll, on any day money flows in or out, and on any other day its exposure is further from that than band of the net assets. Contracts are whole by default, so the exposure is the nearest a whole number of contracts comes; fractional contracts carry exactly what was asked for. Initial margin is not modelled, since it is the fund's own cash, held with a broker.
The same futures can equitise a physical fund's cash buffer instead:
Implementation(cash_buffer=0.03, equitise=IndexFutures()) holds futures on
the cash the fund keeps uninvested, so the buffer earns the index's return.
IndexFutures
dataclass
¶
IndexFutures(
roll_days: int = DEFAULT_ROLL_DAYS,
roll_cost_bps: float = 0.0,
dividend_yield: float | None = None,
multiplier: float = DEFAULT_MULTIPLIER,
whole_contracts: bool = True,
band: float = DEFAULT_BAND,
cost_per_contract: float = 0.0,
trading_cost_bps: float = 0.0,
underlying: Any = None,
prices: str | None = None,
mispricing_bps: float = 0.0,
mispricing_half_life: float = 10.0,
mispricing_seed: int = 0,
)
The index futures a fund holds.
Attributes:
| Name | Type | Description |
|---|---|---|
roll_days |
int
|
Sessions before expiry the position rolls to the next contract. |
roll_cost_bps |
float
|
What each roll costs, in basis points of the notional. |
dividend_yield |
float | None
|
The index's annual dividend yield the futures are priced with. None estimates it (zero for an index that reinvests its dividends). |
multiplier |
float
|
The value of one index point per contract, in the book's currency. |
whole_contracts |
bool
|
Hold a whole number of contracts (the default), or fractional ones that carry exactly the target. |
band |
float
|
How far the exposure may drift from its target, as a share of the net assets, before the position is resized between rebalances. |
cost_per_contract |
float
|
What each contract traded costs, in the book's currency: commission and fees. |
trading_cost_bps |
float
|
What a trade between rolls costs, in basis points of the notional it trades: the spread paid. |
underlying |
Any
|
The index the futures are on, when not the fund's: a
market series' identifier, an |
prices |
str | None
|
A series in the data whose close is the price of the contract held each day. |
mispricing_bps |
float
|
The typical size of the assumed mispricing when the data has no price: its standard deviation, in basis points of fair value. |
mispricing_half_life |
float
|
The sessions the mispricing takes on average to halve. |
mispricing_seed |
int
|
The seed its draws are made from. |
underlying_levels ¶
The underlying's levels when given as an index or a series; None for an identifier, which the data is asked for, or for none.
trade_cost ¶
What trading contracts at price costs: per contract, and in basis points of the notional for a trade between rolls.
contracts ¶
How many contracts carry target at price: whole, the nearest number, or fractional, exactly.
FuturesReplication ¶
FuturesReplication(
roll_days: int = DEFAULT_ROLL_DAYS,
roll_cost_bps: float = 0.0,
dividend_yield: float | None = None,
multiplier: float = DEFAULT_MULTIPLIER,
whole_contracts: bool = True,
band: float = DEFAULT_BAND,
cost_per_contract: float = 0.0,
trading_cost_bps: float = 0.0,
underlying: str | None = None,
prices: str | None = None,
mispricing_bps: float = 0.0,
mispricing_half_life: float = 10.0,
mispricing_seed: int = 0,
)
Bases: Replication
Cash, with the index held through rolled futures.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
roll_days
|
int
|
Sessions before expiry the position rolls. |
DEFAULT_ROLL_DAYS
|
roll_cost_bps
|
float
|
What each roll costs, in basis points of the notional. |
0.0
|
dividend_yield
|
float | None
|
The index's annual dividend yield the futures are priced with. None estimates it. |
None
|
multiplier
|
float
|
The value of one index point per contract. |
DEFAULT_MULTIPLIER
|
whole_contracts
|
bool
|
Hold a whole number of contracts, or fractional ones. |
True
|
band
|
float
|
How far the exposure may drift before it is resized between rebalances, as a share of the net assets. |
DEFAULT_BAND
|
cost_per_contract
|
float
|
What each contract traded costs. |
0.0
|
trading_cost_bps
|
float
|
What a trade between rolls costs, in basis points of the notional it trades. |
0.0
|
underlying
|
str | None
|
The index the futures are on, when not the fund's: a
market series' identifier, or in Python an |
None
|
prices
|
str | None
|
A series in the data with the held contract's price. |
None
|
mispricing_bps
|
float
|
The typical size of the assumed mispricing. |
0.0
|
mispricing_half_life
|
float
|
The sessions it takes on average to halve. |
10.0
|
mispricing_seed
|
int
|
The seed its draws are made from. |
0
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If a setting is out of range. |
roll_cost_bps
property
¶
What each roll costs, in basis points of the notional.
dividend_yield
property
¶
The dividend yield given, or None to estimate it.
trading_cost_bps
property
¶
What a trade between rolls costs, in basis points of its notional.
mispricing_half_life
property
¶
The sessions the mispricing takes on average to halve.
expiries ¶
The quarterly expiries from start to a year after end: the third Friday of March, June, September and December.
signals ¶
Signals: what an active strategy believes about each name, as a score.
FieldSignal(data.features.fundamentals.earnings_yield)
Momentum(lookback_days=252, skip_days=21)
FunctionSignal(my_function, higher_is_better=False)
A signal gives each candidate a value at a rebalance. The values are turned into scores: standardised across the candidates (mean 0, standard deviation 1), capped at 3 either side so one outlier cannot dominate, and negated when lower is better. A name with no value scores 0, so it is held neither over nor under on the signal's account.
Signal ¶
Bases: ABC
A value for each name at a rebalance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
higher_is_better
|
bool
|
Whether a larger value is a stronger case to hold the name. |
True
|
FieldSignal ¶
FunctionSignal ¶
FunctionSignal(
function: Callable[
[str, Timestamp, DataFetcher], float | None
],
higher_is_better: bool = True,
)
Bases: Signal
A value from a function of the name, the date and the data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
function
|
Callable[[str, Timestamp, DataFetcher], float | None]
|
Called as |
required |
higher_is_better
|
bool
|
Whether a larger value is better. |
True
|
Momentum ¶
Bases: Signal
Price momentum: the return over a lookback, leaving out the most recent days, where short-term reversal works against it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lookback_days
|
int
|
Trading days the return is measured over. |
252
|
skip_days
|
int
|
The most recent trading days left out. |
21
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If skip_days is not below lookback_days. |
standardised ¶
Values as scores: standardised across the names that have one, capped at three standard deviations, and 0 for a name with none.
synthetic ¶
Synthetic replication: a substitute basket held, its return swapped for the index's.
IndexTracking(my_index,
replication=SyntheticReplication(basket=other_index,
spread_bps=15.0))
The fund buys a basket of securities that need not be the index's, and holds a total return swap with a counterparty: on the swap's notional it pays the basket's return and the spread, and is paid the index's return. What the basket earns goes out as fast as it comes in, so the fund earns the index's return less the spread.
The basket still shapes the result:
- Resets. Between resets the swap is worth the index's performance less the basket's. A basket unlike the index moves that value further, so the swap reaches its exposure limit sooner and is reset more often, and each reset trades the basket.
- Counterparty exposure. The swap's value owed to the fund is what the fund would lose if the counterparty failed. It is capped: the swap is reset when it reaches exposure_limit of the fund's net assets (10% under UCITS).
- Dividend tax. The fund receives the basket's dividends net of its own withholding and passes on only what it received, while the swap pays the index's return as the index measures it (price, total or net total return).
- Costs. The basket is bought and sold with the run's costs, and the spread accrues on the notional every calendar day (ACT/360).
The basket is required. It is an index definition, calculated over the run and held at its own weights, or a fixed set of weights. Real swap-based funds hold whatever liquid basket the counterparty proposes within their collateral rules, rarely the index itself.
Resets. The swap is reset (its value paid in cash, and the notional set back to the fund's net assets) when the fund's exposure reaches the limit, at each of the index's rebalances, and on any day money flows in or out. A reset on a rebalance settles before the rebalance trades, so the basket is bought or sold once.
SwapTerms
dataclass
¶
The total return swap a synthetic fund holds.
Attributes:
| Name | Type | Description |
|---|---|---|
spread_bps |
float
|
The spread the fund pays on the notional, in basis points a year, accrued over calendar days (ACT/360). |
exposure_limit |
float
|
The swap's value owed to the fund, as a share of its net assets, at which the swap is reset. |
SyntheticReplication ¶
SyntheticReplication(
basket: AnyIndexDefinition | Mapping[str, float],
spread_bps: float = 0.0,
exposure_limit: float = UCITS_EXPOSURE_LIMIT,
)
Bases: Replication
A substitute basket held, its return swapped for the index's.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
basket
|
AnyIndexDefinition | Mapping[str, float]
|
What the fund holds: an index definition, calculated over the run and held at its weights, or fixed weights by identifier, which are scaled to add up to one. |
required |
spread_bps
|
float
|
The spread the fund pays on the swap, in basis points a year. |
0.0
|
exposure_limit
|
float
|
The swap's value owed to the fund, as a share of its net assets, at which the swap is reset. 0.10 (UCITS) by default. |
UCITS_EXPOSURE_LIMIT
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the basket is empty or has a weight that is not positive, the spread is not a finite number, or the limit is not above 0 and at most 1. |
spread_bps
property
¶
The spread the fund pays on the swap, in basis points a year.
exposure_limit
property
¶
The share of net assets owed to the fund at which the swap resets.
basket_index
property
¶
The basket's index definition, or None for fixed weights.
with_basket ¶
This replication with its basket index's calculation, whose weights it holds at each rebalance.
tracking ¶
Index tracking: holding an index, in full or through a subset.
Backtest(initial_capital=1e8).run(
IndexTracking(my_index, replication=OptimisedReplication(holdings=50)),
start="2023-01-03", end="2024-12-31")
A bare index definition passed to run() is tracked in full. IndexTracking
says how else to hold it. The index itself is still calculated and is what
the run is measured against; at each rebalance the replication turns the
index's weights into the weights the portfolio trades to.
FullReplication: every constituent at its index weight.OptimisedReplication: a subset weighted by the optimiser to minimise tracking error.SampledReplication: the largest names in each sector and size cell, each cell at its index weight.
Optimised. At each rebalance the covariance of the constituents is estimated from their trailing daily returns in the book's currency (a year by default), shrunk toward constant correlation, and the optimiser finds the long-only weights closest to the index in tracking error, within a holdings limit and any other constraints. A name with too little history to measure is held at its index weight, outside the optimisation.
Sampled (stratified). The constituents are split into cells by sector and by size (terciles of market cap by default). Each cell is given holdings in proportion to its index weight, at least one where the limit allows, holds its largest names by index weight, and is scaled to its index weight. A limit smaller than the number of cells keeps the heaviest cells, and the others' weight is spread across them.
ReplicationStep
dataclass
¶
ReplicationStep(
date: Timestamp,
weights: dict[str, float],
holdings: int,
tracking_error: float | None = None,
unmeasured: tuple[str, ...] = tuple(),
)
What a replication did at one rebalance.
Attributes:
| Name | Type | Description |
|---|---|---|
date |
Timestamp
|
The rebalance date. |
weights |
dict[str, float]
|
The weights the portfolio traded to. |
holdings |
int
|
How many names they hold. |
tracking_error |
float | None
|
The ex-ante annualised tracking error to the index, for an optimised replication; None when it was not estimated. |
unmeasured |
tuple[str, ...]
|
Names held at their index weight because their history was too short to measure. |
Replication ¶
Bases: ABC
How an index is held: from its weights at a rebalance to the portfolio's.
FullReplication ¶
OptimisedReplication ¶
OptimisedReplication(
holdings: int | None = None,
constraints: Sequence[Constraint] = (),
lookback_days: int = DEFAULT_LOOKBACK_DAYS,
minimum_observations: int = MINIMUM_OBSERVATIONS,
)
Bases: Replication
A subset weighted to minimise tracking error to the index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
holdings
|
int | None
|
The most names to hold, or None for no limit. |
None
|
constraints
|
Sequence[Constraint]
|
Further optimiser constraints, such as |
()
|
lookback_days
|
int
|
Trading days of returns the covariance is estimated over. |
DEFAULT_LOOKBACK_DAYS
|
minimum_observations
|
int
|
The fewest returns a name needs to be measured; a name with fewer is held at its index weight. |
MINIMUM_OBSERVATIONS
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If holdings is below 1 or the windows are too short. |
SampledReplication ¶
Bases: Replication
The largest names in each sector and size cell, each cell at its index weight.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
holdings
|
int
|
How many names to hold. |
required |
size_buckets
|
int
|
How many size groups (by market cap) each sector is split into: 3 for terciles. |
3
|
scheme
|
str
|
The classification the sectors are read from. |
'SECTOR'
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If holdings or size_buckets is below 1. |
IndexTracking ¶
A strategy that holds an index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index
|
AnyIndexDefinition
|
The index to track. |
required |
replication
|
Replication | None
|
How it is held; in full by default. |
None
|
replicated ¶
replicated(
snapshots: dict[Timestamp, dict[str, float]],
context: StrategyContext,
) -> list[ReplicationStep]
The replication at each of the index's rebalances, in date order.