### Development Installation Source: https://github.com/xgboosted/pandas-ta-classic/blob/main/README.md Clone the repository and install with specific dependency groups for development or optional features. ```bash # Clone the repository git clone https://github.com/xgboosted/pandas-ta-classic.git cd pandas-ta-classic # Install with all dependencies uv pip install -e ".[all]" # Or install specific dependency groups: uv pip install -e ".[dev]" # Development tools uv pip install -e ".[optional]" # Optional runtime features uv pip install -e ".[oracle]" # Oracle parity libs: TA-Lib + tulipy ``` ```bash # Clone the repository git clone https://github.com/xgboosted/pandas-ta-classic.git cd pandas-ta-classic # Install with all dependencies pip install -e ".[all]" # Or install specific dependency groups: pip install -e ".[dev]" # Development tools pip install -e ".[optional]" # Optional runtime features pip install -e ".[oracle]" # Oracle parity libs: TA-Lib + tulipy ``` -------------------------------- ### Verify installation Source: https://github.com/xgboosted/pandas-ta-classic/blob/main/docs/installation.md Run this script to confirm that the library is installed correctly and indicators are accessible. ```python import pandas_ta_classic as ta import pandas as pd # Create a simple DataFrame df = pd.DataFrame({'close': [100, 101, 102, 101, 100]}) # Test an indicator sma = df.ta.sma(length=3) print(sma) # List all available indicators print(f"Available indicators: {len(df.ta.indicators())}") ``` -------------------------------- ### Install Required Packages Source: https://github.com/xgboosted/pandas-ta-classic/blob/main/examples/AIExample.ipynb Uncomment and run these commands to install the necessary dependencies for the project. ```python #!pip install numpy #!pip install pandas #!pip install mplfinance #!pip install pandas-datareader #!pip install requests_cache #!pip install tqdm #!pip install alphaVantage-api # Required for Watchlist ``` -------------------------------- ### Development Installation (uv) Source: https://github.com/xgboosted/pandas-ta-classic/blob/main/docs/installation.md Clone the repository and install in editable mode with specific dependency groups using uv. ```bash # Clone the repository git clone https://github.com/xgboosted/pandas-ta-classic.git cd pandas-ta-classic # Install in editable mode with all dependencies uv pip install -e ".[all]" # Or install specific dependency groups: uv pip install -e ".[dev]" # Development tools uv pip install -e ".[test]" # Testing: pytest, Hypothesis, coverage, benchmarks uv pip install -e ".[optional]" # Optional features like TA-Lib uv pip install -e ".[oracle]" # Oracle parity libs: TA-Lib + tulipy ``` -------------------------------- ### Install oracle libraries Source: https://github.com/xgboosted/pandas-ta-classic/blob/main/README.md Commands to install optional oracle libraries for testing and acceleration. ```bash # uv uv pip install pandas-ta-classic[oracle] # installs both TA-Lib and tulipy uv pip install TA-Lib # TA-Lib only (also enables acceleration backend) uv pip install tulipy # tulipy only (oracle test use only) # pip pip install pandas-ta-classic[oracle] # installs both TA-Lib and tulipy pip install TA-Lib # TA-Lib only (also enables acceleration backend) pip install tulipy # tulipy only (oracle test use only) ``` -------------------------------- ### Setup Data and Indicators Source: https://github.com/xgboosted/pandas-ta-classic/blob/main/docs/tutorials.md Download market data using yfinance and calculate baseline SMA and RSI indicators. ```python import pandas as pd import pandas_ta_classic as ta import yfinance as yf # Download data df = yf.download("SPY", period="3mo") # Calculate baseline indicators df.ta.sma(length=50, append=True) df.ta.rsi(length=14, append=True) ``` -------------------------------- ### Installing tulipy Source: https://github.com/xgboosted/pandas-ta-classic/blob/main/docs/installation.md Commands to install the tulipy oracle library. ```bash uv pip install tulipy ``` ```bash pip install tulipy ``` -------------------------------- ### Verify Installation Source: https://github.com/xgboosted/pandas-ta-classic/blob/main/docs/quickstart.md Check if the package is installed or upgrade to the latest version. ```bash pip list | grep pandas-ta-classic # or pip install --upgrade pandas-ta-classic ``` -------------------------------- ### Install Development Version Source: https://github.com/xgboosted/pandas-ta-classic/blob/main/docs/installation.md Install the latest features and bug fixes directly from the GitHub repository. ```bash uv pip install git+https://github.com/xgboosted/pandas-ta-classic ``` ```bash pip install -U git+https://github.com/xgboosted/pandas-ta-classic ``` -------------------------------- ### Development Installation (pip) Source: https://github.com/xgboosted/pandas-ta-classic/blob/main/docs/installation.md Clone the repository and install in editable mode with specific dependency groups using pip. ```bash # Clone the repository git clone https://github.com/xgboosted/pandas-ta-classic.git cd pandas-ta-classic # Install in editable mode with all dependencies pip install -e ".[all]" # Or install specific dependency groups: pip install -e ".[dev]" # Development tools pip install -e ".[test]" # Testing: pytest, Hypothesis, coverage, benchmarks pip install -e ".[optional]" # Optional features like TA-Lib pip install -e ".[oracle]" # Oracle parity libs: TA-Lib + tulipy ``` -------------------------------- ### Install dependencies with uv Source: https://github.com/xgboosted/pandas-ta-classic/blob/main/CONTRIBUTING.md Commands to install the package in development mode with various dependency groups using uv. ```bash # Install package in development mode with all dependencies uv pip install -e ".[all]" # Or install specific dependency groups as needed: uv pip install -e ".[dev]" # Development dependencies uv pip install -e ".[test]" # Testing: pytest, Hypothesis, coverage uv pip install -e ".[docs]" # Documentation dependencies uv pip install -e ".[optional]" # Optional runtime features (tqdm progress bars) uv pip install -e ".[oracle]" # Oracle parity libs: TA-Lib + tulipy uv pip install -e ".[integration]" # Backtesting integrations: backtesting, backtrader, vectorbt, yfinance uv pip install -e ".[performance]" # Numba acceleration ``` -------------------------------- ### Install VectorBT Source: https://github.com/xgboosted/pandas-ta-classic/blob/main/docs/tutorials.md Install the required VectorBT package via pip. ```bash pip install vectorbt ``` -------------------------------- ### Install TA-Lib Acceleration Source: https://github.com/xgboosted/pandas-ta-classic/blob/main/docs/quickstart.md Install the optional TA-Lib dependency to accelerate core indicators. ```bash pip install "ta-lib>=0.6.8" ``` -------------------------------- ### Installing Oracle Libraries via Extras Source: https://github.com/xgboosted/pandas-ta-classic/blob/main/docs/installation.md Convenience command to install both oracle libraries simultaneously. ```bash # uv uv pip install pandas-ta-classic[oracle] # pip pip install pandas-ta-classic[oracle] ``` -------------------------------- ### Installing TA-Lib Source: https://github.com/xgboosted/pandas-ta-classic/blob/main/docs/installation.md Commands to install the TA-Lib library using various package managers. ```bash uv pip install "ta-lib>=0.6.8" ``` ```bash pip install "ta-lib>=0.6.8" ``` ```bash conda install -c conda-forge libta-lib conda install -c conda-forge ta-lib ``` -------------------------------- ### Install Stable Release Source: https://github.com/xgboosted/pandas-ta-classic/blob/main/docs/installation.md Install the latest stable version from PyPI using recommended or standard package managers. ```bash uv pip install pandas-ta-classic ``` ```bash pip install pandas-ta-classic ``` -------------------------------- ### Install optional dependencies with uv Source: https://github.com/xgboosted/pandas-ta-classic/blob/main/docs/installation.md Use these commands to install optional packages when using the uv package manager. ```bash # For stock data download uv pip install yfinance # For backtesting uv pip install backtesting uv pip install backtrader uv pip install vectorbt # For enhanced performance (optional — provides 6–230× speedups on hot-loop indicators) uv pip install pandas-ta-classic[performance] # Or install numba directly uv pip install numba # Install all optional dependencies at once uv pip install pandas-ta-classic[optional] ``` -------------------------------- ### Initialize AlphaVantage Data Source Source: https://github.com/xgboosted/pandas-ta-classic/blob/main/examples/PandasTA_Strategy_Examples.ipynb Configure the AlphaVantage data source if the library is installed. ```python if AlphaVantage is not None: AV = AlphaVantage( api_key="YOUR API KEY", premium=False, output_size="full", clean=True, export_path=".", export=True, ) else: AV = None print("[!] AlphaVantage not installed. Install with: pip install alphaVantage-api") AV ``` -------------------------------- ### Install dependencies with pip Source: https://github.com/xgboosted/pandas-ta-classic/blob/main/CONTRIBUTING.md Commands to install the package in development mode with various dependency groups using pip. ```bash # Install package in development mode with all dependencies pip install -e ".[all]" # Or install specific dependency groups as needed: pip install -e ".[dev]" # Development dependencies pip install -e ".[test]" # Testing: pytest, Hypothesis, coverage pip install -e ".[docs]" # Documentation dependencies pip install -e ".[optional]" # Optional runtime features (tqdm progress bars) pip install -e ".[oracle]" # Oracle parity libs: TA-Lib + tulipy pip install -e ".[integration]" # Backtesting integrations: backtesting, backtrader, vectorbt, yfinance pip install -e ".[performance]" # Numba acceleration ``` -------------------------------- ### Quick Start and Indicator Calculation Source: https://github.com/xgboosted/pandas-ta-classic/blob/main/index.md Basic usage for loading data, calculating indicators, and using the fluent API or strategies. ```python import pandas as pd import pandas_ta_classic as ta # Load your data df = pd.read_csv("path/to/symbol.csv") # Calculate indicators df.ta.sma(length=20, append=True) # Simple Moving Average df.ta.rsi(length=14, append=True) # RSI df.ta.macd(append=True) # MACD # Fluent API chaining df.ta.chain().sma(20).ta.rsi(14).ta.macd().ta.bbands(20) # Or use strategies for bulk processing df.ta.strategy("CommonStrategy") ``` -------------------------------- ### Install optional dependencies with pip Source: https://github.com/xgboosted/pandas-ta-classic/blob/main/docs/installation.md Use these commands to install optional packages when using the standard pip package manager. ```bash # For stock data download pip install yfinance # For backtesting pip install backtesting pip install backtrader pip install vectorbt # For enhanced performance (optional — provides 6–230× speedups on hot-loop indicators) pip install pandas-ta-classic[performance] # Or install numba directly pip install numba # Install all optional dependencies at once pip install pandas-ta-classic[optional] ``` -------------------------------- ### Get Indicator Help Source: https://github.com/xgboosted/pandas-ta-classic/blob/main/examples/example.ipynb Accesses documentation for a specific indicator. ```python help(ta.ema) ``` -------------------------------- ### Configure TA-Lib Implementation for Core Indicators Source: https://github.com/xgboosted/pandas-ta-classic/blob/main/docs/indicators.md Native implementations are used by default for core indicators. Pass talib=True to explicitly use the TA-Lib implementation if installed. ```python # 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) # Indicators with TA-Lib passthrough: # ad, adosc, apo, aroon, atr, bbands, bop, cci, cmo, dema, dm, # ema, hlc3, macd, mfi, midpoint, midprice, mom, natr, obv, ppo, # roc, rsi, sma, stdev, t3, tema, trima, true_range, uo, # variance, wcp, willr, wma ``` -------------------------------- ### Initialize Environment and Dependencies Source: https://github.com/xgboosted/pandas-ta-classic/blob/main/examples/VectorBT_Backtest_with_Pandas_TA.ipynb Imports necessary libraries and prints version information to verify the environment. ```python from datetime import datetime import numpy as np import pandas as pd import pandas_ta_classic as ta import vectorbt as vbt print("Package Versions:") print(f"Numpy v{np.__version__}") print(f"Pandas v{pd.__version__}") print("vectorbt >= v1.0.0") print( f"\nPandas TA Classic v{ta.version}\nTo install the Latest Version:\n$ pip install pandas-ta-classic\n" ) %matplotlib inline ``` -------------------------------- ### Import Libraries and Download Data Source: https://github.com/xgboosted/pandas-ta-classic/blob/main/docs/tutorials.md Initialize the environment by importing necessary libraries and fetching historical price data. ```python import pandas as pd import pandas_ta_classic as ta import vectorbt as vbt import yfinance as yf # Download data df = yf.download("AAPL", start="2022-01-01", end="2024-01-01") ``` -------------------------------- ### Initialize Environment and Imports Source: https://github.com/xgboosted/pandas-ta-classic/blob/main/examples/AIExample.ipynb Import core libraries and configure Pandas display settings for data analysis. ```python import numpy as np import pandas as pd import mplfinance as mpf import pandas_ta_classic as ta from watchlist import ( colors, Watchlist, ) # Is this failing? If so, copy it locally. See above. pd.set_option("display.max_rows", 100) pd.set_option("display.max_columns", 20) print(f"Numpy v{np.__version__}") print(f"Pandas v{pd.__version__}") print(f"mplfinance v{mpf.__version__}") print( f"\nPandas TA Classic v{ta.version}\nTo install the Latest Version:\n$ pip install pandas-ta-classic\n" ) %matplotlib inline ``` -------------------------------- ### Set Up Environment for Pandas TA Classic Source: https://github.com/xgboosted/pandas-ta-classic/blob/main/docs/tutorials.md Imports necessary libraries and downloads historical stock data using yfinance. ```python import pandas as pd import pandas_ta_classic as ta import yfinance as yf import matplotlib.pyplot as plt # Download data df = yf.download("AAPL", start="2023-01-01", end="2024-01-01") print(f"Downloaded {len(df)} rows of data") ``` -------------------------------- ### Initialize Environment Source: https://github.com/xgboosted/pandas-ta-classic/blob/main/examples/example.ipynb Imports necessary libraries and configures the environment for technical analysis. ```python %matplotlib inline import random as rnd import numpy as np import pandas as pd import mplfinance as mpf # Optional import for AlphaVantage API try: from alphaVantageAPI.alphavantage import AlphaVantage except ImportError: print( "[!] alphaVantageAPI not available. Install with: pip install alphaVantage-api" ) AlphaVantage = None import pandas_ta_classic as ta from watchlist import colors # Is this failing? If so, copy it locally. See above. print( f"\nPandas TA Classic v{ta.version}\nTo install the Latest Version:\n$ pip install pandas-ta-classic\n" ) ``` -------------------------------- ### Create virtual environment Source: https://github.com/xgboosted/pandas-ta-classic/blob/main/CONTRIBUTING.md Commands to initialize a virtual environment using either uv or standard venv. ```bash uv venv source .venv/bin/activate # On Windows: .venv\Scripts\activate ``` ```bash python -m venv .venv source .venv/bin/activate # On Windows: .venv\Scripts\activate ``` -------------------------------- ### Clone the repository Source: https://github.com/xgboosted/pandas-ta-classic/blob/main/CONTRIBUTING.md Use a full clone to ensure setuptools-scm can access git tags for versioning. ```bash git clone https://github.com/xgboosted/pandas-ta-classic.git ``` -------------------------------- ### Create Buy and Hold Portfolios Source: https://github.com/xgboosted/pandas-ta-classic/blob/main/examples/VectorBT_Backtest_with_Pandas_TA.ipynb Initializes portfolios based on holding strategies for benchmark and asset data. ```python # Benchmark Buy and Hold (BnH) Strategy benchmarkpf_bnh = vbt.Portfolio.from_holding(benchmarkdf.close) print(trade_table(benchmarkpf_bnh)) combine_stats(benchmarkpf_bnh, benchmarkdf.name, "Buy and Hold", LIVE) ``` ```python # Asset Buy and Hold (BnH) Strategy assetpf_bnh = vbt.Portfolio.from_holding(assetdf.close) print(trade_table(assetpf_bnh)) combine_stats(assetpf_bnh, assetdf.name, "Buy and Hold", LIVE) ``` -------------------------------- ### Create Signal-based Portfolios Source: https://github.com/xgboosted/pandas-ta-classic/blob/main/examples/VectorBT_Backtest_with_Pandas_TA.ipynb Initializes portfolios using entry and exit signals. ```python # Benchmark Portfolio from Trade Signals benchmarkpf_signals = vbt.Portfolio.from_signals( benchmarkdf.close, entries=benchmark_signals.TS_Entries, exits=benchmark_signals.TS_Exits, ) trade_table(benchmarkpf_signals, k=5) combine_stats(benchmarkpf_signals, benchmarkdf.name, "Long Strategy", LIVE) ``` ```python # Asset Portfolio from Trade Signals assetpf_signals = vbt.Portfolio.from_signals( assetdf.close, entries=asset_signals.TS_Entries, exits=asset_signals.TS_Exits, ) trade_table(assetpf_signals, k=5) combine_stats(assetpf_signals, assetdf.name, "Long Strategy", LIVE) ``` -------------------------------- ### Create and Inspect Watchlist Source: https://github.com/xgboosted/pandas-ta-classic/blob/main/examples/PandasTA_Strategy_Examples.ipynb Initialize a Watchlist with tickers and inspect its configuration. ```python data_source = "yahoo" # Default (change to "av" if AlphaVantage is configured) # data_source = "av" watch = Watchlist(["SPY", "IWM"], ds_name=data_source, timed=False) ``` ```python watch ``` ```python help(Watchlist) ``` -------------------------------- ### Define Backtest Date Range Source: https://github.com/xgboosted/pandas-ta-classic/blob/main/examples/VectorBT_Backtest_with_Pandas_TA.ipynb Set the start and end dates for the analysis period. ```python start_date = datetime(2005, 1, 1) # Adjust as needed end_date = datetime(2010, 1, 1) # Adjust as needed ``` -------------------------------- ### Get List of Indicators Source: https://github.com/xgboosted/pandas-ta-classic/blob/main/docs/dataframe_api.md Retrieve a list of available technical indicators. Can be returned as a list or exclude specific indicators. ```python ind_list = df.ta.indicators(as_list=True) ``` ```python ind_list = df.ta.indicators(as_list=True, exclude=["vp", "td_seq"]) ``` -------------------------------- ### Configuring and running a backtest Source: https://github.com/xgboosted/pandas-ta-classic/blob/main/docs/tutorials/vectorbt.md Sets portfolio settings and executes the backtest using generated signals. ```python vbt.settings.portfolio["freq"] = "1D" vbt.settings.portfolio["fees"] = 0.0025 vbt.settings.portfolio["slippage"] = 0.0025 pf = vbt.Portfolio.from_signals( df["Close"], entries=signals.TS_Entries, exits=signals.TS_Exits, ) print(pf.stats()) ``` -------------------------------- ### Fetch data using built-in ticker method Source: https://github.com/xgboosted/pandas-ta-classic/blob/main/docs/quickstart.md Uses the library's internal ticker wrapper which requires yfinance to be installed. ```python import pandas as pd import pandas_ta_classic as ta # Create empty DataFrame df = pd.DataFrame() # Fetch data (requires yfinance) df = df.ta.ticker("AAPL", period="1y") # Add indicators df.ta.sma(length=20, append=True) df.ta.ema(length=20, append=True) ``` -------------------------------- ### Property: Get Last Run Time Source: https://github.com/xgboosted/pandas-ta-classic/blob/main/docs/dataframe_api.md The `.ta.last_run` property returns the execution time in seconds of the most recently run indicator or strategy. ```python # Returns the time it took to run the last indicator or strategy df.ta.last_run ``` -------------------------------- ### Using TA-Lib for Core Indicators Source: https://github.com/xgboosted/pandas-ta-classic/blob/main/docs/installation.md Demonstrates how to toggle between native implementations and TA-Lib acceleration for core indicators. ```python 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 ``` -------------------------------- ### Define indicator docstring format Source: https://github.com/xgboosted/pandas-ta-classic/blob/main/CONTRIBUTING.md Required structure for indicator function docstrings, including type hints, argument descriptions, and usage examples. ```python from typing import Optional def indicator_name(close: pd.Series, length: Optional[int] = None) -> pd.Series: """ Brief description of the indicator. Longer description if needed, including mathematical formula or algorithm explanation. Args: close (pd.Series): Series of closing prices length (Optional[int]): Lookback period. Defaults to None (resolved internally, typically 20). Returns: pd.Series: Calculated indicator values Example: >>> import pandas as pd >>> import pandas_ta_classic as ta >>> data = pd.read_csv('data.csv') >>> result = ta.indicator_name(data['close']) """ ``` -------------------------------- ### Initialize Pandas TA Classic Environment Source: https://github.com/xgboosted/pandas-ta-classic/blob/main/examples/PandasTA_Strategy_Examples.ipynb Sets up the environment by importing necessary modules and checking for optional dependencies like AlphaVantage and the Watchlist module. ```python %matplotlib inline import pandas_ta_classic as ta # Optional import for AlphaVantage API try: from alphaVantageAPI.alphavantage import ( AlphaVantage, ) # pip install alphaVantage-api except ImportError: print( "[!] alphaVantageAPI not available. Install with: pip install alphaVantage-api" ) AlphaVantage = None from watchlist import Watchlist # Is this failing? If so, copy it locally. See above. print( f"\nPandas TA Classic v{ta.version}\nTo install the Latest Version:\n$ pip install pandas-ta-classic\n" ) ``` -------------------------------- ### Configure VectorBT Theme and Portfolio Settings Source: https://github.com/xgboosted/pandas-ta-classic/blob/main/examples/VectorBT_Backtest_with_Pandas_TA.ipynb Sets global visualization themes and portfolio parameters such as fees, slippage, and frequency. ```python cheight, cwidth = 500, 1000 # Adjust as needed for Chart Height and Width vbt.settings.set_theme("dark") # Options: "light" (Default), "dark" (my fav), "seaborn" # Must be set vbt.settings.portfolio["freq"] = "1D" # Daily # Predefine vectorbt Portfolio settings # vbt.settings.portfolio["init_cash"] = 100 vbt.settings.portfolio["fees"] = 0.0025 # 0.25% vbt.settings.portfolio["slippage"] = 0.0025 # 0.25% # vbt.settings.portfolio["size"] = 100 # vbt.settings.portfolio["accumulate"] = False vbt.settings.portfolio["allow_partial"] = False pf_settings = pd.DataFrame(vbt.settings.portfolio.items(), columns=["Option", "Value"]) pf_settings.set_index("Option", inplace=True) print("Portfolio Settings [Initial]") pf_settings ``` -------------------------------- ### Clone the repository Source: https://github.com/xgboosted/pandas-ta-classic/blob/main/CONTRIBUTING.md Commands to clone the forked repository and navigate into the project directory. ```bash git clone https://github.com/your-username/pandas-ta-classic.git cd pandas-ta-classic ``` -------------------------------- ### Access Squeeze Indicator Help Source: https://github.com/xgboosted/pandas-ta-classic/blob/main/examples/example.ipynb Displays the help documentation for the squeeze indicator function. ```python # help(ta.squeeze) ``` -------------------------------- ### Define Tickers for Benchmarks and Assets Source: https://github.com/xgboosted/pandas-ta-classic/blob/main/examples/VectorBT_Backtest_with_Pandas_TA.ipynb Initialize lists for benchmark and asset symbols to be used in the backtest. ```python benchmark_tickers = ["SPY", "QQQ"] asset_tickers = ["AAPL", "TSLA", "NVDA"] all_tickers = benchmark_tickers + asset_tickers print("Tickers by index #") print("=" * 100) print(f"Benchmarks: {', '.join([f'{k}: {v}' for k,v in enumerate(benchmark_tickers)])}") print(f" Assets: {', '.join([f'{k}: {v}' for k,v in enumerate(asset_tickers)])}") print(f" All: {', '.join([f'{k}: {v}' for k,v in enumerate(all_tickers)])}") ``` ```python benchmark = benchmark_tickers[0] # Change index for different benchmark asset = asset_tickers[2] # Change index for different symbol print(f"Selected Benchmark | Asset: {benchmark} | {asset}") ``` -------------------------------- ### Display Available Data Source: https://github.com/xgboosted/pandas-ta-classic/blob/main/examples/VectorBT_Backtest_with_Pandas_TA.ipynb Print the keys of the downloaded benchmark and asset datasets. ```python print("Available Data:") print("=" * 100) print(f"Benchmarks: {', '.join(benchmarks.keys())}") print(f"Assets: {', '.join(assets.keys())}") ``` -------------------------------- ### Execute Full Test Suite Source: https://github.com/xgboosted/pandas-ta-classic/blob/main/docs/testing.md Commands for running the complete test suite, regenerating fixtures, and checking code coverage. ```bash # Full test suite (primary — matches CI, auto-regenerates fixture JSONs) python -m unittest discover tests/ -v # Regenerate fixtures then run all tests (recommended after indicator changes) make test-all # Regenerate fixture JSONs only (requires TA-Lib installed) make fixtures # pytest equivalent python -m pytest tests/ -v # With coverage python -m pytest --cov=pandas_ta_classic --cov-report=html tests/ ``` -------------------------------- ### Create Custom Strategies Source: https://github.com/xgboosted/pandas-ta-classic/blob/main/examples/PandasTA_Strategy_Examples.ipynb Define strategies by providing a name and a list of indicator dictionaries. ```python custom_a = ta.Strategy( name="A", ta=[{"kind": "sma", "length": 50}, {"kind": "sma", "length": 200}] ) custom_a ``` ```python custom_b = ta.Strategy( name="B", ta=[ {"kind": "ema", "length": 8}, {"kind": "ema", "length": 21}, {"kind": "log_return", "cumulative": True}, {"kind": "rsi"}, {"kind": "supertrend"}, ], ) custom_b ``` -------------------------------- ### Implement Charting Class with mplfinance Source: https://github.com/xgboosted/pandas-ta-classic/blob/main/examples/example.ipynb A custom class structure for integrating technical analysis strategies with mplfinance visualization. ```python class Chart(object): def __init__( self, df: pd.DataFrame = None, strategy: ta.Strategy = ta.CommonStrategy, *args, **kwargs, ): self.verbose = kwargs.pop("verbose", False) if isinstance(df, pd.DataFrame) and df.ta.datetime_ordered: self.df = df if self.df.name is not None and self.df.name != "": df_name = str(self.df.name) else: df_name = "DataFrame" if self.verbose: print(f"[i] Loaded {df_name}{self.df.shape}") else: print("[X] Oops! Missing 'ohlcv' data or index is not datetime ordered.\n") return None self._validate_mpf_kwargs(**kwargs) self._validate_chart_kwargs(**kwargs) self._validate_ta_strategy(strategy) # Build TA and Plot self.df.ta.strategy(self.strategy, verbose=self.verbose) self._plot(**kwargs) def _validate_ta_strategy(self, strategy): if strategy is not None or isinstance(strategy, ta.Strategy): self.strategy = strategy elif len(self.strategy_ta) > 0: print(f"[+] Strategy: {self.strategy_name}") else: self.strategy = ta.CommonStrategy def _validate_chart_kwargs(self, **kwargs): """Chart Settings""" self.config = {} self.config["last"] = kwargs.pop("last", recent_bars(self.df)) self.config["rpad"] = kwargs.pop("rpad", 10) self.config["title"] = kwargs.pop("title", "Asset") self.config["volume"] = kwargs.pop("volume", True) def _validate_mpf_kwargs(self, **kwargs): # mpf global chart settings default_mpf_width = { "candle_linewidth": 0.6, "candle_width": 0.525, "volume_width": 0.525, } mpfchart = {} mpf_style = kwargs.pop("style", "") if mpf_style == "" or mpf_style.lower() == "random": mpf_styles = mpf.available_styles() mpfchart["style"] = mpf_styles[rnd.randrange(len(mpf_styles))] elif mpf_style.lower() in mpf.available_styles(): mpfchart["style"] = mpf_style mpfchart["figsize"] = kwargs.pop("figsize", (12, 10)) mpfchart["non_trading"] = kwargs.pop("nontrading", False) mpfchart["rc"] = kwargs.pop("rc", {"figure.facecolor": "#EDEDED"}) mpfchart["plot_ratios"] = kwargs.pop("plot_ratios", (12, 1.7)) mpfchart["scale_padding"] = kwargs.pop( "scale_padding", {"left": 1, "top": 4, "right": 1, "bottom": 1} ) mpfchart["tight_layout"] = kwargs.pop("tight_layout", True) mpfchart["type"] = kwargs.pop("type", "candle") mpfchart["width_config"] = kwargs.pop("width_config", default_mpf_width) mpfchart["xrotation"] = kwargs.pop("xrotation", 15) self.mpfchart = mpfchart def _attribution(self): print( f"\nPandas v: {pd.__version__} [pip install pandas] https://github.com/pandas-dev/pandas" ) print( "Data from AlphaVantage v: 1.0.19 [pip install alphaVantage-api] http://www.alphavantage.co" ) print( f"Technical Analysis with Pandas TA Classic v: {ta.version} [pip install pandas-ta-classic] https://github.com/xgboosted/pandas-ta-classic" ) print( f"Charts by Matplotlib Finance v: {mpf.__version__} [pip install mplfinance] https://github.com/matplotlib/mplfinance\n" ) def _right_pad_df(self, rpad: int, delta_unit: str = "D", range_freq: str = "B"): if rpad > 0: dfpad = self.df[-rpad:].copy() dfpad.iloc[:, :] = np.nan df_frequency = self.df.index.value_counts().mode()[ 0 ] # Most common frequency freq_delta = pd.Timedelta(df_frequency, unit=delta_unit) new_dr = pd.date_range( start=self.df.index[-1] + freq_delta, periods=rpad, freq=range_freq ) dfpad.index = new_dr # Update the padded index with new dates self.df = pd.concat([self.df, dfpad]) def _plot(self, **kwargs): if not isinstance(self.mpfchart["plot_ratios"], tuple): print("[X] plot_ratios must be a tuple") return ``` -------------------------------- ### Swap and Run Strategies Source: https://github.com/xgboosted/pandas-ta-classic/blob/main/examples/PandasTA_Strategy_Examples.ipynb Assign custom strategies to the Watchlist and execute them on specific tickers. ```python # Load custom_a into Watchlist and verify watch.strategy = custom_a # watch.debug = True watch.strategy ``` ```python watch.load("IWM") ``` ```python # Load custom_b into Watchlist and verify watch.strategy = custom_b watch.strategy ``` ```python watch.load("SPY") ``` -------------------------------- ### Execute Watchlist Strategy Source: https://github.com/xgboosted/pandas-ta-classic/blob/main/examples/PandasTA_Strategy_Examples.ipynb Load data for tickers using the assigned strategy. ```python # No arguments loads all the tickers and applies the Strategy to each ticker. # The result can be accessed with Watchlist's 'data' property which returns a # dictionary keyed by ticker and DataFrames as values watch.load(verbose=True) ``` ```python ", ".join([f"{t}: {d.shape}" for t, d in watch.data.items()]) ``` ```python watch.data["SPY"] ``` ```python watch.load("SPY", plot=True, mas=True) ``` -------------------------------- ### Development Validation Commands Source: https://github.com/xgboosted/pandas-ta-classic/blob/main/AGENTS.md Commands for setting up the development environment, running tests, and performing code quality checks. ```bash # Create venv (first time only) python -m venv .venv # stdlib # or: uv venv .venv # faster alternative if uv installed # Activate and install source .venv/bin/activate pip install -e . # or: uv pip install -e . # Core import check python -c "import pandas_ta_classic; print(pandas_ta_classic.version)" # Formatting check black --check --diff pandas_ta_classic/ # Linting (critical errors only) ruff check pandas_ta_classic --select E9,F63,F7,F82 # Linting (advisory — non-blocking in CI) ruff check pandas_ta_classic --extend-select C901,E501 --exit-zero # Apply formatting black pandas_ta_classic/ # Install oracle dependencies (required for full test suite) pip install -e ".[oracle]" # Full test suite pytest tests/ -v # Oracle tests only pytest tests/test_oracle_talib.py tests/test_oracle_tulipy.py -v # Single test module (fastest feedback) pytest tests/test_indicator_momentum.py -v # Specific test pytest tests/test_indicator_momentum.py::TestRSI::test_rsi -v # Hypothesis property-based tests pytest tests/test_property_based.py -v # Docs build cd docs && make html # Build distribution python -m build ``` -------------------------------- ### Comparing strategy against Buy-and-Hold Source: https://github.com/xgboosted/pandas-ta-classic/blob/main/docs/tutorials/vectorbt.md Benchmarks the strategy performance against a simple buy-and-hold portfolio. ```python pf_bnh = vbt.Portfolio.from_holding(df["Close"]) print("Strategy:") print(pf.stats()[["Total Return [%]", "Sharpe Ratio", "Max Drawdown [%]"]]) print("\nBuy and Hold:") print(pf_bnh.stats()[["Total Return [%]", "Sharpe Ratio", "Max Drawdown [%]"]]) ``` -------------------------------- ### Define and Run Custom Strategy Source: https://github.com/xgboosted/pandas-ta-classic/blob/main/docs/strategies.md Creates and runs a custom strategy by defining a name, description, and a list of indicators with their specific arguments. This allows for a tailored set of indicators to be applied. ```python CustomStrategy = ta.Strategy( name="Momo and Volatility", description="SMA 50,200, BBANDS, RSI, MACD and Volume SMA 20", ta=[ {"kind": "sma", "length": 50}, {"kind": "sma", "length": 200}, {"kind": "bbands", "length": 20}, {"kind": "rsi"}, {"kind": "macd", "fast": 8, "slow": 21}, {"kind": "sma", "close": "volume", "length": 20, "prefix": "VOLUME"}, ] ) # To run your "Custom Strategy" df.ta.strategy(CustomStrategy) ``` -------------------------------- ### Run VectorBT Backtest Source: https://github.com/xgboosted/pandas-ta-classic/blob/main/docs/tutorials.md Execute the backtest using the generated signals and display performance statistics. ```python # Create portfolio portfolio = vbt.Portfolio.from_signals( df['Close'], entries, exits, init_cash=10000, fees=0.001, # 0.1% trading fees freq='1D' ) # Display results print(portfolio.stats()) print(f"\nTotal Return: {portfolio.total_return() * 100:.2f}%") print(f"Sharpe Ratio: {portfolio.sharpe_ratio():.2f}") print(f"Max Drawdown: {portfolio.max_drawdown() * 100:.2f}%") ``` -------------------------------- ### Create and push a release tag Source: https://github.com/xgboosted/pandas-ta-classic/blob/main/CONTRIBUTING.md Create an annotated tag and push it to the remote repository to trigger the automated release process. ```bash git tag -a X.Y.Z -m "X.Y.Z" git push origin X.Y.Z ``` -------------------------------- ### Fix versioning issues Source: https://github.com/xgboosted/pandas-ta-classic/blob/main/CONTRIBUTING.md Fetch missing tags and reinstall the package in editable mode to regenerate the version file if the version appears as 0.0.0. ```bash git fetch --tags pip install -e ".[dev]" # reinstall to regenerate _version.py ``` -------------------------------- ### Load data from CSV files Source: https://github.com/xgboosted/pandas-ta-classic/blob/main/docs/quickstart.md Demonstrates loading OHLCV data from a local file and ensuring proper formatting for indicator calculation. ```python import pandas as pd import pandas_ta_classic as ta # Load CSV with OHLCV data df = pd.read_csv('stock_data.csv', parse_dates=['date'], index_col='date') # Ensure column names are lowercase (optional but recommended) df.columns = [col.lower() for col in df.columns] # Calculate indicators df.ta.sma(length=20, append=True) df.ta.atr(length=14, append=True) # Average True Range ``` -------------------------------- ### Retrieve Indicator Documentation Source: https://github.com/xgboosted/pandas-ta-classic/blob/main/docs/quickstart.md Use the help function or access the docstring directly to understand indicator parameters. ```python # Get indicator documentation help(ta.sma) help(ta.macd) help(ta.rsi) # Or use Python's built-in print(ta.sma.__doc__) ``` -------------------------------- ### Configure and Plot Technical Indicators with mplfinance Source: https://github.com/xgboosted/pandas-ta-classic/blob/main/examples/example.ipynb This snippet demonstrates how to override chart configurations, calculate various technical indicators, and prepare them for visualization using mplfinance addplots. ```python # Override Chart Title Option chart_title = self.config["title"] if "title" in kwargs and isinstance(kwargs["title"], str): chart_title = kwargs.pop("title") # Override Right Bar Padding Option rpad = self.config["rpad"] if "rpad" in kwargs and kwargs["rpad"] > 0: rpad = int(kwargs["rpad"]) def cpanel(): return len(self.mpfchart["plot_ratios"]) # Last Second Default TA Indicators linreg = kwargs.pop("linreg", False) linreg_name = self.df.ta.linreg(append=True).name if linreg else "" midpoint = kwargs.pop("midpoint", False) midpoint_name = self.df.ta.midpoint(append=True).name if midpoint else "" ohlc4 = kwargs.pop("ohlc4", False) ohlc4_name = self.df.ta.ohlc4(append=True).name if ohlc4 else "" clr = kwargs.pop("clr", False) clr_name = ( self.df.ta.log_return(cumulative=True, append=True).name if clr else "" ) rsi = kwargs.pop("rsi", False) rsi_length = kwargs.pop("rsi_length", None) if isinstance(rsi_length, int) and rsi_length > 1: rsi_name = self.df.ta.rsi(length=rsi_length, append=True).name elif rsi: rsi_name = self.df.ta.rsi(append=True).name else: rsi_name = "" zscore = kwargs.pop("zscore", False) zscore_length = kwargs.pop("zscore_length", None) if isinstance(zscore_length, int) and zscore_length > 1: zs_name = self.df.ta.zscore(length=zscore_length, append=True).name elif zscore: zs_name = self.df.ta.zscore(append=True).name else: zs_name = "" macd = kwargs.pop("macd", False) macd_name = "" if macd: macds = self.df.ta.macd(append=True) macd_name = macds.name squeeze = kwargs.pop("squeeze", False) lazybear = kwargs.pop("lazybear", False) squeeze_name = "" if squeeze: squeezes = self.df.ta.squeeze(lazybear=lazybear, detailed=True, append=True) squeeze_name = squeezes.name ama = kwargs.pop("archermas", False) ama_name = "" if ama: amas = self.df.ta.amat(append=True) ama_name = amas.name aobv = kwargs.pop("archerobv", False) aobv_name = "" if aobv: aobvs = self.df.ta.aobv(append=True) aobv_name = aobvs.name # Pad and trim Chart self._right_pad_df(rpad) mpfdf = self.df.tail(self.config["last"]).copy() mpfdf_columns = list(self.df.columns) tsig = kwargs.pop("tsignals", False) if tsig: # Long Trend requires Series Comparison (<=. <, = >, >=) # or Trade Logic that yields trends in binary. default_long = mpfdf["SMA_10"] > mpfdf["SMA_20"] long_trend = kwargs.pop("long_trend", default_long) if not isinstance(long_trend, pd.Series): raise ( "[X] Must be a Series that has boolean values or values of 0s and 1s" ) mpfdf.ta.percent_return(append=True) mpfdf.ta.tsignals(long_trend, append=True) buys = np.where(mpfdf.TS_Entries > 0, 1, np.nan) sells = np.where(mpfdf.TS_Exits > 0, 1, np.nan) mpfdf["ACTRET_1"] = mpfdf.TS_Trends * mpfdf.PCTRET_1 # BEGIN: Custom TA Plots and Panels # Modify the area below taplots = [] # Holds all the additional plots # Panel 0: Price Overlay if linreg_name in mpfdf_columns: taplots += [ mpf.make_addplot( mpfdf[linreg_name], type=kwargs.pop("linreg_type", "line"), color=kwargs.pop("linreg_color", "black"), linestyle="-.", width=1.2, panel=0, ) ] if midpoint_name in mpfdf_columns: taplots += [ mpf.make_addplot( mpfdf[midpoint_name], type=kwargs.pop("midpoint_type", "scatter"), color=kwargs.pop("midpoint_color", "fuchsia"), width=0.4, panel=0, ) ] if ohlc4_name in mpfdf_columns: taplots += [ mpf.make_addplot( mpfdf[ohlc4_name], ylabel=ohlc4_name, type=kwargs.pop("ohlc4_type", "scatter"), color=kwargs.pop("ohlc4_color", "blue"), alpha=0.85, width=0.4, panel=0, ) ] ``` -------------------------------- ### Implement Momentum Strategy with Multi-Output Indicators Source: https://github.com/xgboosted/pandas-ta-classic/blob/main/docs/tutorials/backtesting_py.md Unpacks multi-column indicator results like MACD into separate strategy attributes. ```python class MACDMomentum(Strategy): def init(self): self.macd_line, self.macd_hist, self.macd_signal = self.I( ta_bridge, self.data, lambda df: df.ta.macd(fast=12, slow=26, signal=9) ) def next(self): if crossover(self.macd_line, self.macd_signal): self.buy() elif crossover(self.macd_signal, self.macd_line): self.position.close() ``` -------------------------------- ### Apply support and resistance indicators Source: https://github.com/xgboosted/pandas-ta-classic/blob/main/docs/quickstart.md Calculates Parabolic SAR and Donchian Channels to identify key price levels. ```python # Parabolic Stop and Reverse df.ta.psar(append=True) # Donchian Channel (high/low price channels) df.ta.donchian(lower_length=20, upper_length=20, append=True) ``` -------------------------------- ### Access AllStrategy Properties Source: https://github.com/xgboosted/pandas-ta-classic/blob/main/examples/PandasTA_Strategy_Examples.ipynb Retrieves and prints the metadata and indicator configuration for the built-in AllStrategy. ```python AllStrategy = ta.AllStrategy print("name =", AllStrategy.name) print("description =", AllStrategy.description) print("created =", AllStrategy.created) print("ta =", AllStrategy.ta) ``` -------------------------------- ### Configure Plotting Environment Source: https://github.com/xgboosted/pandas-ta-classic/blob/main/examples/VectorBT_Backtest_with_Pandas_TA.ipynb Sets the theme and patches the show_png method to support interactive plotly widgets in notebooks. ```python vbt.settings.set_theme("seaborn") ``` ```python # Patch show_png to display as interactive plotly widget (no Chrome/kaleido needed) import plotly.io._renderers as _pr import nbformat as _nbf import vectorbt.utils.figure as _vbt_fig # Force plotly to recognize nbformat is available _pr.nbformat = _nbf def _show_png_patched(self, **kw): import plotly.io as pio pio.show(self, renderer="notebook_connected") _vbt_fig.FigureMixin.show_png = _show_png_patched ``` -------------------------------- ### Run multiple indicators using the Strategy System Source: https://github.com/xgboosted/pandas-ta-classic/blob/main/docs/quickstart.md Efficiently execute multiple indicators at once using built-in or custom strategies. ```python import pandas as pd import pandas_ta_classic as ta df = pd.read_csv('your_data.csv') # Use a built-in strategy df.ta.strategy("CommonStrategy") # Or create your own custom strategy my_strategy = ta.Strategy( name="MyStrategy", ta=[ {"kind": "sma", "length": 20}, {"kind": "sma", "length": 50}, {"kind": "rsi", "length": 14}, {"kind": "macd", "fast": 12, "slow": 26, "signal": 9}, {"kind": "bbands", "length": 20}, ] ) # Run your strategy df.ta.strategy(my_strategy) print(df.columns) # See all new indicator columns ``` -------------------------------- ### Generate Fixture Files Source: https://github.com/xgboosted/pandas-ta-classic/blob/main/docs/testing.md Manually trigger the generation of expected values and regression snapshots. ```bash python -m tests.fixtures.generate_fixtures python -m tests.fixtures.generate_regression_snapshots ``` -------------------------------- ### Select and Filter Data for Backtesting Source: https://github.com/xgboosted/pandas-ta-classic/blob/main/examples/VectorBT_Backtest_with_Pandas_TA.ipynb Select specific assets and apply date masking to constrain the data range. ```python benchmark_name = "SPY" # Select a Benchmark asset_name = "AAPL" # Select an Asset benchmarkdf = benchmarks[benchmark_name] assetdf = assets[asset_name] # Set True if you want to constrain Data between start_date & end_date common_range = True if common_range: crs = f" from {start_date} to {end_date}" benchmarkdf = dtmask(benchmarkdf, start_date, end_date) assetdf = dtmask(assetdf, start_date, end_date) # Update DataFrame names benchmarkdf.name = benchmark_name assetdf.name = asset_name print( f"Analysis of: {benchmarkdf.name} and {assetdf.name}{crs if common_range else ''}" ) ``` ```python benchmarkdf ``` ```python assetdf ``` -------------------------------- ### Check Ticker Help Source: https://github.com/xgboosted/pandas-ta-classic/blob/main/examples/example.ipynb Placeholder for checking ticker-related help documentation. ```python # help(e.ta.ticker) ```