0
# Algorithm Components
1
2
Comprehensive library of 50+ algorithmic building blocks for strategy logic, organized into functional categories. These components can be mixed and matched to create complex trading strategies while maintaining modularity and reusability.
3
4
## Capabilities
5
6
### Execution Control Algorithms
7
8
Control when strategy logic executes based on time periods, dates, or other conditions.
9
10
```python { .api }
11
class RunOnce(Algo):
12
"""Returns True on first run, then False."""
13
def __init__(self): ...
14
def __call__(self, target): ...
15
16
class RunDaily(RunPeriod):
17
"""Returns True on day change."""
18
def __init__(self, run_on_first_date=True, run_on_end_of_period=False, run_on_last_date=False): ...
19
def __call__(self, target): ...
20
21
class RunWeekly(RunPeriod):
22
"""Returns True on week change."""
23
def __init__(self, run_on_first_date=True, run_on_end_of_period=False, run_on_last_date=False): ...
24
25
class RunMonthly(RunPeriod):
26
"""Returns True on month change."""
27
def __init__(self, run_on_first_date=True, run_on_end_of_period=False, run_on_last_date=False): ...
28
29
class RunQuarterly(RunPeriod):
30
"""Returns True on quarter change."""
31
def __init__(self, run_on_first_date=True, run_on_end_of_period=False, run_on_last_date=False): ...
32
33
class RunYearly(RunPeriod):
34
"""Returns True on year change."""
35
def __init__(self, run_on_first_date=True, run_on_end_of_period=False, run_on_last_date=False): ...
36
37
class RunOnDate(Algo):
38
"""Returns True on specific dates."""
39
def __init__(self, *dates): ...
40
41
class RunAfterDate(Algo):
42
"""Returns True after specified date."""
43
def __init__(self, date): ...
44
45
class RunAfterDays(Algo):
46
"""Returns True after specified trading days."""
47
def __init__(self, days: int): ...
48
49
class RunIfOutOfBounds(Algo):
50
"""Returns True if weights deviate beyond tolerance."""
51
def __init__(self, tolerance: float): ...
52
53
class RunEveryNPeriods(Algo):
54
"""Runs every N periods."""
55
def __init__(self, n: int, offset=0): ...
56
```
57
58
### Security Selection Algorithms
59
60
Select which securities to include in the strategy based on various criteria.
61
62
```python { .api }
63
class SelectAll(Algo):
64
"""Selects all securities from universe."""
65
def __init__(self, include_no_data=False, include_negative=False): ...
66
67
class SelectThese(Algo):
68
"""Selects specific list of tickers."""
69
def __init__(self, tickers: list, include_no_data=False, include_negative=False): ...
70
71
class SelectHasData(Algo):
72
"""Selects securities with sufficient data history."""
73
def __init__(self, lookback=None, min_count=None, include_no_data=False, include_negative=False): ...
74
75
class SelectN(Algo):
76
"""Selects top/bottom N securities based on ranking."""
77
def __init__(self, n: int, sort_descending=True, all_or_none=False, filter_selected=False): ...
78
79
class SelectMomentum(AlgoStack):
80
"""Selects securities based on momentum ranking."""
81
def __init__(self, n: int, lookback=None, lag=None, sort_descending=True, all_or_none=False): ...
82
83
class SelectWhere(Algo):
84
"""Selects securities based on boolean indicator."""
85
def __init__(self, signal, include_no_data=False, include_negative=False): ...
86
87
class SelectRandomly(Algo):
88
"""Selects random subset of securities."""
89
def __init__(self, n=None, include_no_data=False, include_negative=False): ...
90
91
class SelectRegex(Algo):
92
"""Selects securities matching regex pattern."""
93
def __init__(self, regex: str): ...
94
95
class SelectTypes(Algo):
96
"""Selects securities by node type."""
97
def __init__(self, include_types=None, exclude_types=None): ...
98
99
class SelectActive(Algo):
100
"""Filters out closed or rolled securities."""
101
def __call__(self, target): ...
102
103
class ResolveOnTheRun(Algo):
104
"""Resolves on-the-run security aliases."""
105
def __init__(self, on_the_run: dict, include_no_data=False, include_negative=False): ...
106
```
107
108
### Weighting Algorithms
109
110
Determine how to allocate capital among selected securities.
111
112
```python { .api }
113
class WeighEqually(Algo):
114
"""Sets equal weights for selected securities."""
115
def __call__(self, target): ...
116
117
class WeighSpecified(Algo):
118
"""Sets weights from specified dictionary."""
119
def __init__(self, **weights): ...
120
121
class ScaleWeights(Algo):
122
"""Scales existing weights by factor."""
123
def __init__(self, scale: float): ...
124
125
class WeighTarget(Algo):
126
"""Sets weights from target DataFrame."""
127
def __init__(self, weights): ...
128
129
class WeighInvVol(Algo):
130
"""Sets inverse volatility weights (risk parity)."""
131
def __init__(self, lookback=None, lag=None): ...
132
133
class WeighERC(Algo):
134
"""Sets equal risk contribution weights."""
135
def __init__(self, lookback=None, initial_weights=None, risk_weights=None,
136
covar_method="ledoit-wolf", risk_parity_method="ccd",
137
maximum_iterations=100, tolerance=1e-8, lag=None): ...
138
139
class WeighMeanVar(Algo):
140
"""Sets mean-variance optimization weights."""
141
def __init__(self, lookback=None, bounds=(0.0, 1.0), covar_method="ledoit-wolf",
142
rf=0.0, lag=None): ...
143
144
class WeighRandomly(Algo):
145
"""Sets random weights for benchmarking."""
146
def __init__(self, bounds=(0.0, 1.0), weight_sum=1): ...
147
```
148
149
### Portfolio Management Algorithms
150
151
Manage portfolio positions, risk, and execution.
152
153
```python { .api }
154
class Rebalance(Algo):
155
"""Main rebalancing algorithm using temp weights."""
156
def __call__(self, target): ...
157
158
class RebalanceOverTime(Algo):
159
"""Rebalances to target over multiple periods."""
160
def __init__(self, n=10): ...
161
162
class LimitDeltas(Algo):
163
"""Limits weight changes between periods."""
164
def __init__(self, limit=0.1): ...
165
166
class LimitWeights(Algo):
167
"""Limits maximum individual asset weights."""
168
def __init__(self, limit=0.1): ...
169
170
class TargetVol(Algo):
171
"""Scales weights to target volatility."""
172
def __init__(self, target_volatility: float, lookback=None, lag=None,
173
covar_method="standard", annualization_factor=252): ...
174
175
class PTE_Rebalance(Algo):
176
"""Triggers rebalance based on tracking error."""
177
def __init__(self, PTE_volatility_cap: float, target_weights, lookback=None,
178
lag=None, covar_method="standard", annualization_factor=252): ...
179
180
class CapitalFlow(Algo):
181
"""Models capital inflows/outflows."""
182
def __init__(self, amount: float): ...
183
184
class CloseDead(Algo):
185
"""Closes positions with zero prices."""
186
def __call__(self, target): ...
187
188
class SetNotional(Algo):
189
"""Sets notional value for fixed income strategies."""
190
def __init__(self, notional_value: float): ...
191
```
192
193
### Advanced Portfolio Management
194
195
Specialized algorithms for complex portfolio operations.
196
197
```python { .api }
198
class ClosePositionsAfterDates(Algo):
199
"""Closes positions after specified dates."""
200
def __init__(self, close_dates: dict): ...
201
202
class RollPositionsAfterDates(Algo):
203
"""Rolls securities based on mapping."""
204
def __init__(self, roll_data: dict): ...
205
206
class ReplayTransactions(Algo):
207
"""Replays executed transactions."""
208
def __init__(self, transactions): ...
209
210
class SimulateRFQTransactions(Algo):
211
"""Simulates RFQ transaction outcomes."""
212
def __init__(self, rfqs, model): ...
213
```
214
215
### Statistics and Data Algorithms
216
217
Calculate and store statistical measures for use by other algorithms.
218
219
```python { .api }
220
class SetStat(Algo):
221
"""Sets statistic in temp data for downstream use."""
222
def __init__(self, stat: str, lag=None): ...
223
224
class StatTotalReturn(Algo):
225
"""Calculates total returns over period."""
226
def __init__(self, lookback=None, lag=None): ...
227
```
228
229
### Risk Management Algorithms
230
231
Monitor and manage risk exposures across the strategy.
232
233
```python { .api }
234
class UpdateRisk(Algo):
235
"""Tracks risk measures across strategy nodes."""
236
def __init__(self, measure: str, history=0): ...
237
238
class PrintRisk(Algo):
239
"""Prints risk data for debugging."""
240
def __init__(self, fmt_string=""): ...
241
242
class HedgeRisks(Algo):
243
"""Hedges risk measures with instruments."""
244
def __init__(self, measures: dict, pseudo=False, strategy=None, throw_nan=True): ...
245
```
246
247
### Flow Control Algorithms
248
249
Control algorithm execution flow with logical operations.
250
251
```python { .api }
252
class Require(Algo):
253
"""Controls flow based on predicate evaluation."""
254
def __init__(self, pred, item, if_none=False): ...
255
256
class Not(Algo):
257
"""Inverts return value of another algorithm."""
258
def __init__(self, algo: Algo): ...
259
260
class Or(Algo):
261
"""Combines multiple signals with OR logic."""
262
def __init__(self, list_of_algos: list): ...
263
```
264
265
### Debugging Algorithms
266
267
Utility algorithms for debugging and monitoring strategy execution.
268
269
```python { .api }
270
class PrintDate(Algo):
271
"""Prints current date for debugging."""
272
def __call__(self, target): ...
273
274
class PrintTempData(Algo):
275
"""Prints temporary data with optional formatting."""
276
def __init__(self, fmt_string=None): ...
277
278
class PrintInfo(Algo):
279
"""Prints strategy information with formatting."""
280
def __init__(self, fmt_string="{name} {now}"): ...
281
282
class Debug(Algo):
283
"""Triggers debugger (pdb.set_trace)."""
284
def __call__(self, target): ...
285
```
286
287
## Decorators
288
289
```python { .api }
290
def run_always(f):
291
"""Ensure algorithm runs on each pass regardless of stack failures."""
292
...
293
```
294
295
## Usage Examples
296
297
### Building Algorithm Stacks
298
299
```python
300
# Monthly momentum strategy
301
strategy = bt.Strategy('Momentum', [
302
bt.algos.RunMonthly(),
303
bt.algos.SelectAll(),
304
bt.algos.SelectMomentum(10, lookback=pd.DateOffset(months=3)),
305
bt.algos.WeighEqually(),
306
bt.algos.Rebalance()
307
])
308
309
# Risk parity with volatility targeting
310
strategy = bt.Strategy('RiskParity', [
311
bt.algos.RunMonthly(),
312
bt.algos.SelectAll(),
313
bt.algos.WeighInvVol(lookback=pd.DateOffset(months=6)),
314
bt.algos.TargetVol(0.12),
315
bt.algos.Rebalance()
316
])
317
```
318
319
### Conditional Execution
320
321
```python
322
# Rebalance only when out of bounds
323
strategy = bt.Strategy('ConditionalRebalance', [
324
bt.algos.RunDaily(),
325
bt.algos.RunIfOutOfBounds(0.05), # Only if >5% deviation
326
bt.algos.SelectAll(),
327
bt.algos.WeighEqually(),
328
bt.algos.Rebalance()
329
])
330
```
331
332
### Complex Selection Logic
333
334
```python
335
# Select top 20 momentum stocks with data requirements
336
strategy = bt.Strategy('TopMomentum', [
337
bt.algos.RunMonthly(),
338
bt.algos.SelectHasData(lookback=pd.DateOffset(months=12)),
339
bt.algos.SelectMomentum(20, lookback=pd.DateOffset(months=3)),
340
bt.algos.WeighEqually(),
341
bt.algos.Rebalance()
342
])
343
```