pandas-ta-classic

repository·main·Indexed 18 days ago

https://github.com/xgboosted/pandas-ta-classic

A community-maintained technical analysis library that extends Pandas DataFrames with over 280 indicators and candlestick patterns. It provides native Python implementations that do not require TA-Lib, while offering optional acceleration via Numba or TA-Lib for core indicators. The library features a .ta accessor for easy DataFrame integration, automatic column mapping for OHLCVA data, and support for fluent chaining.

Tokens
28.4K
Snippets
89
Records
114
Agent score
62%

What's inside pandas-ta-classic

  1. Overview of Pandas TA Classic features

    main

    Pandas TA Classic is a community-maintained technical analysis library that integrates with Pandas.

    Key capabilities include:

    • 224 indicators and utility functions.
    • 62 native candlestick patterns (e.g., cdl_doji, cdl_inside) implemented without requiring TA-Lib.
    • Dynamic configuration management: Indicators are automatically detected via category discovery, and version management is handled via CI/CD to ensure metadata stays in sync with capabilities.
  2. What is a Strategy in Pandas TA Classic

    main

    A Strategy is a named group of technical analysis (TA) indicators that can be executed as a single batch using the df.ta.strategy() method. Instead of calling indicators one by one, you define a ta.Strategy object (a Data Class) that contains a list of indicators and their specific parameters. This allows for reproducible and organized technical analysis workflows.

    # Example of the concept: grouping indicators
    CustomStrategy = ta.Strategy(
        name="Momo and Volatility",
        ta=[
            {"kind": "rsi"},
            {"kind": "sma", "length": 50}
        ]
    )
    df.ta.strategy(CustomStrategy)
  3. What is tulipy and when to use it?

    main

    The tulipy library is an oracle-only dependency. It is never used as a computation backend for indicator calculations at runtime.

    Its sole purpose is to provide reference values for the test_oracle_tulipy.py test suite, which verifies that the native Pandas TA Classic implementations match tulipy's output. Installing tulipy has no effect on indicator performance or behavior in your production code.

  4. Understand the role of TA-Lib and tulipy in Pandas TA Classic

    main

    Pandas TA Classic uses native Python implementations by default, but supports optional libraries for acceleration and validation:

    • TA-Lib: Acts as both an acceleration backend and a live oracle. When installed, you can opt-in to use its C-library implementations for core indicators by setting talib=True. It is not used for candlestick (CDL) patterns; those remain native Python.
    • tulipy: Used only as a frozen oracle. It is not a computation backend. It is primarily used to generate a 'golden snapshot' of output for testing purposes. You do not need tulipy for normal usage.
    AreaBehaviour without TA-LibBehaviour with TA-Lib
    CDL patterns (62)Native Python — always usedStill native — TA-Lib never used for patterns
    Core indicators (59)Native Python (default)TA-Lib available via talib=True
  5. How renaming columns affects multiprocessing

    main

    When defining a strategy, if you use the col_names parameter within an indicator definition to rename the resulting columns, Pandas TA Classic will switch from multiprocessing to sequential execution. This is necessary to maintain the order of the indicators in the ta array when column renaming is involved.

    If you require multiprocessing, ensure your strategy definitions do not use col_names.

    # This strategy will NOT use multiprocessing because of 'col_names'
    NonMPStrategy = ta.Strategy(
        name="EMAs, BBs, and MACD",
        ta=[
            {"kind": "ema", "length": 8},
            {"kind": "ema", "length": 21},
            {"kind": "bbands", "length": 20, "col_names": ("BBL", "BBM", "BBU")},
            {"kind": "macd", "fast": 8, "slow": 21, "col_names": ("MACD", "MACD_H", "MACD_S")}
        ]
    )
    
    df.ta.strategy(NonMPStrategy)
  6. How pandas-ta-classic handles performance and TA-Lib

    main

    Pandas TA Classic is designed to be high-performance without requiring TA-Lib for standard operations, but it supports it as an optional acceleration layer.

    • Native Implementation: All 224 indicators and 62 candlestick patterns use native Python/Pandas implementations. No TA-Lib is required for basic usage.
    • Numba Acceleration: For specific 'hot-loop' indicators (like QQE, RSX, Supertrend, etc.), you can achieve 6–230× speedups by installing the performance extra: pip install pandas-ta-classic[performance].
    • TA-Lib Acceleration: While native implementations are the default, you can pass talib=True to specific indicator calls to use TA-Lib's C implementation if it is installed on your system.
  7. How to integrate pandas-ta-classic with backtrader

    main

    Because pandas-ta-classic is vectorized (operates on full Series) and backtrader is event-driven (processes bar-by-bar), they integrate using a precompute-then-feed pattern.

    Instead of calculating indicators inside the backtrader strategy loop, you should:

    1. Precompute indicators over the entire DataFrame using pandas-ta-classic functions.
    2. Store the results as new columns in your DataFrame.
    3. Declare these columns as lines in a custom bt.feeds.PandasData subclass.
    4. Access them within your strategy using self.data.<column_name>.

    This approach avoids the overhead of per-bar incremental updates and keeps the integration clean.

    import pandas as pd
    import pandas_ta_classic as ta
    import backtrader as bt
    
    # Step 1 — precompute
    df['sma_fast'] = ta.sma(df['Close'], length=10)
    df['sma_slow'] = ta.sma(df['Close'], length=20)
    df = df.dropna()
    
    # Step 2 — declare extra lines
    class PandasDataWithTA(bt.feeds.PandasData):
        lines = ('sma_fast', 'sma_slow',)
        params = (('sma_fast', -1), ('sma_slow', -1),)
        # param value -1 tells backtrader to auto-detect the column by line name
    
    # Step 3 — feed to cerebro
    data = PandasDataWithTA(dataname=df)
  8. How indicator output formats work

    main

    Indicators in Pandas TA Classic return different types of objects depending on the indicator type:

    1. Single Column Output: Returns a pandas.Series. Example: sma = df.ta.sma(length=20)

    2. Multiple Column Output: Returns a pandas.DataFrame containing all components of the indicator. Example: bbands = df.ta.bbands(length=20) returns columns like ['BBL_20_2.0', 'BBM_20_2.0', 'BBU_20_2.0'].

    Customizing Column Names

    You can use prefix, suffix, or col_names to control the resulting column names:

    # Using a suffix
    df.ta.sma(length=20, suffix="Daily", append=True) # Column: SMA_20_Daily
    
    # Using specific column names for multi-column indicators
    df.ta.chain().bbands(20, col_names=("LOWER", "MID", "UPPER", "BW", "PCT"))
    import pandas as pd
    import pandas_ta_classic as ta
    
    # Single column (Series)
    sma = df.ta.sma(length=20)
    
    # Multiple columns (DataFrame)
    bbands = df.ta.bbands(length=20)
    
    # Customizing names
    df.ta.sma(length=20, suffix="Daily", append=True)
    df.ta.chain().bbands(20, col_names=("LOWER", "MID", "UPPER", "BW", "PCT"))
  9. Three ways to use Pandas TA Classic

    main

    Pandas TA Classic provides three levels of abstraction for processing technical indicators:

    1. Standard Usage: You explicitly pass input columns (e.g., df['Close']) to the library functions. This gives you full control over inputs and outputs. Note that column names are case-sensitive.
    2. DataFrame Extension: Using the .ta accessor on a DataFrame. This automatically handles column mapping (lowercasing OHLCVA to ohlcva) and allows for easier chaining and direct appending to the DataFrame.
    3. Pandas TA Classic Strategy: The highest level of abstraction (details not covered in this specific API reference).
    import pandas_ta_classic as ta
    
    # Standard Usage
    sma10 = ta.sma(df["Close"], length=10)
    
    # DataFrame Extension
    sma10 = df.ta.sma(length=10)
  10. How to use Performance Metrics

    main

    Performance Metrics in pandas-ta-classic return a float and are called using the standard functional way rather than through the DataFrame Extension.

    Requirement: The input DataFrame must have a DatetimeIndex for time-based metrics such as cagr to function correctly.

    import pandas_ta_classic as ta
    result = ta.cagr(df.close)
  11. How indicator acceleration and oracles work

    main

    Pandas TA Classic is designed to be highly flexible regarding backend dependencies:

    • Native Implementation: All 284 indicators and patterns (including 62 candlestick patterns) are natively implemented and do not require TA-Lib.
    • TA-Lib Acceleration: If TA-Lib is installed on your system, core indicators will automatically use it for acceleration. To prevent this and force native implementation, pass talib=False to the indicator method.
    • Optional Oracles: The library can optionally use TA-Lib (as an acceleration backend + oracle) or tulipy (as an oracle only). These libraries are optional; the library will skip them gracefully if they are not installed.
  12. How TA-Lib works in Pandas TA Classic

    main

    TA-Lib serves two roles: an acceleration backend and a parity oracle. It is fully optional.

    1. Acceleration Backend

    By default, core indicators (e.g., ema, sma, rsi) use native Python implementations. If TA-Lib is installed, you can opt-in to use its C-based implementation for potentially better performance by passing talib=True to the indicator method.

    2. Candlestick Patterns (CDL family)

    TA-Lib is never used for CDL patterns. All 62 CDL patterns use native Python implementations. The talib=True argument has no effect on these calls.

    Installation

    For versions 0.6.5+, binary wheels are available for Linux, macOS, and Windows (x86_64, arm64). It is recommended to install ta-lib>=0.6.8 to ensure out-of-the-box compatibility.

    uv pip install "ta-lib>=0.6.8"
    # or
    pip install "ta-lib>=0.6.8"
    import pandas_ta_classic as ta
    
    # Uses native EMA — default behaviour
    ema = df.ta.ema(length=20)
    
    # Use TA-Lib implementation if installed
    ema = df.ta.ema(length=20, talib=True)
    
    # CDL patterns — always native, talib= kwarg has no effect here
    df = df.ta.cdl_pattern(name="engulfing")       # native
    result = df.ta.cdl_pattern(name="hammer")      # native