### Access Help and Documentation for Pandas-TA Indicators in Python Source: https://context7.com/context7/pandas-ta_dev/llms.txt Shows how to use Python's built-in `help()` function to get detailed information about specific pandas-ta indicators (e.g., sma, macd, rsi, bbands). It also covers listing all indicators, accessing categories, checking the version, and inspecting indicator signatures. ```python import pandas_ta as ta import inspect # Get help on specific indicators help(ta.sma) help(ta.macd) help(ta.rsi) help(ta.bbands) # List all available indicators print(ta.indicators()) # Get indicator categories print(ta.categories) # Get version print(ta.version) # Example help output interpretation help(ta.macd) # Output shows: # - Function signature with parameters # - Default values # - Return value description # - Calculation formula # - Usage examples # Check if specific indicator exists if hasattr(ta, 'supertrend'): print("SuperTrend is available") # Get indicator metadata print(inspect.signature(ta.macd)) ``` -------------------------------- ### Get Indicator Help in Pandas TA Source: https://www.pandas-ta.dev/documentation/index Retrieve detailed information about a specific technical analysis indicator within the Pandas TA library. This is useful for understanding indicator arguments and usage, similar to using Python's built-in help function. ```python help(ta.macd) help(ta.sma) ``` -------------------------------- ### Recognize Candlestick Patterns with Pandas TA (TA-Lib) Source: https://context7.com/context7/pandas-ta_dev/llms.txt Demonstrates how to identify Japanese candlestick patterns using the pandas_ta library, which integrates with TA-Lib. It covers applying individual patterns, multiple patterns, all patterns at once, and filtering for specific bullish or bearish formations. The examples also show how to combine pattern recognition with other technical indicators like RSI. Requires pandas, pandas_ta, and TA-Lib libraries. ```python import pandas as pd import pandas_ta as ta df = pd.read_csv('candle_data.csv') # Single candlestick patterns df.ta.cdl_doji(append=True) # Doji df.ta.cdl_hammer(append=True) # Hammer df.ta.cdl_shooting_star(append=True) # Shooting Star df.ta.cdl_marubozu(append=True) # Marubozu # Multiple candlestick patterns df.ta.cdl_engulfing(append=True) # Engulfing pattern df.ta.cdl_harami(append=True) # Harami pattern df.ta.cdl_morning_star(append=True) # Morning Star df.ta.cdl_evening_star(append=True) # Evening Star # Apply all candlestick patterns at once df.ta.cdl_pattern(name="all", append=True) # Filter for specific patterns bullish_patterns = df[ (df['CDL_HAMMER'] != 0) | (df['CDL_MORNINGSTAR'] != 0) | (df['CDL_ENGULFING'] > 0) ] bearish_patterns = df[ (df['CDL_SHOOTINGSTAR'] != 0) | (df['CDL_EVENINGSTAR'] != 0) | (df['CDL_ENGULFING'] < 0) ] # Combine patterns with indicators df.ta.rsi(length=14, append=True) df['pattern_rsi_signal'] = ( ((df['CDL_HAMMER'] != 0) & (df['RSI_14'] < 30)) | # Bullish ((df['CDL_SHOOTINGSTAR'] != 0) & (df['RSI_14'] > 70)) # Bearish ) ``` -------------------------------- ### Apply Custom Strategies with Pandas TA Source: https://context7.com/context7/pandas-ta_dev/llms.txt Shows how to define and apply custom trading strategies using the pandas_ta library. Users can create a Strategy object with a list of technical indicators and their parameters, then apply it to a DataFrame. It also demonstrates how to create custom signals based on indicator outputs and use pre-built strategies. Requires pandas and pandas_ta libraries. ```python import pandas as pd import pandas_ta as ta df = pd.read_csv('trading_data.csv') # Define a custom strategy my_strategy = ta.Strategy( name="Momentum and Trend", description="Combines momentum and trend indicators", ta=[ {"kind": "sma", "length": 20}, {"kind": "sma", "length": 50}, {"kind": "ema", "length": 12}, {"kind": "ema", "length": 26}, {"kind": "rsi", "length": 14}, {"kind": "macd", "fast": 12, "slow": 26, "signal": 9}, {"kind": "bbands", "length": 20, "std": 2}, {"kind": "atr", "length": 14}, {"kind": "adx", "length": 14}, {"kind": "obv"} ] ) # Apply strategy to DataFrame df.ta.strategy(my_strategy) # Verify all indicators are added print(df.columns.tolist()) # Create custom combined strategy macd_bullish = df['MACD_12_26_9'] > df['MACDs_12_26_9'] rsi_oversold = df['RSI_14'] < 40 price_above_sma = df['close'] > df['SMA_50'] strong_trend = df['ADX_14'] > 25 df['buy_signal'] = macd_bullish & rsi_oversold & price_above_sma & strong_trend # Alternative: Use pre-built strategies df.ta.strategy("all") # Apply all available indicators (warning: very comprehensive) ``` -------------------------------- ### Calculate Bollinger Bands (BBANDS) with pandas-ta Source: https://context7.com/context7/pandas-ta_dev/llms.txt Calculates Bollinger Bands, including the middle band (SMA), upper band, and lower band, along with bandwidth and percentage. Supports direct function calls or DataFrame extension with customizable length and standard deviation. Input is a pandas Series of prices. Output is a DataFrame with BBANDS components or appended columns. ```python import pandas as pd import pandas_ta as ta df = pd.read_csv('stock_prices.csv') # Standard Bollinger Bands (20, 2) bbands = ta.bbands(df['close'], length=20, std=2) print(bbands.columns) # ['BBL_20_2.0', 'BBM_20_2.0', 'BBU_20_2.0', 'BBB_20_2.0', 'BBP_20_2.0'] # Custom Bollinger Bands bbands_custom = ta.bbands(df['close'], length=20, std=2.5) ``` -------------------------------- ### Utilize DataFrame Extension Methods in Pandas TA Source: https://context7.com/context7/pandas-ta_dev/llms.txt Illustrates how to access and apply various technical indicators directly through the pandas DataFrame extension interface provided by pandas_ta. This method simplifies workflows by allowing indicators to be appended directly to the DataFrame. It covers applying single, multiple, and category-based indicators, as well as retrieving metadata and help information. Requires pandas and pandas_ta libraries. ```python import pandas as pd import pandas_ta as ta # Load data df = pd.read_csv('ohlcv_data.csv', parse_dates=['date'], index_col='date') # Single indicator with append df.ta.sma(length=20, append=True) df.ta.rsi(length=14, append=True) # Multiple indicators in sequence df.ta.macd(append=True) df.ta.bbands(length=20, std=2, append=True) df.ta.atr(length=14, append=True) # Apply all overlap indicators df.ta.overlap(append=True) # SMA, EMA, WMA, etc. # Apply all momentum indicators df.ta.momentum(append=True) # RSI, MACD, Stochastic, etc. # Apply all volatility indicators df.ta.volatility(append=True) # ATR, Bollinger Bands, etc. # Apply all volume indicators df.ta.volume(append=True) # OBV, AD, CMF, etc. # Apply all trend indicators df.ta.trend(append=True) # ADX, Aroon, etc. # Get indicator metadata print(df.ta.cores) # Available cores print(df.ta.categories) # Indicator categories # Get help on any indicator help(df.ta.macd) ``` -------------------------------- ### Calculate SuperTrend Indicator with Pandas TA Source: https://context7.com/context7/pandas-ta_dev/llms.txt Demonstrates how to calculate the SuperTrend indicator using the pandas_ta library. It shows standard and custom parameter usage, applying the indicator directly to a DataFrame, and deriving buy/sell signals and distance from the SuperTrend line. Requires pandas and pandas_ta libraries. ```python import pandas as pd import pandas_ta as ta df = pd.read_csv('price_data.csv') # Standard SuperTrend (7, 3.0) supertrend = ta.supertrend(df['high'], df['low'], df['close'], length=7, multiplier=3.0) print(supertrend.columns) # ['SUPERT_7_3.0', 'SUPERTd_7_3.0', 'SUPERTl_7_3.0', 'SUPERTs_7_3.0'] # Custom SuperTrend parameters supertrend_custom = ta.supertrend(df['high'], df['low'], df['close'], length=10, multiplier=2.5) # Using DataFrame extension df.ta.supertrend(length=7, multiplier=3.0, append=True) # SUPERTd_7_3.0: Direction (1 = bullish, -1 = bearish) df['st_signal'] = 'buy' df.loc[df['SUPERTd_7_3.0'] == -1, 'st_signal'] = 'sell' # Detect trend changes df['st_change'] = df['SUPERTd_7_3.0'].diff() entry_signals = df[df['st_change'] != 0].copy() # Calculate distance from SuperTrend line df['distance_from_st'] = (df['close'] - df['SUPERT_7_3.0']) / df['SUPERT_7_3.0'] * 100 ``` -------------------------------- ### Develop and Register Custom Momentum Indicator in Python Source: https://context7.com/context7/pandas-ta_dev/llms.txt Demonstrates how to define a custom momentum indicator function, validate input series, calculate the indicator, and register it with pandas-ta for direct DataFrame use. It requires pandas and pandas-ta libraries. ```python import pandas as pd import pandas_ta as ta from pandas_ta.utils import get_offset, verify_series def custom_momentum(close, length=None, offset=None, **kwargs): """Custom Momentum Indicator: Rate of Change""" # Validate arguments length = int(length) if length and length > 0 else 10 close = verify_series(close, length) offset = get_offset(offset) if close is None: return # Calculate custom indicator momentum = (close / close.shift(length) - 1) * 100 # Offset if offset != 0: momentum = momentum.shift(offset) # Name and category momentum.name = f"CUSTOM_MOM_{length}" momentum.category = "momentum" return momentum # Use custom indicator df = pd.read_csv('data.csv') custom_result = custom_momentum(df['close'], length=14) df['custom_momentum'] = custom_result # Register custom indicator with pandas-ta ta.custom_momentum = custom_momentum # Now use it like any other indicator df.ta.custom_momentum(length=14, append=True) ``` -------------------------------- ### Calculate Stochastic Oscillator (STOCH) using pandas-ta Source: https://context7.com/context7/pandas-ta_dev/llms.txt Calculates the Stochastic Oscillator, a momentum indicator comparing closing price to its price range over a period. This snippet shows how to calculate both standard and fast versions, append them to the DataFrame, and use them for generating overbought/oversold signals and detecting crossovers. ```python import pandas as pd import pandas_ta as ta df = pd.read_csv('ticker_data.csv') # Standard Stochastic (14, 3, 3) stoch = ta.stoch(df['high'], df['low'], df['close'], k=14, d=3, smooth_k=3) print(stoch.columns) # ['STOCHk_14_3_3', 'STOCHd_14_3_3'] # Fast Stochastic (no smoothing) stoch_fast = ta.stoch(df['high'], df['low'], df['close'], k=14, d=3, smooth_k=1) # Using DataFrame extension df.ta.stoch(k=14, d=3, smooth_k=3, append=True) # Generate overbought/oversold signals df['stoch_signal'] = 'neutral' df.loc[(df['STOCHk_14_3_3'] > 80) & (df['STOCHd_14_3_3'] > 80), 'stoch_signal'] = 'overbought' df.loc[(df['STOCHk_14_3_3'] < 20) & (df['STOCHd_14_3_3'] < 20), 'stoch_signal'] = 'oversold' # Detect %K and %D crossovers df['stoch_crossover'] = 0 df.loc[df['STOCHk_14_3_3'] > df['STOCHd_14_3_3'], 'stoch_crossover'] = 1 df.loc[df['STOCHk_14_3_3'] < df['STOCHd_14_3_3'], 'stoch_crossover'] = -1 df['stoch_cross_signal'] = df['stoch_crossover'].diff() ``` -------------------------------- ### Calculate On Balance Volume (OBV) using pandas-ta Source: https://context7.com/context7/pandas-ta_dev/llms.txt Calculates the On Balance Volume (OBV) indicator, a volume-based tool used to confirm price trends or detect divergences. This snippet shows how to calculate OBV, append it to the DataFrame, and use it for trend analysis and divergence detection. ```python import pandas as pd import pandas_ta as ta df = pd.read_csv('volume_data.csv') # Calculate OBV obv = ta.obv(df['close'], df['volume']) # Using DataFrame extension df.ta.obv(append=True) # Calculate OBV moving average for trend df['obv_sma'] = df['OBV'].rolling(20).mean() # Detect OBV trend df['obv_trend'] = 'neutral' df.loc[df['OBV'] > df['obv_sma'], 'obv_trend'] = 'bullish' df.loc[df['OBV'] < df['obv_sma'], 'obv_trend'] = 'bearish' # Detect divergences (price vs OBV) price_rising = df['close'] > df['close'].shift(20) obv_falling = df['OBV'] < df['OBV'].shift(20) df['bearish_divergence'] = price_rising & obv_falling price_falling = df['close'] < df['close'].shift(20) obv_rising = df['OBV'] > df['OBV'].shift(20) df['bullish_divergence'] = price_falling & obv_rising ``` -------------------------------- ### Calculate Bollinger Bands using pandas-ta Source: https://context7.com/context7/pandas-ta_dev/llms.txt Calculates Bollinger Bands (upper, middle, and lower bands) for a given DataFrame. It can append the results directly to the DataFrame. This snippet also shows how to derive band width, squeeze conditions, and price position relative to the bands. ```python import pandas as pd import pandas_ta as ta df = pd.DataFrame({'close': [10, 11, 12, 11, 10, 12, 13, 14, 13, 12]}) # Using DataFrame extension df.ta.bbands(length=20, std=2, append=True) # Calculate squeeze indicators df['bb_width'] = df['BBU_20_2.0'] - df['BBL_20_2.0'] df['bb_squeeze'] = df['bb_width'] < df['bb_width'].rolling(20).mean() # Identify price position relative to bands df['bb_position'] = 'middle' df.loc[df['close'] > df['BBU_20_2.0'], 'bb_position'] = 'above_upper' df.loc[df['close'] < df['BBL_20_2.0'], 'bb_position'] = 'below_lower' # BBP (Bollinger Band Percentage) already calculated print(f"Current BB %: {df['BBP_20_2.0'].iloc[-1]:.2f}") ``` -------------------------------- ### Calculate Simple Moving Average (SMA) with pandas-ta Source: https://context7.com/context7/pandas-ta_dev/llms.txt Calculates the Simple Moving Average (SMA) of a price series. Supports direct function calls or DataFrame extension. Input is a pandas Series of prices and an integer for the lookback period. Output is a pandas Series of SMA values or appended columns to the DataFrame. ```python import pandas as pd import pandas_ta as ta # Sample OHLCV data df = pd.DataFrame({ 'open': [100, 102, 101, 103, 105], 'high': [102, 104, 103, 105, 107], 'low': [99, 101, 100, 102, 104], 'close': [101, 103, 102, 104, 106], 'volume': [1000, 1200, 900, 1100, 1300] }) # Method 1: Direct function call sma_20 = ta.sma(df['close'], length=20) print(f"SMA(20): {sma_20}") # Method 2: DataFrame extension (appends column to df) df.ta.sma(length=20, append=True) print(df[['close', 'SMA_20']]) # Method 3: Multiple SMAs at once df.ta.sma(length=50, append=True) df.ta.sma(length=200, append=True) ``` -------------------------------- ### Calculate Moving Average Convergence Divergence (MACD) with pandas-ta Source: https://context7.com/context7/pandas-ta_dev/llms.txt Calculates the MACD indicator, which consists of the MACD line, signal line, and histogram. Supports direct function calls or DataFrame extension with customizable parameters for fast, slow, and signal periods. Output includes three pandas Series or appended columns. ```python import pandas as pd import pandas_ta as ta df = pd.read_csv('forex_data.csv') # Standard MACD (12, 26, 9) macd = ta.macd(df['close']) print(macd.columns) # ['MACD_12_26_9', 'MACDh_12_26_9', 'MACDs_12_26_9'] # Custom MACD parametersmacd_custom = ta.macd(df['close'], fast=8, slow=21, signal=5) # Using DataFrame extension df.ta.macd(fast=12, slow=26, signal=9, append=True) # Generate trading signals df['macd_crossover'] = 0 df.loc[df['MACD_12_26_9'] > df['MACDs_12_26_9'], 'macd_crossover'] = 1 # Bullish df.loc[df['MACD_12_26_9'] < df['MACDs_12_26_9'], 'macd_crossover'] = -1 # Bearish # Detect crossover points df['macd_cross_signal'] = df['macd_crossover'].diff() buy_signals = df[df['macd_cross_signal'] == 2] sell_signals = df[df['macd_cross_signal'] == -2] ``` -------------------------------- ### Calculate Relative Strength Index (RSI) with pandas-ta Source: https://context7.com/context7/pandas-ta_dev/llms.txt Calculates the Relative Strength Index (RSI), a momentum oscillator. Supports direct function calls or DataFrame extension. Input is a pandas Series of prices and an optional integer for the lookback period. Output is a pandas Series of RSI values or appended columns, useful for identifying overbought/oversold conditions. ```python import pandas as pd import pandas_ta as ta df = pd.read_csv('crypto_data.csv') # Standard RSI with 14-period length rsi_14 = ta.rsi(df['close'], length=14) # Custom RSI length rsi_21 = ta.rsi(df['close'], length=21) # Using DataFrame extension df.ta.rsi(length=14, append=True) # Identify overbought/oversold conditions df['rsi_signal'] = 'neutral' df.loc[df['RSI_14'] > 70, 'rsi_signal'] = 'overbought' df.loc[df['RSI_14'] < 30, 'rsi_signal'] = 'oversold' # Count signals print(f"Overbought: {(df['rsi_signal'] == 'overbought').sum()}") print(f"Oversold: {(df['rsi_signal'] == 'oversold').sum()}") ``` -------------------------------- ### Calculate Average Directional Index (ADX) using pandas-ta Source: https://context7.com/context7/pandas-ta_dev/llms.txt Calculates the Average Directional Index (ADX) along with its directional indicators (+DI and -DI) to measure trend strength and direction. This snippet shows calculating ADX with different lengths and appending results. It also demonstrates classifying trend strength and direction for combined signal generation. ```python import pandas as pd import pandas_ta as ta df = pd.read_csv('trend_data.csv') # Standard ADX (14 periods) adx = ta.adx(df['high'], df['low'], df['close'], length=14) print(adx.columns) # ['ADX_14', 'DMP_14', 'DMN_14'] # Custom ADX length adx_20 = ta.adx(df['high'], df['low'], df['close'], length=20) # Using DataFrame extension df.ta.adx(length=14, append=True) # Classify trend strength df['trend_strength'] = 'no_trend' df.loc[(df['ADX_14'] >= 25) & (df['ADX_14'] < 50), 'trend_strength'] = 'strong' df.loc[df['ADX_14'] >= 50, 'trend_strength'] = 'very_strong' df.loc[(df['ADX_14'] >= 20) & (df['ADX_14'] < 25), 'trend_strength'] = 'weak' # Determine trend direction df['trend_direction'] = 'neutral' df.loc[df['DMP_14'] > df['DMN_14'], 'trend_direction'] = 'up' df.loc[df['DMP_14'] < df['DMN_14'], 'trend_direction'] = 'down' # Combined signal df['adx_signal'] = df['trend_strength'] + '_' + df['trend_direction'] ``` -------------------------------- ### Calculate Exponential Moving Average (EMA) with pandas-ta Source: https://context7.com/context7/pandas-ta_dev/llms.txt Calculates the Exponential Moving Average (EMA) of a price series, giving more weight to recent data. Supports direct function calls or DataFrame extension. Input is a pandas Series of prices and an optional integer for the lookback period. Output is a pandas Series of EMA values or appended columns. ```python import pandas as pd import pandas_ta as ta df = pd.read_csv('stock_data.csv', parse_dates=['date']) # Calculate EMA with default length (10) ema_default = ta.ema(df['close']) # Calculate EMA with custom length ema_12 = ta.ema(df['close'], length=12) ema_26 = ta.ema(df['close'], length=26) # Using DataFrame extension df.ta.ema(length=12, append=True) df.ta.ema(length=26, append=True) # Calculate crossover signals df['ema_signal'] = 0 df.loc[df['EMA_12'] > df['EMA_26'], 'ema_signal'] = 1 df.loc[df['EMA_12'] < df['EMA_26'], 'ema_signal'] = -1 ``` -------------------------------- ### Calculate Average True Range (ATR) using pandas-ta Source: https://context7.com/context7/pandas-ta_dev/llms.txt Calculates the Average True Range (ATR) indicator, which measures market volatility. This snippet demonstrates calculating ATR with different lengths and appending it to the DataFrame. It also shows practical uses like setting stop-loss levels, position sizing, and detecting volatility regimes. ```python import pandas as pd import pandas_ta as ta df = pd.read_csv('market_data.csv') # Standard ATR with 14-period length atr_14 = ta.atr(df['high'], df['low'], df['close'], length=14) # Custom ATR length atr_10 = ta.atr(df['high'], df['low'], df['close'], length=10) # Using DataFrame extension df.ta.atr(length=14, append=True) # Calculate stop-loss levels (2x ATR) df['long_stop'] = df['close'] - (2 * df['ATR_14']) df['short_stop'] = df['close'] + (2 * df['ATR_14']) # Position sizing based on ATR risk_per_trade = 1000 # $1000 risk per trade df['position_size'] = risk_per_trade / (2 * df['ATR_14']) # Volatility regime detection df['volatility_regime'] = 'normal' atr_ma = df['ATR_14'].rolling(50).mean() df.loc[df['ATR_14'] > 1.5 * atr_ma, 'volatility_regime'] = 'high' df.loc[df['ATR_14'] < 0.5 * atr_ma, 'volatility_regime'] = 'low' ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.