0
# Volatility Indicators
1
2
Measures of price volatility and range-based indicators that help identify periods of high and low market volatility, support and resistance levels, and potential breakout conditions.
3
4
## Capabilities
5
6
### Bollinger Bands
7
8
Volatility bands consisting of a middle moving average line with upper and lower bands based on standard deviations.
9
10
```python { .api }
11
def get_bollinger_bands(quotes: Iterable[Quote], lookback_periods: int = 20, standard_deviations: float = 2):
12
"""
13
Bollinger Bands® - volatility bands using standard deviation boundaries from moving average.
14
15
Args:
16
quotes (Iterable[Quote]): Historical price quotes
17
lookback_periods (int): Number of periods for moving average (defaults to 20)
18
standard_deviations (float): Number of standard deviations for bands (defaults to 2)
19
20
Returns:
21
BollingerBandsResults[BollingerBandsResult]: Collection of Bollinger Bands results
22
"""
23
```
24
25
**BollingerBandsResult Properties:**
26
- `date` (datetime): Result date
27
- `sma` (Optional[Decimal]): Simple moving average (middle band)
28
- `upper_band` (Optional[Decimal]): Upper Bollinger Band
29
- `lower_band` (Optional[Decimal]): Lower Bollinger Band
30
- `percent_b` (Optional[float]): %B position within bands
31
- `z_score` (Optional[float]): Z-score relative to middle band
32
- `width` (Optional[float]): Band width as percentage
33
34
### Average True Range (ATR)
35
36
Measures market volatility by calculating the average of true ranges over a specified period.
37
38
```python { .api }
39
def get_atr(quotes: Iterable[Quote], lookback_periods: int = 14):
40
"""
41
Average True Range (ATR) - measures market volatility using true range.
42
43
Args:
44
quotes (Iterable[Quote]): Historical price quotes
45
lookback_periods (int): Number of periods for ATR calculation (defaults to 14)
46
47
Returns:
48
ATRResults[ATRResult]: Collection of ATR results
49
"""
50
```
51
52
**ATRResult Properties:**
53
- `date` (datetime): Result date
54
- `tr` (Optional[Decimal]): True Range value
55
- `atr` (Optional[Decimal]): Average True Range value
56
- `atrp` (Optional[float]): ATR as percentage of close price
57
58
### Keltner Channels
59
60
Volatility-based channels using exponential moving average and Average True Range.
61
62
```python { .api }
63
def get_keltner(quotes: Iterable[Quote], ema_periods: int = 20, multiplier: float = 2.0, atr_periods: int = 10):
64
"""
65
Keltner Channels - volatility channels using EMA and ATR.
66
67
Args:
68
quotes (Iterable[Quote]): Historical price quotes
69
ema_periods (int): EMA periods for center line (defaults to 20)
70
multiplier (float): ATR multiplier for channel width (defaults to 2.0)
71
atr_periods (int): ATR calculation periods (defaults to 10)
72
73
Returns:
74
KeltnerResults[KeltnerResult]: Collection of Keltner Channel results
75
"""
76
```
77
78
**KeltnerResult Properties:**
79
- `date` (datetime): Result date
80
- `upper_band` (Optional[Decimal]): Upper Keltner Channel
81
- `center_line` (Optional[Decimal]): EMA center line
82
- `lower_band` (Optional[Decimal]): Lower Keltner Channel
83
- `width` (Optional[float]): Channel width as percentage
84
85
### Donchian Channels
86
87
Price channels based on highest high and lowest low over a lookback period.
88
89
```python { .api }
90
def get_donchian(quotes: Iterable[Quote], lookback_periods: int = 20):
91
"""
92
Donchian Channels - price channels using highest high and lowest low.
93
94
Args:
95
quotes (Iterable[Quote]): Historical price quotes
96
lookback_periods (int): Number of periods for high/low calculation (defaults to 20)
97
98
Returns:
99
DonchianResults[DonchianResult]: Collection of Donchian Channel results
100
"""
101
```
102
103
**DonchianResult Properties:**
104
- `date` (datetime): Result date
105
- `upper_band` (Optional[Decimal]): Upper channel (highest high)
106
- `center_line` (Optional[Decimal]): Middle line (average of upper and lower)
107
- `lower_band` (Optional[Decimal]): Lower channel (lowest low)
108
- `width` (Optional[float]): Channel width as percentage
109
110
### Standard Deviation
111
112
Measures the volatility of price data using statistical standard deviation.
113
114
```python { .api }
115
def get_stdev(quotes: Iterable[Quote], lookback_periods: int):
116
"""
117
Standard Deviation - statistical measure of price volatility.
118
119
Args:
120
quotes (Iterable[Quote]): Historical price quotes
121
lookbook_periods (int): Number of periods for calculation
122
123
Returns:
124
StdevResults[StdevResult]: Collection of Standard Deviation results
125
"""
126
```
127
128
**StdevResult Properties:**
129
- `date` (datetime): Result date
130
- `stdev` (Optional[Decimal]): Standard deviation value
131
- `mean` (Optional[Decimal]): Mean price over period
132
- `z_score` (Optional[float]): Z-score of current price
133
134
### STARC Bands
135
136
Stoller Average Range Channels using ATR-based volatility bands around a simple moving average.
137
138
```python { .api }
139
def get_starc_bands(quotes: Iterable[Quote], sma_periods: int = 20, multiplier: float = 2.0, atr_periods: int = 10):
140
"""
141
STARC Bands - Stoller Average Range Channels using SMA and ATR.
142
143
Args:
144
quotes (Iterable[Quote]): Historical price quotes
145
sma_periods (int): SMA periods for center line (defaults to 20)
146
multiplier (float): ATR multiplier for band width (defaults to 2.0)
147
atr_periods (int): ATR calculation periods (defaults to 10)
148
149
Returns:
150
StarcBandsResults[StarcBandsResult]: Collection of STARC Bands results
151
"""
152
```
153
154
**StarcBandsResult Properties:**
155
- `date` (datetime): Result date
156
- `upper_band` (Optional[Decimal]): Upper STARC band
157
- `center_line` (Optional[Decimal]): SMA center line
158
- `lower_band` (Optional[Decimal]): Lower STARC band
159
160
### Moving Average Envelopes
161
162
Percentage-based bands around a moving average for volatility analysis.
163
164
```python { .api }
165
def get_ma_envelopes(quotes: Iterable[Quote], lookback_periods: int = 20, percent_offset: float = 2.5, ma_type: MAType = MAType.SMA):
166
"""
167
Moving Average Envelopes - percentage-based bands around moving average.
168
169
Args:
170
quotes (Iterable[Quote]): Historical price quotes
171
lookback_periods (int): Number of periods for moving average (defaults to 20)
172
percent_offset (float): Percentage offset for bands (defaults to 2.5)
173
ma_type (MAType): Type of moving average (defaults to SMA)
174
175
Returns:
176
MAEnvelopesResults[MAEnvelopesResult]: Collection of MA Envelopes results
177
"""
178
```
179
180
**MAEnvelopesResult Properties:**
181
- `date` (datetime): Result date
182
- `upper_envelope` (Optional[Decimal]): Upper envelope
183
- `center_line` (Optional[Decimal]): Moving average center line
184
- `lower_envelope` (Optional[Decimal]): Lower envelope
185
186
### Choppiness Index
187
188
Measures market choppiness to determine if markets are trending or ranging.
189
190
```python { .api }
191
def get_chop(quotes: Iterable[Quote], lookback_periods: int = 14):
192
"""
193
Choppiness Index - measures whether market is trending or ranging.
194
195
Args:
196
quotes (Iterable[Quote]): Historical price quotes
197
lookback_periods (int): Number of periods for calculation (defaults to 14)
198
199
Returns:
200
ChopResults[ChopResult]: Collection of Choppiness Index results
201
"""
202
```
203
204
**ChopResult Properties:**
205
- `date` (datetime): Result date
206
- `chop` (Optional[Decimal]): Choppiness Index value (0-100)
207
208
### Ulcer Index
209
210
Volatility measure that focuses on downside risk and drawdown magnitude.
211
212
```python { .api }
213
def get_ulcer_index(quotes: Iterable[Quote], lookback_periods: int = 14):
214
"""
215
Ulcer Index - volatility measure focused on downside risk.
216
217
Args:
218
quotes (Iterable[Quote]): Historical price quotes
219
lookback_periods (int): Number of periods for calculation (defaults to 14)
220
221
Returns:
222
UlcerIndexResults[UlcerIndexResult]: Collection of Ulcer Index results
223
"""
224
```
225
226
**UlcerIndexResult Properties:**
227
- `date` (datetime): Result date
228
- `ui` (Optional[Decimal]): Ulcer Index value
229
230
## Usage Examples
231
232
### Bollinger Bands Analysis
233
234
```python
235
from stock_indicators.indicators import get_bollinger_bands
236
237
# Calculate Bollinger Bands
238
bb_results = get_bollinger_bands(quotes, lookback_periods=20, standard_deviations=2)
239
240
# Identify squeeze and expansion conditions
241
for result in bb_results:
242
if result.width is not None:
243
if result.width < 0.1: # Tight bands indicate low volatility
244
print(f"{result.date}: Bollinger Band squeeze - Width: {result.width:.3f}")
245
elif result.width > 0.4: # Wide bands indicate high volatility
246
print(f"{result.date}: Bollinger Band expansion - Width: {result.width:.3f}")
247
```
248
249
### ATR-Based Position Sizing
250
251
```python
252
from stock_indicators.indicators import get_atr
253
254
# Calculate ATR for position sizing
255
atr_results = get_atr(quotes, lookback_periods=14)
256
257
# Use ATR for stop-loss and position sizing
258
current_atr = atr_results[-1].atr
259
current_price = quotes[-1].close
260
261
if current_atr:
262
stop_loss_distance = current_atr * 2 # 2x ATR stop loss
263
position_risk = 0.02 # 2% account risk
264
265
print(f"Current ATR: {current_atr}")
266
print(f"Suggested stop loss: {current_price - stop_loss_distance}")
267
print(f"Position size factor: {position_risk / (stop_loss_distance / current_price)}")
268
```