Stock Indicators for Python provides financial market technical indicators from historical price quotes.
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.
Volatility bands consisting of a middle moving average line with upper and lower bands based on standard deviations.
def get_bollinger_bands(quotes: Iterable[Quote], lookback_periods: int = 20, standard_deviations: float = 2):
"""
Bollinger Bands® - volatility bands using standard deviation boundaries from moving average.
Args:
quotes (Iterable[Quote]): Historical price quotes
lookback_periods (int): Number of periods for moving average (defaults to 20)
standard_deviations (float): Number of standard deviations for bands (defaults to 2)
Returns:
BollingerBandsResults[BollingerBandsResult]: Collection of Bollinger Bands results
"""BollingerBandsResult Properties:
date (datetime): Result datesma (Optional[Decimal]): Simple moving average (middle band)upper_band (Optional[Decimal]): Upper Bollinger Bandlower_band (Optional[Decimal]): Lower Bollinger Bandpercent_b (Optional[float]): %B position within bandsz_score (Optional[float]): Z-score relative to middle bandwidth (Optional[float]): Band width as percentageMeasures market volatility by calculating the average of true ranges over a specified period.
def get_atr(quotes: Iterable[Quote], lookback_periods: int = 14):
"""
Average True Range (ATR) - measures market volatility using true range.
Args:
quotes (Iterable[Quote]): Historical price quotes
lookback_periods (int): Number of periods for ATR calculation (defaults to 14)
Returns:
ATRResults[ATRResult]: Collection of ATR results
"""ATRResult Properties:
date (datetime): Result datetr (Optional[Decimal]): True Range valueatr (Optional[Decimal]): Average True Range valueatrp (Optional[float]): ATR as percentage of close priceVolatility-based channels using exponential moving average and Average True Range.
def get_keltner(quotes: Iterable[Quote], ema_periods: int = 20, multiplier: float = 2.0, atr_periods: int = 10):
"""
Keltner Channels - volatility channels using EMA and ATR.
Args:
quotes (Iterable[Quote]): Historical price quotes
ema_periods (int): EMA periods for center line (defaults to 20)
multiplier (float): ATR multiplier for channel width (defaults to 2.0)
atr_periods (int): ATR calculation periods (defaults to 10)
Returns:
KeltnerResults[KeltnerResult]: Collection of Keltner Channel results
"""KeltnerResult Properties:
date (datetime): Result dateupper_band (Optional[Decimal]): Upper Keltner Channelcenter_line (Optional[Decimal]): EMA center linelower_band (Optional[Decimal]): Lower Keltner Channelwidth (Optional[float]): Channel width as percentagePrice channels based on highest high and lowest low over a lookback period.
def get_donchian(quotes: Iterable[Quote], lookback_periods: int = 20):
"""
Donchian Channels - price channels using highest high and lowest low.
Args:
quotes (Iterable[Quote]): Historical price quotes
lookback_periods (int): Number of periods for high/low calculation (defaults to 20)
Returns:
DonchianResults[DonchianResult]: Collection of Donchian Channel results
"""DonchianResult Properties:
date (datetime): Result dateupper_band (Optional[Decimal]): Upper channel (highest high)center_line (Optional[Decimal]): Middle line (average of upper and lower)lower_band (Optional[Decimal]): Lower channel (lowest low)width (Optional[float]): Channel width as percentageMeasures the volatility of price data using statistical standard deviation.
def get_stdev(quotes: Iterable[Quote], lookback_periods: int):
"""
Standard Deviation - statistical measure of price volatility.
Args:
quotes (Iterable[Quote]): Historical price quotes
lookbook_periods (int): Number of periods for calculation
Returns:
StdevResults[StdevResult]: Collection of Standard Deviation results
"""StdevResult Properties:
date (datetime): Result datestdev (Optional[Decimal]): Standard deviation valuemean (Optional[Decimal]): Mean price over periodz_score (Optional[float]): Z-score of current priceStoller Average Range Channels using ATR-based volatility bands around a simple moving average.
def get_starc_bands(quotes: Iterable[Quote], sma_periods: int = 20, multiplier: float = 2.0, atr_periods: int = 10):
"""
STARC Bands - Stoller Average Range Channels using SMA and ATR.
Args:
quotes (Iterable[Quote]): Historical price quotes
sma_periods (int): SMA periods for center line (defaults to 20)
multiplier (float): ATR multiplier for band width (defaults to 2.0)
atr_periods (int): ATR calculation periods (defaults to 10)
Returns:
StarcBandsResults[StarcBandsResult]: Collection of STARC Bands results
"""StarcBandsResult Properties:
date (datetime): Result dateupper_band (Optional[Decimal]): Upper STARC bandcenter_line (Optional[Decimal]): SMA center linelower_band (Optional[Decimal]): Lower STARC bandPercentage-based bands around a moving average for volatility analysis.
def get_ma_envelopes(quotes: Iterable[Quote], lookback_periods: int = 20, percent_offset: float = 2.5, ma_type: MAType = MAType.SMA):
"""
Moving Average Envelopes - percentage-based bands around moving average.
Args:
quotes (Iterable[Quote]): Historical price quotes
lookback_periods (int): Number of periods for moving average (defaults to 20)
percent_offset (float): Percentage offset for bands (defaults to 2.5)
ma_type (MAType): Type of moving average (defaults to SMA)
Returns:
MAEnvelopesResults[MAEnvelopesResult]: Collection of MA Envelopes results
"""MAEnvelopesResult Properties:
date (datetime): Result dateupper_envelope (Optional[Decimal]): Upper envelopecenter_line (Optional[Decimal]): Moving average center linelower_envelope (Optional[Decimal]): Lower envelopeMeasures market choppiness to determine if markets are trending or ranging.
def get_chop(quotes: Iterable[Quote], lookback_periods: int = 14):
"""
Choppiness Index - measures whether market is trending or ranging.
Args:
quotes (Iterable[Quote]): Historical price quotes
lookback_periods (int): Number of periods for calculation (defaults to 14)
Returns:
ChopResults[ChopResult]: Collection of Choppiness Index results
"""ChopResult Properties:
date (datetime): Result datechop (Optional[Decimal]): Choppiness Index value (0-100)Volatility measure that focuses on downside risk and drawdown magnitude.
def get_ulcer_index(quotes: Iterable[Quote], lookback_periods: int = 14):
"""
Ulcer Index - volatility measure focused on downside risk.
Args:
quotes (Iterable[Quote]): Historical price quotes
lookback_periods (int): Number of periods for calculation (defaults to 14)
Returns:
UlcerIndexResults[UlcerIndexResult]: Collection of Ulcer Index results
"""UlcerIndexResult Properties:
date (datetime): Result dateui (Optional[Decimal]): Ulcer Index valuefrom stock_indicators.indicators import get_bollinger_bands
# Calculate Bollinger Bands
bb_results = get_bollinger_bands(quotes, lookback_periods=20, standard_deviations=2)
# Identify squeeze and expansion conditions
for result in bb_results:
if result.width is not None:
if result.width < 0.1: # Tight bands indicate low volatility
print(f"{result.date}: Bollinger Band squeeze - Width: {result.width:.3f}")
elif result.width > 0.4: # Wide bands indicate high volatility
print(f"{result.date}: Bollinger Band expansion - Width: {result.width:.3f}")from stock_indicators.indicators import get_atr
# Calculate ATR for position sizing
atr_results = get_atr(quotes, lookback_periods=14)
# Use ATR for stop-loss and position sizing
current_atr = atr_results[-1].atr
current_price = quotes[-1].close
if current_atr:
stop_loss_distance = current_atr * 2 # 2x ATR stop loss
position_risk = 0.02 # 2% account risk
print(f"Current ATR: {current_atr}")
print(f"Suggested stop loss: {current_price - stop_loss_distance}")
print(f"Position size factor: {position_risk / (stop_loss_distance / current_price)}")Install with Tessl CLI
npx tessl i tessl/pypi-stock-indicators