or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

algorithm-components.mdbacktesting-engine.mdcore-framework.mdindex.mdspecialized-securities.md

core-framework.mddocs/

0

# Core Framework Classes

1

2

Fundamental building blocks for creating strategies and securities within bt's tree structure. These classes provide the foundation for bt's modular design, enabling the construction of complex trading strategies through hierarchical composition of nodes.

3

4

## Capabilities

5

6

### Base Node Class

7

8

The fundamental building block of bt's tree structure, providing price tracking, hierarchy management, and core functionality shared by all tree components.

9

10

```python { .api }

11

class Node:

12

"""

13

Base tree node class for bt's hierarchical structure.

14

15

Args:

16

name (str): Name of the node

17

parent (Node, optional): Parent node in tree hierarchy

18

children (list, optional): List of child nodes

19

"""

20

def __init__(self, name: str, parent=None, children=None): ...

21

22

def setup(self, universe, **kwargs):

23

"""Setup node with data universe and configuration."""

24

...

25

26

def update(self, date, data=None, inow=None):

27

"""Update node state for given date."""

28

...

29

30

def adjust(self, amount, update=True, flow=True):

31

"""Adjust node value by specified amount."""

32

...

33

34

def allocate(self, amount, update=True):

35

"""Allocate capital to this node."""

36

...

37

38

def to_dot(self, root=True):

39

"""Generate graphviz representation of tree structure."""

40

...

41

42

# Properties

43

@property

44

def name(self) -> str: ...

45

@property

46

def parent(self): ...

47

@property

48

def root(self): ...

49

@property

50

def children(self) -> list: ...

51

@property

52

def now(self): ...

53

@property

54

def stale(self) -> bool: ...

55

@property

56

def prices(self): ...

57

@property

58

def price(self): ...

59

@property

60

def value(self): ...

61

@property

62

def notional_value(self): ...

63

@property

64

def weight(self): ...

65

@property

66

def full_name(self) -> str: ...

67

@property

68

def members(self) -> list: ...

69

@property

70

def fixed_income(self) -> bool: ...

71

```

72

73

### Strategy Base Class

74

75

Base class for strategy nodes that define strategy logic within the tree structure, providing core functionality for portfolio management and algorithmic execution.

76

77

```python { .api }

78

class StrategyBase(Node):

79

"""

80

Strategy base class inheriting from Node.

81

82

Args:

83

name (str): Strategy name

84

children (list, optional): Child nodes (securities/sub-strategies)

85

parent (Node, optional): Parent node

86

"""

87

def __init__(self, name: str, children=None, parent=None): ...

88

89

def setup(self, universe, **kwargs):

90

"""Setup strategy with universe data and configuration."""

91

...

92

93

def get_data(self, key):

94

"""Get data by key from universe."""

95

...

96

97

def update(self, date, data=None, inow=None):

98

"""Update strategy state for given date."""

99

...

100

101

def adjust(self, amount, update=True, flow=True, fee=0.0):

102

"""Adjust strategy value with optional fee."""

103

...

104

105

def allocate(self, amount, child=None, update=True):

106

"""Allocate capital to specific child or distribute among children."""

107

...

108

109

def transact(self, q, child=None, update=True):

110

"""Execute transaction for specific child."""

111

...

112

113

def rebalance(self, weight, child, base=float('nan'), update=True):

114

"""Rebalance position in specific child to target weight."""

115

...

116

117

def close(self, child, update=True):

118

"""Close position in specific child."""

119

...

120

121

def flatten(self):

122

"""Close all positions in strategy."""

123

...

124

125

def run(self):

126

"""Execute strategy logic."""

127

...

128

129

def set_commissions(self, fn):

130

"""Set commission calculation function."""

131

...

132

133

def get_transactions(self):

134

"""Get transaction history for strategy."""

135

...

136

137

# Properties

138

@property

139

def prices(self): ...

140

@property

141

def price(self): ...

142

@property

143

def values(self): ...

144

@property

145

def notional_values(self): ...

146

@property

147

def capital(self): ...

148

@property

149

def cash(self): ...

150

@property

151

def fees(self): ...

152

@property

153

def flows(self): ...

154

@property

155

def bidoffer_paid(self): ...

156

@property

157

def bidoffers_paid(self): ...

158

@property

159

def universe(self): ...

160

@property

161

def securities(self): ...

162

@property

163

def outlays(self): ...

164

@property

165

def positions(self): ...

166

```

167

168

### Security Base Class

169

170

Base class for security nodes representing individual securities with position tracking, transaction execution, and commission handling.

171

172

```python { .api }

173

class SecurityBase(Node):

174

"""

175

Security base class inheriting from Node.

176

177

Args:

178

name (str): Security name/ticker

179

multiplier (float): Security multiplier (default 1)

180

lazy_add (bool): Whether to add to parent lazily

181

"""

182

def __init__(self, name: str, multiplier=1, lazy_add=False): ...

183

184

def setup(self, universe, **kwargs):

185

"""Setup security with universe data."""

186

...

187

188

def update(self, date, data=None, inow=None):

189

"""Update security state for given date."""

190

...

191

192

def allocate(self, amount, update=True):

193

"""Allocate capital to this security."""

194

...

195

196

def transact(self, q, update=True, update_self=True, price=None):

197

"""Execute transaction for specified quantity."""

198

...

199

200

def commission(self, q, p):

201

"""Calculate commission for transaction."""

202

...

203

204

def outlay(self, q, p=None):

205

"""Calculate total outlay for transaction including commission."""

206

...

207

208

def run(self):

209

"""Execute security updates."""

210

...

211

212

# Properties

213

@property

214

def prices(self): ...

215

@property

216

def price(self): ...

217

@property

218

def values(self): ...

219

@property

220

def notional_values(self): ...

221

@property

222

def position(self): ...

223

@property

224

def positions(self): ...

225

@property

226

def outlays(self): ...

227

@property

228

def bidoffer(self): ...

229

@property

230

def bidoffers(self): ...

231

@property

232

def bidoffer_paid(self): ...

233

@property

234

def bidoffers_paid(self): ...

235

```

236

237

### Main Strategy Class

238

239

The primary strategy class that incorporates algorithmic logic through algorithm stacks, with temporary and permanent data storage for cross-algorithm communication.

240

241

```python { .api }

242

class Strategy(StrategyBase):

243

"""

244

Main strategy class incorporating algorithms.

245

246

Args:

247

name (str): Strategy name

248

algos (list, optional): List of algorithms to execute

249

children (list, optional): Child nodes

250

parent (Node, optional): Parent node

251

"""

252

def __init__(self, name: str, algos=None, children=None, parent=None): ...

253

254

def run(self):

255

"""Run strategy with algorithm stack execution."""

256

...

257

258

# Properties

259

@property

260

def stack(self): ... # Algorithm stack

261

@property

262

def temp(self): ... # Temporary data storage

263

@property

264

def perm(self): ... # Permanent data storage

265

```

266

267

### Standard Security Class

268

269

Standard security implementation with market value-based notional value calculation, suitable for most equity and ETF trading strategies.

270

271

```python { .api }

272

class Security(SecurityBase):

273

"""

274

Standard security with market value-based notional value.

275

276

Inherits all methods and properties from SecurityBase.

277

Notional value equals market value (price * position).

278

"""

279

pass

280

```

281

282

### Algorithm Base Classes

283

284

Base classes for creating custom algorithmic components that can be combined into strategy logic.

285

286

```python { .api }

287

class Algo:

288

"""

289

Base algorithm class for strategy building blocks.

290

291

Args:

292

name (str, optional): Algorithm name

293

"""

294

def __init__(self, name=None): ...

295

296

def __call__(self, target):

297

"""Execute algorithm logic on target strategy (abstract method)."""

298

...

299

300

@property

301

def name(self) -> str: ...

302

303

class AlgoStack(Algo):

304

"""

305

Algorithm container that runs multiple algorithms sequentially.

306

307

Args:

308

*algos: Variable number of algorithm instances

309

"""

310

def __init__(self, *algos): ...

311

312

def __call__(self, target):

313

"""Execute all algorithms in stack until one fails."""

314

...

315

```

316

317

## Utility Functions

318

319

```python { .api }

320

def is_zero(x) -> bool:

321

"""

322

Test for zero robust against floating point errors.

323

324

Args:

325

x: Value to test

326

327

Returns:

328

bool: True if value is effectively zero

329

"""

330

...

331

```

332

333

## Constants

334

335

```python { .api }

336

PAR: float = 100.0 # Par value constant for fixed income

337

TOL: float = 1e-16 # Tolerance for floating point zero comparison

338

```

339

340

## Usage Examples

341

342

### Creating a Basic Strategy Tree

343

344

```python

345

import bt

346

347

# Create securities

348

spy = bt.Security('SPY')

349

tlt = bt.Security('TLT')

350

351

# Create strategy with securities as children

352

strategy = bt.Strategy('EqualWeight', children=[spy, tlt])

353

354

# Or add securities after creation

355

strategy = bt.Strategy('EqualWeight')

356

strategy.children = [spy, tlt]

357

```

358

359

### Building Algorithm Stacks

360

361

```python

362

# Create individual algorithms

363

select_all = bt.algos.SelectAll()

364

weigh_equally = bt.algos.WeighEqually()

365

rebalance = bt.algos.Rebalance()

366

367

# Combine into algorithm stack

368

algo_stack = bt.AlgoStack(select_all, weigh_equally, rebalance)

369

370

# Use in strategy

371

strategy = bt.Strategy('MyStrategy', algos=[algo_stack])

372

```