### Install technical library Source: https://github.com/freqtrade/technical/blob/main/docs/index.md Install the technical library using pip. For the latest version, install directly from GitHub. ```bash pip install technical ``` ```bash pip install git+https://github.com/freqtrade/technical ``` -------------------------------- ### Install TA-Lib Source: https://github.com/freqtrade/technical/blob/main/_autodocs/quick-start.md Troubleshoot TA-Lib import errors. Recommended installation methods include using conda, installing from a binary wheel, or compiling from source. ```bash # If TA-Lib installation fails on your system: # Option 1: Use conda (often more reliable) conda install -c conda-forge ta-lib # Option 2: Install from binary wheel (Windows/macOS) pip install TA-Lib # Option 3: Or install from source pip install TA-Lib --no-binary TA-Lib ``` -------------------------------- ### Install Latest Development Version from GitHub Source: https://github.com/freqtrade/technical/blob/main/_autodocs/configuration.md Install the most recent development version directly from the GitHub repository. ```bash pip install git+https://github.com/freqtrade/technical ``` -------------------------------- ### Install Technical Library from PyPI Source: https://github.com/freqtrade/technical/blob/main/_autodocs/configuration.md Use this command to install the latest stable version of the technical library from the Python Package Index. ```bash pip install technical ``` -------------------------------- ### Example Usage of QTPyLib Indicators Source: https://github.com/freqtrade/technical/blob/main/_autodocs/api-reference/qtpylib-indicators.md Shows how to import and use various QTPyLib indicators to calculate RSI, EMA, Bollinger Bands, and detect crossovers for generating trading signals. ```python from technical.qtpylib import rsi, ema, bollinger_bands, crossed_above # Calculate multiple indicators df['rsi'] = rsi(df['close'], 14) df['ema_9'] = ema(df['close'], 9) df['ema_21'] = ema(df['close'], 21) bands = bollinger_bands(df['close'], 20, 2) df['bb_upper'] = bands['upper'] df['bb_lower'] = bands['lower'] # Detect crossovers df['ema_crossover'] = crossed_above(df['ema_9'], df['ema_21']) # Mean reversion signal df['buy'] = crossed_above(df['close'], df['bb_lower']) ``` -------------------------------- ### Install Technical Library with Test Dependencies Source: https://github.com/freqtrade/technical/blob/main/_autodocs/configuration.md Install the technical library along with dependencies required for development and testing, including pytest and related plugins. ```bash pip install technical[tests] ``` -------------------------------- ### Import and Resample Dataframe Source: https://github.com/freqtrade/technical/blob/main/docs/index.md Import necessary functions and resample a dataframe to a different interval. This example shows resampling to a 4-hour interval and merging it back with the original dataframe. ```python from technical.indicators import accumulation_distribution, ... from technical.util import resample_to_interval, resampled_merge # Assuming 1h dataframe -resampling to 4h: dataframe_long = resample_to_interval(dataframe, 240) # 240 = 4 * 60 = 4h dataframe_long['rsi'] = ta.RSI(dataframe_long) # Combine the 2 dataframes dataframe = resampled_merge(dataframe, dataframe_long, fill_na=True) """ The resulting dataframe will have 5 resampled columns in addition to the regular columns, following the template resample__. So in the above example: ['resample_240_open', 'resample_240_high', 'resample_240_low','resample_240_close', 'resample_240_rsi'] """ ``` -------------------------------- ### Generate Trading Signals Source: https://github.com/freqtrade/technical/blob/main/_autodocs/quick-start.md Create trading signals based on indicator values. Examples include trend-following, mean reversion, and momentum strategies. ```python # Simple trend-following signal df['buy_signal'] = (df['close'] > df['sma_20']) & (df['close'].shift(1) <= df['sma_20'].shift(1)) df['sell_signal'] = (df['close'] < df['sma_20']) & (df['close'].shift(1) >= df['sma_20'].shift(1)) # Mean reversion signal df['buy_revert'] = df['close'] <= df['bb_lower'] df['sell_revert'] = df['close'] >= df['bb_upper'] # Momentum signal df['buy_rsi'] = (df['rsi_14'] < 30) & (df['rsi_14'] > df['rsi_14'].shift(1)) df['sell_rsi'] = (df['rsi_14'] > 70) & (df['rsi_14'] < df['rsi_14'].shift(1)) ``` -------------------------------- ### TD Sequential Signal Generation Source: https://github.com/freqtrade/technical/blob/main/_autodocs/api-reference/more-custom-indicators.md Generates buy/sell setup signals based on TD Sequential count completion (-9 or 9). Also identifies bars approaching completion (absolute count >= 7). ```python # Count completion signals df['buy_setup'] = df['TD_count'] == 9 df['sell_setup'] = df['TD_count'] == -9 # Approaching completion df['approaching_completion'] = df['TD_count'].abs() >= 7 ``` -------------------------------- ### Import and Use Technical Indicators Source: https://github.com/freqtrade/technical/blob/main/README.md Import necessary functions from the technical library and apply indicators to a dataframe. This example shows resampling a dataframe and merging it back with the original. ```python from technical.indicators import accumulation_distribution, ... from technical.util import resample_to_interval, resampled_merge # Assuming 1h dataframe -resampling to 4h: dataframe_long = resample_to_interval(dataframe, 240) # 240 = 4 * 60 = 4h dataframe_long['rsi'] = ta.RSI(dataframe_long) # Combine the 2 dataframes dataframe = resampled_merge(dataframe, dataframe_long, fill_na=True) """ The resulting dataframe will have 5 resampled columns in addition to the regular columns, following the template resample__. So in the above example: ['resample_240_open', 'resample_240_high', 'resample_240_low','resample_240_close', 'resample_240_rsi'] """ ``` -------------------------------- ### Access Technical Library Version Source: https://github.com/freqtrade/technical/blob/main/_autodocs/configuration.md Import and print the `__version__` attribute to get the current version of the technical library. ```python from technical import __version__ print(__version__) # e.g., "1.6.0" ``` -------------------------------- ### Ichimoku System Signals Source: https://github.com/freqtrade/technical/blob/main/_autodocs/quick-start.md Calculates and applies Ichimoku Cloud components (Tenkan-sen, Kijun-sen, Senkou Spans) to a DataFrame. Identifies full bullish and bearish setups based on price position relative to the cloud and Tenkan/Kijun cross. ```python from technical.indicators import ichimoku ichi = ichimoku(df) df['tenkan'] = ichi['tenkan_sen'] df['kijun'] = ichi['kijun_sen'] df['senkou_a'] = ichi['senkou_span_a'] df['senkou_b'] = ichi['senkou_span_b'] # Full bullish setup df['buy'] = (df['close'] > df['senkou_a']) & \ (df['close'] > df['senkou_b']) & \ (df['tenkan'] > df['kijun']) # Full bearish setup df['sell'] = (df['close'] < df['senkou_a']) & \ (df['close'] < df['senkou_b']) & \ (df['tenkan'] < df['kijun']) ``` -------------------------------- ### Support/Resistance Trading with Pivots and Touches Source: https://github.com/freqtrade/technical/blob/main/_autodocs/quick-start.md Utilize this for trading support and resistance levels. It calculates pivot points and detects touches/bounces, generating buy/sell signals on bounces from support (S1) or resistance (R1) levels. ```python from technical.indicators import pivots_points from technical.candles import touches, bounce # Pivot levels pivots = pivots_points(df, timeperiod=30, levels=3) df['pivot'] = pivots['pivot'] df['r1'] = pivots['r1'] df['s1'] = pivots['s1'] # Detect touches and bounces df['touch_r1'] = touches(df, df['r1'].iloc[-1]) df['bounce_s1'] = bounce(df, df['s1'].iloc[-1]) # Buy on bounce from S1, Sell on bounce from R1 df['buy'] = (df['touch_s1'] != 0) & (df['bounce_s1'] == 1) df['sell'] = (df['touch_r1'] != 0) & (df['bounce_r1'] == -1) ``` -------------------------------- ### Import QTPyLib Indicators Source: https://github.com/freqtrade/technical/blob/main/_autodocs/configuration.md Import common indicators and helper functions that are compatible with QTPyLib. This is useful for strategies that leverage QTPyLib functionalities. ```python from technical.qtpylib import rsi, macd, ema, bollinger_bands, crossed_above ``` -------------------------------- ### Calculate VPCI and VPCII Source: https://github.com/freqtrade/technical/blob/main/_autodocs/api-reference/custom-indicators.md Demonstrates how to calculate VPCI and VPCII using the technical library. These indicators can be used to identify strong confirmation signals for price movements. ```python from technical.indicators import vpci, vpcii df['vpci'] = vpci(df, period_short=5, period_long=20) df['vpcii'] = vpcii(df, period_short=5, period_long=20) # Strong confirmation signals df['confirmed_up'] = (df['close'] > df['bb_upper']) & (df['vpci'] > 0.5) df['confirmed_down'] = (df['close'] < df['bb_lower']) & (df['vpci'] < -0.5) ``` -------------------------------- ### Import Candle Analysis Functions Source: https://github.com/freqtrade/technical/blob/main/_autodocs/configuration.md Import functions for analyzing candle patterns, including detecting touches, bounces, doji patterns, and processing Heikin-Ashi candles. An alternative import for touches and bounce is also shown. ```python from technical.candles import touches, bounce, doji, heikinashi from technical.bouncyhouse import touches, bounce # Alternative import ``` -------------------------------- ### Compute DataFrame Interval Source: https://github.com/freqtrade/technical/blob/main/_autodocs/api-reference/utilities.md Calculates the time interval of a DataFrame. Use `exchange_interval=True` to get the interval as a string (e.g., '1h') instead of minutes. Supported intervals are defined in `TICKER_INTERVAL_MINUTES`. ```python from technical.util import compute_interval # Get interval in minutes interval_mins = compute_interval(df) # Returns: 60 # Get interval as exchange string interval_str = compute_interval(df, exchange_interval=True) # Returns: '1h' ``` -------------------------------- ### Pandas DataFrame/Series Indicator Methods Source: https://github.com/freqtrade/technical/blob/main/_autodocs/api-reference/qtpylib-indicators.md Demonstrates the convenience of QTPyLib functions being available as direct methods on pandas DataFrame and Series objects. ```python df.sma(20) # Same as sma(df['close'], 20) df.ema(12) df.rsi(14) df.bollinger_bands(20) df.macd() df.crossed_above(50) # Assuming df contains price series ``` -------------------------------- ### Mean Reversion with Bollinger Bands and RSI Source: https://github.com/freqtrade/technical/blob/main/_autodocs/quick-start.md Implement this for mean reversion strategies. It calculates Bollinger Bands and RSI, generating buy/sell signals when the price touches the bands and the RSI is not in extreme oversold/overbought territory. ```python from technical.indicators import bollinger_bands, rsi # Bollinger Bands df = bollinger_bands(df, period=20, stdv=2) # RSI filter (don't trade oversold/overbought) df['rsi'] = rsi(df, 14) # Buy at lower band (if not extreme oversold) df['buy'] = (df['close'] <= df['bb_lower']) & (df['rsi'] > 20) # Sell at upper band (if not extreme overbought) df['sell'] = (df['close'] >= df['bb_upper']) & (df['rsi'] < 80) ``` -------------------------------- ### Calculate Pivot Points and Support/Resistance Levels Source: https://github.com/freqtrade/technical/blob/main/_autodocs/api-reference/more-custom-indicators.md Calculates standard pivot points and multiple levels of support and resistance using rolling averages of OHLC data. Useful for identifying potential price reversal or breakout points. ```python from technical.indicators import pivots_points pivots = pivots_points(df, timeperiod=30, levels=3) df = df.join(pivots) # Trade around pivot levels df['above_pivot'] = df['close'] > df['pivot'] df['near_r1'] = (df['close'] > df['r1'] * 0.99) & (df['close'] < df['r1'] * 1.01) df['near_s1'] = (df['close'] > df['s1'] * 0.99) & (df['close'] < df['s1'] * 1.01) ``` -------------------------------- ### Import All Indicators Source: https://github.com/freqtrade/technical/blob/main/_autodocs/configuration.md Import all available indicators from all submodules of the technical.indicators module. This is a convenient way to access a wide range of indicators at once. ```python from technical.indicators import * ``` -------------------------------- ### Dynamic Position Sizing with ATR Percent Source: https://github.com/freqtrade/technical/blob/main/_autodocs/api-reference/volatility-indicators.md Scales position size inversely to volatility using ATR Percent. This helps reduce trading size during high volatility periods. ```python from technical.indicators import atr_percent # Scale position size inversely to volatility df['atr_pct'] = atr_percent(df, period=14) df['position_size'] = 100 / df['atr_pct'] # Reduce size when volatile # Apply position limits df['position_size'] = df['position_size'].clip(lower=0.5, upper=2.0) ``` -------------------------------- ### Dynamic Trendline Following with segtrends Source: https://github.com/freqtrade/technical/blob/main/_autodocs/api-reference/trendlines.md Utilize `segtrends` for dynamic trendline following, adapting to changing market trends. Calculate trend strength by examining the slope of the trendlines. This approach allows for strategies that follow support during uptrends. ```python # Use segtrends to adapt to changing trends trends = segtrends(df, field="close", segments=5) # Calculate trend strength (slope) max_line = trends['Max Line'] slope = (max_line.iloc[-1] - max_line.iloc[-100]) / 100 # Follow support when uptrending df['follow_trend'] = (df['close'] > trends['Min Line']) & (slope > 0) ``` -------------------------------- ### Import Helper Functions Source: https://github.com/freqtrade/technical/blob/main/_autodocs/configuration.md Import helper functions for various technical analyses, such as detecting price movement direction or applying advanced smoothing techniques like Ehlers Super Smoother. ```python from technical.indicator_helpers import went_up, went_down, ehlers_super_smoother, fishers_inverse ``` -------------------------------- ### Run Ruff Checks and Formatting Source: https://github.com/freqtrade/technical/blob/main/_autodocs/configuration.md Execute Ruff commands to check code style and automatically format the code. These commands are part of the pre-commit quality checks. ```bash ruff check . ruff format . ``` -------------------------------- ### Multi-component Return (Dictionary) Source: https://github.com/freqtrade/technical/blob/main/_autodocs/types.md Certain indicators return results as a dictionary, providing named access to various calculated components. ```python ichi = ichimoku(df) # Returns: dict with keys: # 'tenkan_sen', 'kijun_sen', 'senkou_span_a', 'senkou_span_b', # 'leading_senkou_span_a', 'leading_senkou_span_b', # 'chikou_span', 'cloud_green', 'cloud_red' pivots = pivots_points(df) # Returns: DataFrame with columns ['pivot', 'r1', 's1', 'r2', 's2', ...] ``` -------------------------------- ### Run Code Formatters Source: https://github.com/freqtrade/technical/blob/main/README.md Before creating a Pull Request, ensure code quality by running ruff check and ruff format. ```bash ruff check . ruff format . ``` -------------------------------- ### returns Source: https://github.com/freqtrade/technical/blob/main/_autodocs/api-reference/qtpylib-indicators.md Calculates the percentage returns of a series over time. ```APIDOC ## returns ### Description Calculates the percentage returns of a series over time. ### Signature ```python def returns(series) -> Series ``` ``` -------------------------------- ### Volatility Breakout with ATR and Chopiness Source: https://github.com/freqtrade/technical/blob/main/_autodocs/quick-start.md Use this for volatility breakout strategies. It calculates Average True Range (ATR) bands and Chopiness index, generating buy/sell signals only in trending markets. ```python from technical.indicators import atr, atr_percent, chopiness # ATR bands df['atr'] = atr(df, 14) df['upper_band'] = df['close'] + (df['atr'] * 2) df['lower_band'] = df['close'] - (df['atr'] * 2) # Only trade breakouts in trending markets (not choppy) df['chop'] = chopiness(df, 14) df['is_trending'] = (df['chop'] < 40) | (df['chop'] > 60) # Buy on breakout above upper band (in trending market) df['buy'] = (df['close'] > df['upper_band']) & df['is_trending'] # Sell on breakdown below lower band (in trending market) df['sell'] = (df['close'] < df['lower_band']) & df['is_trending'] ``` -------------------------------- ### Trend Following with EMAs Source: https://github.com/freqtrade/technical/blob/main/_autodocs/quick-start.md Use this recipe for trend following strategies. It calculates Exponential Moving Averages (EMAs) and generates buy/sell signals based on price crossing the short-term EMA and the alignment of all EMAs. ```python from technical.indicators import sma, ema from technical.qtpylib import crossed_above, crossed_below # EMA ribbon df['ema_8'] = ema(df, 8) df['ema_21'] = ema(df, 21) df['ema_55'] = ema(df, 55) # Buy when price crosses above short-term EMA, all EMAs aligned df['buy'] = crossed_above(df['close'], df['ema_8']) & \ (df['ema_8'] > df['ema_21']) & \ (df['ema_21'] > df['ema_55']) df['sell'] = crossed_below(df['close'], df['ema_8']) & \ (df['ema_8'] < df['ema_21']) & \ (df['ema_21'] < df['ema_55']) ``` -------------------------------- ### Import and Use Indicators Source: https://github.com/freqtrade/technical/blob/main/docs/general-usage.md Import the technical indicators library using the recommended alias 'ftt' to avoid naming conflicts. Then, apply indicators directly to your pandas DataFrame. ```python import technical.indicators as ftt # The indicator calculations can now be used as follows: dataframe['cmf'] = ftt.chaikin_money_flow(dataframe) ``` -------------------------------- ### Pandas DataFrame/Series Integration Source: https://github.com/freqtrade/technical/blob/main/_autodocs/api-reference/qtpylib-indicators.md QTPyLib functions are conveniently attached as methods to pandas DataFrame and Series objects, allowing for direct application of indicators. ```APIDOC ## Pandas Integration ### Description All QTPyLib functions are also attached as methods to pandas DataFrame/Series objects for convenience. ### Example Usage ```python df.sma(20) # Equivalent to sma(df['close'], 20) df.ema(12) df.rsi(14) df.bollinger_bands(20) df.macd() df.crossed_above(50) # Assuming df contains price series ``` ``` -------------------------------- ### Multi-component Return (DataFrame) Source: https://github.com/freqtrade/technical/blob/main/_autodocs/types.md Some indicators return multiple related values as a pandas DataFrame with specific column names. ```python bands = bollinger_bands(df, period=20) # Returns: DataFrame with columns ['upper', 'mid', 'lower'] macd_data = macd(df['close'], fast=12, slow=26) # Returns: DataFrame with columns ['macd', 'signal', 'histogram'] ``` -------------------------------- ### Import Specific Indicator Modules Source: https://github.com/freqtrade/technical/blob/main/_autodocs/configuration.md Import specific indicator functions from different submodules like overlap_studies, indicators, and volatility. This approach is more organized and avoids namespace pollution. ```python from technical.indicators.overlap_studies import sma, ema, bollinger_bands from technical.indicators.indicators import ichimoku, mmar, vfi from technical.indicators.volatility import atr, atr_percent, chopiness ``` -------------------------------- ### Madrid Trend Squeeze Indicator Implementation Source: https://github.com/freqtrade/technical/blob/main/_autodocs/api-reference/custom-indicators.md This snippet demonstrates how to use the `madrid_sqz` indicator to calculate and assign squeeze momentum colors to a DataFrame. It also shows how to derive bullish and bearish squeeze breakout signals based on the indicator's output colors. ```python from technical.indicators import madrid_sqz sqz_cma, sqz_rma, sqz_sma = madrid_sqz(df, length=34) df['sqz_cma_color'] = sqz_cma df['sqz_rma_color'] = sqz_rma df['sqz_sma_color'] = sqz_sma # Squeeze breakout signal (alignment) df['squeeze_bullish'] = (df['sqz_cma_color'] == 'aqua') & \ (df['sqz_sma_color'] == 'lime') & \ (df['sqz_rma_color'] == 'green') df['squeeze_bearish'] = (df['sqz_cma_color'] == 'fuchsia') & \ (df['sqz_sma_color'] == 'red') & \ (df['sqz_rma_color'] == 'maroon') ``` -------------------------------- ### Import Utility Functions Source: https://github.com/freqtrade/technical/blob/main/_autodocs/configuration.md Import utility functions for data manipulation, such as resampling time series data to a specific interval or merging resampled data. ```python from technical.util import resample_to_interval, resampled_merge, compute_interval ``` -------------------------------- ### Calculate Bollinger Bands with EMA and Identify Squeezes Source: https://github.com/freqtrade/technical/blob/main/_autodocs/api-reference/overlap-studies.md Calculates Bollinger Bands using an Exponential Moving Average (EMA) for faster response and identifies potential 'squeezes' where the band width narrows significantly. ```python from technical.indicators import bollinger_bands # Using EMA for faster response df = bollinger_bands(df, period=20, stdv=2, ma_type="ema", colum_prefix="bb_ema") # Identify squeezes df['squeeze'] = (df['bb_upper'] - df['bb_lower']) < (df['bb_upper'].rolling(20).mean() - df['bb_lower'].rolling(20).mean()) * 0.5 ``` -------------------------------- ### Calculate Percentage Returns Source: https://github.com/freqtrade/technical/blob/main/_autodocs/api-reference/qtpylib-indicators.md Calculates the percentage returns of a series, useful for analyzing price changes over time. ```python def returns(series) -> Series ``` -------------------------------- ### Volatility Regime Identification using ATR Percent and Choppiness Source: https://github.com/freqtrade/technical/blob/main/_autodocs/api-reference/volatility-indicators.md Identifies market regimes (trending, choppy, neutral) using a combination of ATR Percent and Choppiness Index. This allows for applying different strategies based on the identified regime. ```python from technical.indicators import atr_percent, chopiness # Multi-indicator regime identification df['atr_pct'] = atr_percent(df, period=14) df['chop'] = chopiness(df, period=14) # Define regimes df['regime'] = 'neutral' df.loc[df['chop'] < 40, 'regime'] = 'trending' df.loc[(df['chop'] >= 40) & (df['chop'] <= 60), 'regime'] = 'choppy' df.loc[df['chop'] > 60, 'regime'] = 'trending' # Apply different strategies per regime df.loc[df['regime'] == 'trending', 'strategy'] = 'trend_follow' df.loc[df['regime'] == 'choppy', 'strategy'] = 'mean_reversion' ``` -------------------------------- ### Optimizing Imports for Performance Source: https://github.com/freqtrade/technical/blob/main/_autodocs/configuration.md For better performance, use specific imports for indicators instead of importing all symbols with '*'. This reduces overhead when dealing with large datasets. ```python # Use specific imports instead of * from technical.indicators import sma, ema # Faster than import * ``` -------------------------------- ### Import Trendline Functions Source: https://github.com/freqtrade/technical/blob/main/_autodocs/configuration.md Import functions for generating and segmenting trendlines. These are useful for identifying and analyzing price trends. ```python from technical.trendline import gentrends, segtrends ``` -------------------------------- ### Generate Mean Reversion Signals with Bollinger Bands Source: https://github.com/freqtrade/technical/blob/main/_autodocs/api-reference/overlap-studies.md Generates buy and sell signals based on price crossing the lower and upper Bollinger Bands, respectively. This is a common strategy for mean reversion trading. ```python from technical.indicators import bollinger_bands # Mean reversion signals df['buy_signal'] = df['close'] <= df['bb_lower'] df['sell_signal'] = df['close'] >= df['bb_upper'] ``` -------------------------------- ### Calculate Fibonacci Retracement Levels Source: https://github.com/freqtrade/technical/blob/main/_autodocs/api-reference/more-custom-indicators.md Scales price data between minimum and maximum to determine which Fibonacci retracement level it has exceeded. Use this to identify potential support or resistance zones based on Fibonacci ratios. ```python from technical.indicators import fibonacci_retracements df['fib_level'] = fibonacci_retracements(df, field="close") # Buy at 61.8% retracement df['buy_fib'] = df['fib_level'] == 0.618 # Identify breakout above 78.6% level df['breakout'] = df['fib_level'] > 0.786 ``` -------------------------------- ### Handling NaN Values in Indicators Source: https://github.com/freqtrade/technical/blob/main/_autodocs/types.md Illustrates how to handle NaN values that appear at the beginning of indicator series due to insufficient data periods. Shows forward filling and dropping NaN rows. ```python df['sma_20'] = sma(df, 20) # First 19 values are NaN (need 20 periods to calculate) df['rsi_14'] = rsi(df['close'], 14) # First 14 values are NaN # Forward fill to propagate values df['sma_20_filled'] = df['sma_20'].ffill() # Remove NaN rows df_clean = df.dropna(subset=['sma_20']) ``` -------------------------------- ### Zero-Lag Moving Averages (ZLMA, ZLEMA, ZLSMA, ZLHMA) Source: https://github.com/freqtrade/technical/blob/main/_autodocs/api-reference/qtpylib-indicators.md Calculates various types of Zero-Lag Moving Averages (ZLMA, ZLEMA, ZLSMA, ZLHMA). ```APIDOC ## Zero-Lag Moving Averages ### Description Calculates various types of Zero-Lag Moving Averages. ### Method Signatures ```python def zlma(series, window=20, min_periods=None, kind="ema") -> Series def zlema(series, window=20, min_periods=None) -> Series def zlsma(series, window=20, min_periods=None) -> Series def zlhma(series, window=20, min_periods=None) -> Series ``` ### Parameters - **series** (Series) - The input data series. - **window** (int, optional) - The window size for the moving average. Defaults to 20. - **min_periods** (int, optional) - Minimum number of observations in window required to have a value (otherwise result is NA). - **kind** (str, optional) - The kind of EMA to use for zlma. Defaults to "ema". ### Returns - Series: The calculated Zero-Lag Moving Average series. ``` -------------------------------- ### Volume Confirmation with VFI and VWMA Source: https://github.com/freqtrade/technical/blob/main/_autodocs/quick-start.md Employ this for strategies requiring volume confirmation. It uses the Volume Flow Indicator (VFI) and Volume Weighted Moving Average (VWMA) to generate buy/sell signals based on price position relative to VWMA and VFI trends. ```python from technical.indicators import vfi, vwma # Volume Flow Indicator vfi_val, vfima, vfi_hist = vfi(df, length=130) df['vfi'] = vfi_val df['vfima'] = vfima # Volume Weighted MA df['vwma_20'] = vwma(df, 20) # Buy when price above VWMA with bullish volume df['buy'] = (df['close'] > df['vwma_20']) & (df['vfi'] > df['vfima']) # Sell when price below VWMA with bearish volume df['sell'] = (df['close'] < df['vwma_20']) & (df['vfi'] < df['vfima']) ``` -------------------------------- ### typical_price Source: https://github.com/freqtrade/technical/blob/main/_autodocs/api-reference/qtpylib-indicators.md Calculates the typical price of a bar, which is the average of the high, low, and close prices. ```APIDOC ## typical_price ### Description Calculates the typical price of a bar, which is the average of the high, low, and close prices. ### Signature ```python def typical_price(bars) -> Series ``` ``` -------------------------------- ### Using Flexible Field Names for Indicators Source: https://github.com/freqtrade/technical/blob/main/_autodocs/configuration.md Many functions accept a 'field' parameter to specify alternative columns for calculations, allowing flexibility beyond the default 'close' column. ```python # Use 'close' (default) sma(df, 20) # Use alternative column sma(df, 20, field='hl2') # If df has 'hl2' column ``` -------------------------------- ### Convert Data to Different Timeframes Source: https://github.com/freqtrade/technical/blob/main/_autodocs/quick-start.md Resample your hourly data to daily ('1d') or weekly ('1w') intervals using the `resample_to_interval` utility function for analysis at different timeframes. ```python from technical.util import resample_to_interval # For analysis at different timeframes df_daily = resample_to_interval(df_hourly, '1d') df_weekly = resample_to_interval(df_hourly, '1w') ``` -------------------------------- ### Calculate Typical Price Source: https://github.com/freqtrade/technical/blob/main/_autodocs/api-reference/qtpylib-indicators.md Calculates the typical price of a bar, which is the average of the high, low, and close prices. ```python def typical_price(bars) -> Series ``` -------------------------------- ### Freqtrade Strategy Indicators Source: https://github.com/freqtrade/technical/blob/main/_autodocs/INDEX.md Integrate Ichimoku and VFI indicators into your Freqtrade strategy's populate_indicators method. Supports single and multi-timeframe analysis using resampling. ```python from technical.indicators import ichimoku, vfi from technical.util import resample_to_interval, resampled_merge # Single timeframe df = ichimoku(df) df['vfi'], df['vfima'], _ = vfi(df) # Multi-timeframe df_4h = resample_to_interval(df, '4h') df_4h['ema_50'] = ema(df_4h, 50) df = resampled_merge(df, df_4h) ``` -------------------------------- ### Zero-Lag Moving Average Functions Source: https://github.com/freqtrade/technical/blob/main/_autodocs/api-reference/qtpylib-indicators.md Includes various zero-lag moving average implementations: `zlma` (configurable kind), `zlema` (exponential), `zlsma` (simple), and `zlhma` (Hull). ```python def zlma(series, window=20, min_periods=None, kind="ema") -> Series def zlema(series, window=20, min_periods=None) -> Series def zlsma(series, window=20, min_periods=None) -> Series def zlhma(series, window=20, min_periods=None) -> Series ``` -------------------------------- ### Export Specific Columns to CSV Source: https://github.com/freqtrade/technical/blob/main/_autodocs/quick-start.md Select and export specific columns, such as date, close price, and buy/sell signals, to a CSV file for further analysis. ```python signals = df[['date', 'close', 'buy_signal', 'sell_signal']] signals.to_csv('signals.csv', index=False) ``` -------------------------------- ### pivots_points Source: https://github.com/freqtrade/technical/blob/main/_autodocs/api-reference/more-custom-indicators.md Calculates standard pivot points with support and resistance levels based on OHLC data. Returns a DataFrame containing pivot, support, and resistance levels. ```APIDOC ## pivots_points ### Description Standard pivot point calculations with support and resistance levels. ### Method `pivots_points( dataframe: DataFrame, timeperiod: int = 30, levels: int = 3 ) -> DataFrame` ### Parameters #### Path Parameters - **dataframe** (DataFrame) - Required - DataFrame with OHLC data - **timeperiod** (int) - Optional - Period for rolling averages (default: 30) - **levels** (int) - Optional - Number of support/resistance levels (1-5) (default: 3) ### Returns **DataFrame** — Columns named 'pivot', 's1', 'r1', 's2', 'r2', etc. ### Description Standard pivot points calculation using rolling averages: - Pivot = Average(typical price) = Average((H + L + C) / 3) - R1 = (2 × Pivot) - rolling_low - S1 = (2 × Pivot) - rolling_high - R2 = Pivot + (R1 - S1) - S2 = Pivot - (R1 - S1) - (Pattern continues for additional levels) ### Example ```python from technical.indicators import pivots_points pivots = pivots_points(df, timeperiod=30, levels=3) df = df.join(pivots) # Trade around pivot levels df['above_pivot'] = df['close'] > df['pivot'] df['near_r1'] = (df['close'] > df['r1'] * 0.99) & (df['close'] < df['r1'] * 1.01) df['near_s1'] = (df['close'] > df['s1'] * 0.99) & (df['close'] < df['s1'] * 1.01) ``` ``` -------------------------------- ### Standard OHLCV DataFrame Format Source: https://github.com/freqtrade/technical/blob/main/_autodocs/configuration.md Most functions expect DataFrames with specific columns: date, open, high, low, close, and volume. Ensure these columns are present with the correct data types. ```python { 'date': datetime, # Or DatetimeIndex 'open': float, 'high': float, 'low': float, 'close': float, 'volume': float or int, } ``` -------------------------------- ### Calculate Log Returns Source: https://github.com/freqtrade/technical/blob/main/_autodocs/api-reference/qtpylib-indicators.md Calculates the logarithmic returns of a series, often used in financial modeling for its additive properties. ```python def log_returns(series) -> Series ``` -------------------------------- ### log_returns Source: https://github.com/freqtrade/technical/blob/main/_autodocs/api-reference/qtpylib-indicators.md Calculates the logarithmic returns of a series, which is often used for its additive properties. ```APIDOC ## log_returns ### Description Calculates the logarithmic returns of a series, which is often used for its additive properties. ### Signature ```python def log_returns(series) -> Series ``` ``` -------------------------------- ### Generate Buy and Sell Signals with Laguerre RSI Source: https://github.com/freqtrade/technical/blob/main/_autodocs/api-reference/custom-indicators.md Generates buy and sell signals based on Laguerre RSI thresholds. Buy signals are triggered when the indicator crosses above the oversold threshold (0.3), and sell signals are triggered when it crosses below the overbought threshold (0.7). ```python # Oversold buy signal df['buy'] = (df['laguerre'] < 0.3) & (df['laguerre'].shift(1) >= 0.3) # Overbought sell signal df['sell'] = (df['laguerre'] > 0.7) & (df['laguerre'].shift(1) <= 0.7) ``` -------------------------------- ### Heikin Ashi Patterns Source: https://github.com/freqtrade/technical/blob/main/_autodocs/quick-start.md Generates Heikin Ashi candle data, including trend identification (uptrend/downtrend), reversal detection, and consolidation patterns based on candle body size. ```python from technical.candles import heikinashi ha = heikinashi(df) # Trend identification df['uptrend'] = ha['candle'] == 1 df['downtrend'] = ha['candle'] == -1 # Reversal detection df['reversal_bullish'] = ha['reversal'] == 1 df['reversal_bearish'] = ha['reversal'] == -1 # Consolidation (small bodies) df['consolidating'] = ha['small_body'] == 1 ``` -------------------------------- ### Volume Weighted MACD Calculation and Signal Generation Source: https://github.com/freqtrade/technical/blob/main/_autodocs/api-reference/more-custom-indicators.md Calculates the Volume Weighted MACD, its signal line, and histogram. Generates buy/sell signals based on MACD and signal line crossovers. Use for MACD analysis that emphasizes volume conviction. ```python from technical.indicators import vwmacd df = vwmacd(df, fastperiod=12, slowperiod=26, signalperiod=9) # Volume-confirmed MACD signal df['buy'] = (df['vwmacd'] > df['signal']) & (df['vwmacd'].shift(1) <= df['signal'].shift(1)) df['sell'] = (df['vwmacd'] < df['signal']) & (df['vwmacd'].shift(1) >= df['signal'].shift(1)) # Histogram for divergence detection df['bullish_diverg'] = (df['hist'] > df['hist'].shift(1)) & (df['close'] < df['close'].shift(1)) ``` -------------------------------- ### rolling_vwap Source: https://github.com/freqtrade/technical/blob/main/_autodocs/api-reference/qtpylib-indicators.md Calculates the Volume-Weighted Average Price (VWAP) using a rolling window. Note: Non-rolling VWAP is disabled to prevent lookahead bias. ```APIDOC ## rolling_vwap ### Description Calculates the Volume-Weighted Average Price (VWAP) using a rolling window. Note: Non-rolling VWAP is disabled to prevent lookahead bias. ### Parameters - `bars`: DataFrame containing price and volume data. - `window` (int): The lookback window for the rolling VWAP calculation. Defaults to 200. - `min_periods` (int, optional): Minimum number of periods required for a value to be calculated. ### Signature ```python def rolling_vwap(bars, window=200, min_periods=None) -> Series ``` ``` -------------------------------- ### Tuple Return (Multiple Series) Source: https://github.com/freqtrade/technical/blob/main/_autodocs/types.md Indicators that produce multiple distinct Series often return them as a tuple, requiring unpacking into separate variables. ```python vfi, vfima, vfi_hist = vfi(df) # Type: tuple[Series, Series, Series] st, stx = supertrend(df) # Type: tuple[ndarray, ndarray] leadMA, ma10_c, ma20_c, ... = mmar(df) # Type: tuple[Series, ...] (10 items) ``` -------------------------------- ### Calculate Price-Volume Trend (PVT) Source: https://github.com/freqtrade/technical/blob/main/_autodocs/api-reference/qtpylib-indicators.md Calculates the Price-Volume Trend (PVT) indicator, which relates price and volume changes. ```python def pvt(bars) -> Series ``` -------------------------------- ### VFI System Strategy Logic Source: https://github.com/freqtrade/technical/blob/main/_autodocs/INDEX.md This snippet outlines the VFI System strategy, which uses Volume Flow Indicator (VFI) for buy/sell signals with volume confirmation. It is suitable for swing and position trading and requires VFI, VWMA, and Volume indicators. ```text VFI System: - Buy when VFI > Signal with volume confirmation - Sell when VFI < Signal with bearish volume - Multi-timeframe alignment Best for: Swing/position trading Indicators: VFI, VWMA, Volume ``` -------------------------------- ### Calculate Rolling VWAP Source: https://github.com/freqtrade/technical/blob/main/_autodocs/api-reference/qtpylib-indicators.md Calculates the Volume-Weighted Average Price (VWAP) using a rolling window. Non-rolling VWAP is disabled to prevent lookahead bias. ```python def rolling_vwap(bars, window=200, min_periods=None) -> Series ``` -------------------------------- ### Load Data Source: https://github.com/freqtrade/technical/blob/main/_autodocs/quick-start.md Load historical price data into a pandas DataFrame. Supports loading from CSV files or ticker history lists. ```python import pandas as pd from technical.util import ticker_history_to_dataframe # Option A: From your own data df = pd.read_csv('your_data.csv') df['date'] = pd.to_datetime(df['date']) # Option B: From ticker history (list of lists) ticker_data = [ [timestamp_ms, open, high, low, close, volume], ... ] df = ticker_history_to_dataframe(ticker_data) ``` -------------------------------- ### Multi-timeframe Trendline Analysis Source: https://github.com/freqtrade/technical/blob/main/_autodocs/api-reference/trendlines.md Combine `gentrends` and `segtrends` to analyze trendlines across different timeframes. This allows for a more comprehensive view of support and resistance levels. The calculated trendlines from various timeframes can be merged into a main DataFrame, and signals can be generated when the price approaches these trendlines. ```python from technical.trendline import gentrends, segtrends # Calculate trendlines on multiple timeframes trends_1h = gentrends(df_1h, field="close") trends_4h = segtrends(df_4h, field="close", segments=3) # Merge into main dataframe df['trend_1h_support'] = trends_1h['Min Line'] df['trend_4h_resistance'] = trends_4h['Max Line'] # Signal when price approaches multiple trendlines df['near_support'] = (df['close'] < df['trend_1h_support'] * 1.01) & (df['close'] > df['trend_1h_support'] * 0.99) ``` -------------------------------- ### Calculate Stop Loss and Take Profit Levels with ATR Source: https://github.com/freqtrade/technical/blob/main/_autodocs/api-reference/volatility-indicators.md Calculates dynamic stop loss and take profit levels for both long and short positions based on the Average True Range (ATR). This helps in setting risk management parameters. ```python from technical.indicators import atr df['atr'] = atr(df, window=14) # For long positions df['long_entry'] = df['close'] df['long_stop'] = df['long_entry'] - (df['atr'] * 2.0) df['long_tp_1'] = df['long_entry'] + (df['atr'] * 1.5) df['long_tp_2'] = df['long_entry'] + (df['atr'] * 3.0) # For short positions df['short_entry'] = df['close'] df['short_stop'] = df['short_entry'] + (df['atr'] * 2.0) df['short_tp_1'] = df['short_entry'] - (df['atr'] * 1.5) df['short_tp_2'] = df['short_entry'] - (df['atr'] * 3.0) ``` -------------------------------- ### Calculate Awesome Oscillator Source: https://github.com/freqtrade/technical/blob/main/_autodocs/api-reference/qtpylib-indicators.md Calculates the Awesome Oscillator, an indicator based on the midprice, with configurable fast and slow periods. ```python def awesome_oscillator(df, weighted=False, fast=5, slow=34) -> Series ```