0
# Records Management
1
2
Core record classes for managing and analyzing trading data including orders, trades, positions, and drawdowns with efficient sparse data structures. The records module provides the foundation for VectorBT's high-performance backtesting and analysis capabilities.
3
4
## Core Imports
5
6
```python
7
from vectorbt import Records, MappedArray
8
from vectorbt.records import Orders, Trades, Positions, Drawdowns
9
```
10
11
## Capabilities
12
13
### Base Record Classes
14
15
Core classes for managing and analyzing record-based data with efficient sparse storage and vectorized operations.
16
17
```python { .api }
18
class Records:
19
"""
20
Base class for all record types in VectorBT.
21
22
Provides common functionality for record storage, filtering, and analysis
23
with efficient memory usage and vectorized operations.
24
"""
25
26
@property
27
def records_arr(self):
28
"""Get underlying structured array of records."""
29
30
def filter_by_mask(self, mask, **kwargs):
31
"""
32
Filter records by boolean mask.
33
34
Parameters:
35
- mask: array-like, boolean mask for filtering records
36
37
Returns:
38
Records: Filtered records instance
39
"""
40
41
def apply_mask(self, mask, **kwargs):
42
"""Apply boolean mask to records."""
43
44
def count(self):
45
"""Count total number of records."""
46
47
def map_field(self, field, **kwargs):
48
"""Map record field to output array."""
49
50
class MappedArray:
51
"""
52
Efficient array structure for sparse data storage.
53
54
Maps record indices to array positions enabling efficient storage
55
and retrieval of sparse trading data.
56
"""
57
58
@property
59
def id_arr(self):
60
"""Array of indices."""
61
62
@property
63
def col_arr(self):
64
"""Array of column indices."""
65
66
@property
67
def values(self):
68
"""Array of values."""
69
70
def map_to_mask(self, **kwargs):
71
"""Map values to boolean mask."""
72
73
def to_pd(self, **kwargs):
74
"""Convert to pandas Series or DataFrame."""
75
```
76
77
### Order Records
78
79
Management and analysis of order execution records with detailed order-level information.
80
81
```python { .api }
82
class Orders(Records):
83
"""
84
Order execution records management.
85
86
Stores and analyzes order-level information including size, price,
87
fees, and execution details for comprehensive trade analysis.
88
"""
89
90
@property
91
def size(self):
92
"""Order sizes (positive for buy, negative for sell)."""
93
94
@property
95
def price(self):
96
"""Order execution prices."""
97
98
@property
99
def fees(self):
100
"""Order execution fees."""
101
102
@property
103
def side(self):
104
"""Order sides (0=Buy, 1=Sell)."""
105
106
def total_size(self, **kwargs):
107
"""Total order size by column."""
108
109
def total_fees(self, **kwargs):
110
"""Total fees paid by column."""
111
112
def buy_orders(self, **kwargs):
113
"""Filter buy orders only."""
114
115
def sell_orders(self, **kwargs):
116
"""Filter sell orders only."""
117
```
118
119
### Trade Records
120
121
Comprehensive trade analysis with entry/exit matching and performance calculation.
122
123
```python { .api }
124
class Trades(Records):
125
"""
126
Trade records with entry/exit matching.
127
128
Analyzes completed trades with detailed performance metrics,
129
duration analysis, and P&L calculations.
130
"""
131
132
@property
133
def entry_idx(self):
134
"""Entry timestamp indices."""
135
136
@property
137
def exit_idx(self):
138
"""Exit timestamp indices."""
139
140
@property
141
def entry_price(self):
142
"""Trade entry prices."""
143
144
@property
145
def exit_price(self):
146
"""Trade exit prices."""
147
148
@property
149
def size(self):
150
"""Trade sizes."""
151
152
@property
153
def pnl(self):
154
"""Trade profit/loss amounts."""
155
156
@property
157
def return_pct(self):
158
"""Trade returns as percentages."""
159
160
@property
161
def duration(self):
162
"""Trade durations."""
163
164
def winning_trades(self, **kwargs):
165
"""Filter winning trades."""
166
167
def losing_trades(self, **kwargs):
168
"""Filter losing trades."""
169
170
def expectancy(self, **kwargs):
171
"""Calculate trade expectancy."""
172
173
def win_rate(self, **kwargs):
174
"""Calculate win rate percentage."""
175
176
class EntryTrades(Trades):
177
"""Entry-specific trade records for detailed entry analysis."""
178
179
class ExitTrades(Trades):
180
"""Exit-specific trade records for detailed exit analysis."""
181
```
182
183
### Position Records
184
185
Position tracking with detailed exposure and holding period analysis.
186
187
```python { .api }
188
class Positions(Records):
189
"""
190
Position records tracking.
191
192
Monitors position sizes, durations, and P&L for portfolio
193
analysis and risk management.
194
"""
195
196
@property
197
def entry_idx(self):
198
"""Position entry timestamp indices."""
199
200
@property
201
def exit_idx(self):
202
"""Position exit timestamp indices."""
203
204
@property
205
def size(self):
206
"""Position sizes."""
207
208
@property
209
def duration(self):
210
"""Position durations."""
211
212
@property
213
def pnl(self):
214
"""Position profit/loss."""
215
216
def long_positions(self, **kwargs):
217
"""Filter long positions."""
218
219
def short_positions(self, **kwargs):
220
"""Filter short positions."""
221
222
def avg_duration(self, **kwargs):
223
"""Average position duration."""
224
```
225
226
### Drawdown Records
227
228
Drawdown period analysis with detailed recovery tracking and risk metrics.
229
230
```python { .api }
231
class Drawdowns(Records):
232
"""
233
Drawdown period analysis.
234
235
Tracks drawdown periods, depths, and recovery times for
236
comprehensive risk analysis and portfolio evaluation.
237
"""
238
239
@property
240
def start_idx(self):
241
"""Drawdown start indices."""
242
243
@property
244
def valley_idx(self):
245
"""Drawdown valley (lowest point) indices."""
246
247
@property
248
def end_idx(self):
249
"""Drawdown end indices."""
250
251
@property
252
def drawdown(self):
253
"""Drawdown percentages."""
254
255
@property
256
def duration(self):
257
"""Drawdown durations."""
258
259
@property
260
def recovery_duration(self):
261
"""Recovery durations."""
262
263
def max_drawdown(self, **kwargs):
264
"""Maximum drawdown by column."""
265
266
def avg_drawdown(self, **kwargs):
267
"""Average drawdown by column."""
268
269
def recovery_factor(self, **kwargs):
270
"""Recovery factor calculation."""
271
```
272
273
## Usage Examples
274
275
### Basic Record Filtering
276
277
```python
278
import vectorbt as vbt
279
280
# Get portfolio trades
281
portfolio = vbt.Portfolio.from_signals(price, entries, exits)
282
trades = portfolio.trades
283
284
# Filter winning trades
285
winning_trades = trades.winning_trades()
286
print(f"Win rate: {trades.win_rate():.2%}")
287
288
# Analyze trade durations
289
avg_duration = trades.duration.mean()
290
print(f"Average trade duration: {avg_duration}")
291
```
292
293
### Order Analysis
294
295
```python
296
# Analyze order execution
297
orders = portfolio.orders
298
299
# Calculate total trading costs
300
total_fees = orders.total_fees()
301
print(f"Total fees paid: ${total_fees:.2f}")
302
303
# Analyze buy vs sell orders
304
buy_orders = orders.buy_orders()
305
sell_orders = orders.sell_orders()
306
```
307
308
### Drawdown Analysis
309
310
```python
311
# Analyze drawdown periods
312
drawdowns = portfolio.drawdowns
313
314
# Find maximum drawdown
315
max_dd = drawdowns.max_drawdown()
316
print(f"Maximum drawdown: {max_dd:.2%}")
317
318
# Analyze recovery patterns
319
avg_recovery = drawdowns.recovery_duration.mean()
320
print(f"Average recovery time: {avg_recovery} periods")
321
```
322
323
## Types
324
325
```python { .api }
326
# Record field types
327
from vectorbt.records.enums import *
328
329
# Order record structure
330
Order = np.dtype([
331
('id', np.int_),
332
('col', np.int_),
333
('idx', np.int_),
334
('size', np.float_),
335
('price', np.float_),
336
('fees', np.float_),
337
('side', np.int_)
338
])
339
340
# Trade record structure
341
Trade = np.dtype([
342
('id', np.int_),
343
('col', np.int_),
344
('entry_idx', np.int_),
345
('exit_idx', np.int_),
346
('entry_price', np.float_),
347
('exit_price', np.float_),
348
('size', np.float_),
349
('pnl', np.float_),
350
('return_pct', np.float_)
351
])
352
```