0
# Technical Indicators & Signal Generation
1
2
Comprehensive library of technical indicators and signal generation tools with factory pattern for creating custom indicators. Includes traditional indicators, advanced statistical measures, and sophisticated signal processing capabilities.
3
4
## Capabilities
5
6
### Technical Indicators
7
8
Built-in library of common technical indicators with vectorized implementations for high performance.
9
10
```python { .api }
11
class MA:
12
"""
13
Moving Average indicator with multiple averaging methods.
14
15
Supports simple, exponential, weighted, and other moving average types
16
with full vectorization for efficient computation.
17
"""
18
19
@classmethod
20
def run(cls, close, window, ma_type='simple', **kwargs):
21
"""
22
Calculate moving average.
23
24
Parameters:
25
- close: pd.Series or pd.DataFrame, price data
26
- window: int, moving average window size
27
- ma_type: str, averaging method ('simple', 'exp', 'weighted')
28
- alpha: float, smoothing factor for exponential MA
29
- adjust: bool, adjust exponential MA calculation
30
31
Returns:
32
MA: Indicator instance with ma attribute
33
"""
34
35
def ma_crossed_above(self, other):
36
"""
37
Generate signals when MA crosses above another series.
38
39
Parameters:
40
- other: pd.Series or MA instance, comparison series
41
42
Returns:
43
pd.Series: Boolean crossing signals
44
"""
45
46
def ma_crossed_below(self, other):
47
"""Generate signals when MA crosses below another series."""
48
49
class MSTD:
50
"""Moving Standard Deviation indicator."""
51
52
@classmethod
53
def run(cls, close, window, **kwargs):
54
"""
55
Calculate moving standard deviation.
56
57
Parameters:
58
- close: pd.Series or pd.DataFrame, price data
59
- window: int, calculation window
60
- ddof: int, degrees of freedom (default: 1)
61
62
Returns:
63
MSTD: Indicator instance with mstd attribute
64
"""
65
66
class BBANDS:
67
"""
68
Bollinger Bands indicator with configurable parameters.
69
70
Calculates upper and lower bands based on moving average and
71
standard deviation with customizable multipliers.
72
"""
73
74
@classmethod
75
def run(cls, close, window=20, alpha=2.0, **kwargs):
76
"""
77
Calculate Bollinger Bands.
78
79
Parameters:
80
- close: pd.Series or pd.DataFrame, price data
81
- window: int, moving average window (default: 20)
82
- alpha: float, standard deviation multiplier (default: 2.0)
83
- ma_type: str, moving average type (default: 'simple')
84
85
Returns:
86
BBANDS: Indicator with upper, middle, lower attributes
87
"""
88
89
class RSI:
90
"""
91
Relative Strength Index momentum oscillator.
92
93
Measures speed and magnitude of price changes with values
94
ranging from 0 to 100, commonly used for overbought/oversold signals.
95
"""
96
97
@classmethod
98
def run(cls, close, window=14, **kwargs):
99
"""
100
Calculate RSI.
101
102
Parameters:
103
- close: pd.Series or pd.DataFrame, price data
104
- window: int, RSI calculation window (default: 14)
105
106
Returns:
107
RSI: Indicator instance with rsi attribute
108
"""
109
110
class MACD:
111
"""
112
Moving Average Convergence Divergence indicator.
113
114
Trend-following momentum indicator showing relationship between
115
two moving averages with signal line and histogram.
116
"""
117
118
@classmethod
119
def run(cls, close, fast_window=12, slow_window=26, signal_window=9, **kwargs):
120
"""
121
Calculate MACD.
122
123
Parameters:
124
- close: pd.Series or pd.DataFrame, price data
125
- fast_window: int, fast EMA period (default: 12)
126
- slow_window: int, slow EMA period (default: 26)
127
- signal_window: int, signal line EMA period (default: 9)
128
129
Returns:
130
MACD: Indicator with macd, signal, histogram attributes
131
"""
132
133
class STOCH:
134
"""Stochastic Oscillator indicator."""
135
136
@classmethod
137
def run(cls, high, low, close, k_window=14, d_window=3, **kwargs):
138
"""
139
Calculate Stochastic Oscillator.
140
141
Parameters:
142
- high: pd.Series or pd.DataFrame, high prices
143
- low: pd.Series or pd.DataFrame, low prices
144
- close: pd.Series or pd.DataFrame, close prices
145
- k_window: int, %K period
146
- d_window: int, %D smoothing period
147
148
Returns:
149
STOCH: Indicator with percent_k, percent_d attributes
150
"""
151
152
class ATR:
153
"""Average True Range volatility indicator."""
154
155
@classmethod
156
def run(cls, high, low, close, window=14, **kwargs):
157
"""
158
Calculate ATR.
159
160
Parameters:
161
- high: pd.Series or pd.DataFrame, high prices
162
- low: pd.Series or pd.DataFrame, low prices
163
- close: pd.Series or pd.DataFrame, close prices
164
- window: int, ATR period (default: 14)
165
166
Returns:
167
ATR: Indicator instance with atr attribute
168
"""
169
170
class OBV:
171
"""On-Balance Volume indicator."""
172
173
@classmethod
174
def run(cls, close, volume, **kwargs):
175
"""
176
Calculate OBV.
177
178
Parameters:
179
- close: pd.Series or pd.DataFrame, close prices
180
- volume: pd.Series or pd.DataFrame, volume data
181
182
Returns:
183
OBV: Indicator instance with obv attribute
184
"""
185
```
186
187
### Indicator Factory System
188
189
Factory pattern for creating custom indicators and integrating external indicator libraries.
190
191
```python { .api }
192
class IndicatorFactory:
193
"""
194
Factory for creating custom technical indicators.
195
196
Provides framework for building indicators with consistent interface,
197
parameter validation, and result caching.
198
"""
199
200
@classmethod
201
def create(cls, name, **kwargs):
202
"""
203
Create custom indicator.
204
205
Parameters:
206
- name: str, indicator name
207
- kwargs: indicator parameters
208
209
Returns:
210
IndicatorBase: Custom indicator instance
211
"""
212
213
class IndicatorBase:
214
"""
215
Base class for all indicators.
216
217
Provides common functionality including parameter management,
218
caching, and result access patterns.
219
"""
220
221
def __init__(self, **kwargs):
222
"""Initialize indicator with parameters."""
223
224
def run(self, *args, **kwargs):
225
"""Run indicator calculation (implemented by subclasses)."""
226
227
def talib(name, *args, **kwargs):
228
"""
229
Create indicator from TA-Lib library.
230
231
Parameters:
232
- name: str, TA-Lib function name
233
- args: input data arrays
234
- kwargs: function parameters
235
236
Returns:
237
IndicatorBase: TA-Lib indicator wrapper
238
"""
239
240
def pandas_ta(name, *args, **kwargs):
241
"""
242
Create indicator from pandas-ta library.
243
244
Parameters:
245
- name: str, pandas-ta function name
246
- args: input data
247
- kwargs: function parameters
248
249
Returns:
250
IndicatorBase: pandas-ta indicator wrapper
251
"""
252
253
def ta(name, *args, **kwargs):
254
"""
255
Create indicator from ta library.
256
257
Parameters:
258
- name: str, ta library function name
259
- args: input data
260
- kwargs: function parameters
261
262
Returns:
263
IndicatorBase: ta library indicator wrapper
264
"""
265
```
266
267
### Signal Generation
268
269
Advanced signal generation system for creating entry/exit rules with support for complex conditional logic.
270
271
```python { .api }
272
class SignalFactory:
273
"""
274
Factory for creating signal generators.
275
276
Provides framework for building custom signal generation logic
277
with parameter validation and consistent interfaces.
278
"""
279
280
@classmethod
281
def create(cls, name, **kwargs):
282
"""Create custom signal generator."""
283
284
class RAND:
285
"""Random signal generator for strategy testing."""
286
287
@classmethod
288
def run(cls, shape, prob=0.1, seed=None, **kwargs):
289
"""
290
Generate random boolean signals.
291
292
Parameters:
293
- shape: tuple, output shape (n_rows, n_cols)
294
- prob: float, probability of True signal (default: 0.1)
295
- seed: int, random seed for reproducibility
296
297
Returns:
298
pd.DataFrame: Random boolean signals
299
"""
300
301
class RANDX:
302
"""Random exit signal generator."""
303
304
@classmethod
305
def run(cls, entries, prob=0.1, seed=None, **kwargs):
306
"""
307
Generate random exit signals based on entries.
308
309
Parameters:
310
- entries: pd.Series or pd.DataFrame, entry signals
311
- prob: float, exit probability per period
312
- seed: int, random seed
313
314
Returns:
315
pd.DataFrame: Random exit signals
316
"""
317
318
class RANDNX:
319
"""Random entry/exit signal generator."""
320
321
@classmethod
322
def run(cls, shape, entry_prob=0.1, exit_prob=0.1, seed=None, **kwargs):
323
"""Generate random entry and exit signals."""
324
325
class RPROB:
326
"""Random probability signal generator."""
327
328
@classmethod
329
def run(cls, shape, prob_func=None, seed=None, **kwargs):
330
"""
331
Generate signals based on probability function.
332
333
Parameters:
334
- shape: tuple, output shape
335
- prob_func: callable, function returning probabilities
336
- seed: int, random seed
337
338
Returns:
339
pd.DataFrame: Probability-based signals
340
"""
341
```
342
343
### Stop Signal Generation
344
345
Sophisticated stop loss and take profit signal generation with trailing stops and conditional logic.
346
347
```python { .api }
348
class STX:
349
"""Stop signal generator for exits."""
350
351
@classmethod
352
def run(cls, entries, stops, stop_type='stop_loss', **kwargs):
353
"""
354
Generate stop-based exit signals.
355
356
Parameters:
357
- entries: pd.Series or pd.DataFrame, entry signals
358
- stops: float or pd.Series, stop levels
359
- stop_type: str, stop type ('stop_loss', 'take_profit', 'trail_stop')
360
361
Returns:
362
pd.DataFrame: Stop-based exit signals
363
"""
364
365
class STCX:
366
"""Stop chain signal generator."""
367
368
@classmethod
369
def run(cls, entries, stops, **kwargs):
370
"""Generate chained stop signals."""
371
372
class OHLCSTX:
373
"""OHLC-based stop signal generator."""
374
375
@classmethod
376
def run(cls, entries, open, high, low, close, stops, **kwargs):
377
"""
378
Generate stop signals using OHLC data.
379
380
Parameters:
381
- entries: pd.Series or pd.DataFrame, entry signals
382
- open, high, low, close: pd.Series, OHLC price data
383
- stops: float or pd.Series, stop levels or percentages
384
385
Returns:
386
pd.DataFrame: OHLC-based stop signals
387
"""
388
389
class OHLCSTCX:
390
"""OHLC-based stop chain signal generator."""
391
```
392
393
### Enums and Types
394
395
```python { .api }
396
class StopType(IntEnum):
397
"""Stop signal types."""
398
StopLoss = 0
399
TrailStop = 1
400
TakeProfit = 2
401
402
class FactoryMode(IntEnum):
403
"""Signal factory modes."""
404
Entries = 0
405
Exits = 1
406
Both = 2
407
Chain = 3
408
```
409
410
## Usage Examples
411
412
### Basic Indicator Usage
413
414
```python
415
import vectorbt as vbt
416
417
# Download data
418
data = vbt.YFData.download("AAPL", start="2020-01-01", end="2023-01-01")
419
close = data.get("Close")
420
high = data.get("High")
421
low = data.get("Low")
422
volume = data.get("Volume")
423
424
# Calculate indicators
425
ma20 = vbt.MA.run(close, 20)
426
ma50 = vbt.MA.run(close, 50)
427
rsi = vbt.RSI.run(close, 14)
428
macd = vbt.MACD.run(close)
429
bbands = vbt.BBANDS.run(close, window=20, alpha=2.0)
430
431
# Access indicator values
432
ma20_values = ma20.ma
433
rsi_values = rsi.rsi
434
macd_line = macd.macd
435
macd_signal = macd.signal
436
upper_band = bbands.upper
437
lower_band = bbands.lower
438
```
439
440
### Signal Generation
441
442
```python
443
# Moving average crossover signals
444
entries = ma20.ma_crossed_above(ma50.ma)
445
exits = ma20.ma_crossed_below(ma50.ma)
446
447
# RSI overbought/oversold signals
448
rsi_oversold = rsi.rsi < 30
449
rsi_overbought = rsi.rsi > 70
450
451
# Bollinger Bands signals
452
bb_lower_touch = close <= bbands.lower
453
bb_upper_touch = close >= bbands.upper
454
455
# Combine multiple conditions
456
combined_entries = entries & rsi_oversold & bb_lower_touch
457
combined_exits = exits | rsi_overbought | bb_upper_touch
458
```
459
460
### Custom Indicators with TA-Lib
461
462
```python
463
# Using TA-Lib indicators
464
import talib
465
466
# Create TA-Lib indicator
467
stoch_k, stoch_d = vbt.talib('STOCH', high, low, close)
468
469
# Williams %R
470
willr = vbt.talib('WILLR', high, low, close, timeperiod=14)
471
472
# Commodity Channel Index
473
cci = vbt.talib('CCI', high, low, close, timeperiod=14)
474
```
475
476
### Advanced Signal Processing
477
478
```python
479
# Random signal testing
480
random_entries = vbt.RAND.run(
481
shape=close.shape,
482
prob=0.05, # 5% entry probability
483
seed=42
484
)
485
486
random_exits = vbt.RANDX.run(
487
entries=random_entries,
488
prob=0.1, # 10% exit probability per period
489
seed=42
490
)
491
492
# Stop loss signals
493
stop_exits = vbt.STX.run(
494
entries=entries,
495
stops=0.05, # 5% stop loss
496
stop_type='stop_loss'
497
)
498
499
# Trailing stop
500
trail_exits = vbt.STX.run(
501
entries=entries,
502
stops=0.03, # 3% trailing stop
503
stop_type='trail_stop'
504
)
505
506
# OHLC-based stops
507
ohlc_stops = vbt.OHLCSTX.run(
508
entries=entries,
509
open=data.get("Open"),
510
high=high,
511
low=low,
512
close=close,
513
stops=0.02 # 2% stop
514
)
515
```
516
517
### Multi-Timeframe Analysis
518
519
```python
520
# Calculate indicators on different timeframes
521
daily_close = close.resample('D').last()
522
weekly_close = close.resample('W').last()
523
524
# Daily and weekly moving averages
525
daily_ma = vbt.MA.run(daily_close, 20)
526
weekly_ma = vbt.MA.run(weekly_close, 10)
527
528
# Align timeframes for comparison
529
weekly_ma_daily = weekly_ma.ma.reindex(close.index, method='ffill')
530
531
# Multi-timeframe signals
532
daily_signal = daily_ma.ma > daily_ma.ma.shift(1)
533
weekly_signal = weekly_ma_daily > weekly_ma_daily.shift(1)
534
combined_signal = daily_signal & weekly_signal
535
```
536
537
### Custom Indicator Creation
538
539
```python
540
class CustomRSI(vbt.IndicatorBase):
541
"""Custom RSI with additional smoothing."""
542
543
def run(self, close, window=14, smooth_window=3):
544
# Calculate standard RSI
545
rsi = vbt.RSI.run(close, window)
546
547
# Apply additional smoothing
548
smoothed_rsi = vbt.MA.run(rsi.rsi, smooth_window)
549
550
return smoothed_rsi.ma
551
552
# Use custom indicator
553
custom_rsi = CustomRSI().run(close, window=14, smooth_window=3)
554
```