### Install PatternPy using Git Clone Source: https://github.com/keithorange/patternpy/blob/main/README.md This command clones the PatternPy repository from GitHub. This method is suitable for direct use or development, requiring Git to be installed on the system. ```bash git clone https://github.com/keithorange/PatternPy ``` -------------------------------- ### Complete Integration Example: Trading Signal Generation (Python) Source: https://context7.com/keithorange/patternpy/llms.txt This comprehensive example demonstrates how to combine multiple pattern detection functions from the `tradingpatterns` library to perform technical analysis and generate trading signals. It loads daily market data, applies various pattern detectors, aggregates bullish and bearish signals, defines a trading strategy with buy/sell actions, and sets up risk management parameters like stop-loss and take-profit levels. ```python import pandas as pd from tradingpatterns.tradingpatterns import ( detect_head_shoulder, detect_multiple_tops_bottoms, calculate_support_resistance, detect_triangle_pattern, detect_wedge, detect_channel, detect_double_top_bottom, detect_trendline ) # Load real market data df = pd.read_csv('AAPL_daily.csv') df = df[['Open', 'High', 'Low', 'Close', 'Volume']] # Apply all pattern detections df = detect_head_shoulder(df, window=5) df = detect_multiple_tops_bottoms(df, window=5) df = calculate_support_resistance(df, window=10) df = detect_triangle_pattern(df, window=5) df = detect_wedge(df, window=5) df = detect_channel(df, window=5) df = detect_double_top_bottom(df, window=5, threshold=0.03) df = detect_trendline(df, window=3) # Generate composite trading signals df['bullish_signals'] = 0 df['bearish_signals'] = 0 # Count bullish patterns df.loc[df['head_shoulder_pattern'] == 'Inverse Head and Shoulder', 'bullish_signals'] += 1 df.loc[df['multiple_top_bottom_pattern'] == 'Multiple Bottom', 'bullish_signals'] += 1 df.loc[df['triangle_pattern'] == 'Ascending Triangle', 'bullish_signals'] += 1 df.loc[df['double_pattern'] == 'Double Bottom', 'bullish_signals'] += 1 df.loc[df['Close'] > df['support'], 'bullish_signals'] += 1 # Count bearish patterns df.loc[df['head_shoulder_pattern'] == 'Head and Shoulder', 'bearish_signals'] += 1 df.loc[df['multiple_top_bottom_pattern'] == 'Multiple Top', 'bearish_signals'] += 1 df.loc[df['triangle_pattern'] == 'Descending Triangle', 'bearish_signals'] += 1 df.loc[df['double_pattern'] == 'Double Top', 'bearish_signals'] += 1 df.loc[df['Close'] < df['resistance'], 'bearish_signals'] += 1 # Create trading strategy df['action'] = 'HOLD' df.loc[df['bullish_signals'] >= 3, 'action'] = 'BUY' df.loc[df['bearish_signals'] >= 3, 'action'] = 'SELL' # Risk management with support/resistance df['stop_loss'] = df['support'] * 0.97 # 3% below support df['take_profit'] = df['resistance'] * 1.03 # 3% above resistance # Filter actionable signals signals = df[df['action'] != 'HOLD'][['Close', 'action', 'bullish_signals', 'bearish_signals', 'stop_loss', 'take_profit']] print(f"\nTrading signals:\n{signals.tail(10)}") # Pattern summary statistics pattern_columns = ['head_shoulder_pattern', 'multiple_top_bottom_pattern', 'triangle_pattern', 'wedge_pattern', 'channel_pattern', 'double_pattern'] for col in pattern_columns: if col in df.columns: count = df[col].notna().sum() print(f"{col}: {count} occurrences") ``` -------------------------------- ### Calculate Support and Resistance Levels Source: https://context7.com/keithorange/patternpy/llms.txt Calculates dynamic support and resistance levels based on rolling window statistics (mean ± 2 standard deviations) of price data. Requires OHLCV data and returns 'support' and 'resistance' columns with calculated price levels. ```python from tradingpatterns.tradingpatterns import calculate_support_resistance # Prepare data df = pd.DataFrame({ 'High': [105.5, 106.2, 107.8, 108.1, 106.9, 107.5], 'Low': [102.1, 103.5, 104.2, 105.0, 103.8, 104.5], 'Close': [104.2, 105.1, 106.5, 107.2, 105.8, 106.3] }) # Calculate support and resistance with 3-period rolling window df = calculate_support_resistance(df, window=3) # Results in two new columns with float price levels: # - 'support': Mean(Low) - 2*StdDev(Low) # - 'resistance': Mean(High) + 2*StdDev(High) print(df[['Close', 'support', 'resistance']]) # Example output: # Close support resistance # 0 104.2 NaN NaN # 1 105.1 NaN NaN # 2 106.5 98.8523 110.3477 # 3 107.2 100.2156 111.8844 # Use for stop-loss placement df['stop_loss'] = df['support'] * 0.98 # 2% below support df['take_profit'] = df['resistance'] * 1.02 # 2% above resistance ``` -------------------------------- ### Calculate Trendline Support and Resistance in Python Source: https://context7.com/keithorange/patternpy/llms.txt Calculates dynamic trendlines using linear regression on closing prices, providing support in uptrends and resistance in downtrends. This function can be slow on large datasets due to its iterative nature. ```python from tradingpatterns.tradingpatterns import detect_trendline # Data showing clear trend df = pd.DataFrame({ 'Close': [100, 102, 104, 103, 105, 107, 106, 108, 110] }) # Calculate trendline with window=2 (fits line to previous 2 points) # Warning: Uses iterative loop, can be slow on large datasets df = detect_trendline(df, window=3) # Creates four new columns: # - 'slope': Regression slope (positive = uptrend, negative = downtrend) # - 'intercept': Y-intercept of regression line # - 'support': Trendline value when slope > 0 # - 'resistance': Trendline value when slope < 0 print(df[['Close', 'slope', 'support', 'resistance']]) # Use trendlines for entry/exit df['above_support'] = df['Close'] > df['support'] df['below_resistance'] = df['Close'] < df['resistance'] # Buy when price touches support in uptrend buy_opportunities = df[(df['slope'] > 0) & (df['Close'] <= df['support'] * 1.01)] print(f"Buy opportunities: {len(buy_opportunities)}") ``` -------------------------------- ### Identify Head and Shoulders Pattern using PatternPy Source: https://github.com/keithorange/patternpy/blob/main/README.md This Python snippet demonstrates how to use the PatternPy library to identify Head and Shoulders patterns in stock data. It requires Pandas for data manipulation and the specific function from the patternpy.tradingpatterns module. The output is a DataFrame with an added column indicating the detected pattern. ```python from patternpy.tradingpatterns import head_and_shoulders # Have price data (OCHLV dataframe) df = pd.Dataframe(stock_data) # Apply pattern indicator screener df = head_and_shoulders(df) # New column `head_shoulder_pattern` is created with entries containing either: NaN, 'Head and Shoulder' or 'Inverse Head and Shoulder' print(df) ``` -------------------------------- ### Detect Double Top and Bottom Patterns in Python Source: https://context7.com/keithorange/patternpy/llms.txt Identifies double top (bearish reversal) and double bottom (bullish reversal) patterns. It uses a window and threshold parameter to define the pattern and outputs to the 'double_pattern' column. ```python from tradingpatterns.tradingpatterns import detect_double_top_bottom # Sample data with double top formation df = pd.DataFrame({ 'High': [100, 110, 105, 109, 100, 95, 90], 'Low': [95, 105, 100, 104, 95, 90, 85], 'Close': [98, 108, 103, 107, 98, 93, 88] }) # Detect double patterns with window and threshold # threshold=0.05 means peaks/troughs within 5% range are considered df = detect_double_top_bottom(df, window=3, threshold=0.05) # Column 'double_pattern' contains: # - NaN (no pattern) # - 'Double Top' (bearish reversal signal) # - 'Double Bottom' (bullish reversal signal) print(df[['High', 'Low', 'double_pattern']].dropna()) # Generate trading signals with confirmation df['short_signal'] = df['double_pattern'] == 'Double Top' df['long_signal'] = df['double_pattern'] == 'Double Bottom' # Wait for breakout confirmation for idx in df[df['short_signal']].index: if idx + 1 < len(df): neckline = df.loc[idx, 'Low'] if df.loc[idx + 1, 'Close'] < neckline: print(f"Double top confirmed - short at {df.loc[idx+1, 'Close']}") ``` -------------------------------- ### Detect Multiple Tops and Bottoms Patterns Source: https://context7.com/keithorange/patternpy/llms.txt Identifies horizontal consolidation patterns (multiple tops and bottoms) where price tests the same level multiple times. Requires a DataFrame with 'High', 'Low', 'Close' columns and returns a 'multiple_top_bottom_pattern' column indicating 'Multiple Top' or 'Multiple Bottom'. ```python from tradingpatterns.tradingpatterns import detect_multiple_tops_bottoms # Load your data df = pd.read_csv('stock_prices.csv') # Must have High, Low, Close columns # Detect multiple tops/bottoms with adjustable window df = detect_multiple_tops_bottoms(df, window=5) # Access results # Column 'multiple_top_bottom_pattern' contains: # - NaN (no pattern) # - 'Multiple Top' (resistance level being tested) # - 'Multiple Bottom' (support level being tested) # Filter for detected patterns patterns = df[df['multiple_top_bottom_pattern'].notna()] print(patterns[['Close', 'multiple_top_bottom_pattern']]) # Use in trading logic for idx, row in df.iterrows(): if row['multiple_top_bottom_pattern'] == 'Multiple Top': print(f"Potential short opportunity at {row['Close']}") elif row['multiple_top_bottom_pattern'] == 'Multiple Bottom': print(f"Potential long opportunity at {row['Close']}") ``` -------------------------------- ### Detect Triangle Patterns Source: https://context7.com/keithorange/patternpy/llms.txt Identifies ascending and descending triangle consolidation patterns using a rolling window approach. Requires OHLCV data and populates a 'triangle_pattern' column in the DataFrame with pattern labels or NaN if no pattern is detected. ```python from tradingpatterns.tradingpatterns import detect_triangle_pattern # Sample data showing triangle formation df = pd.DataFrame({ 'High': [110, 109, 110, 109, 110, 108, 109, 108], 'Low': [100, 102, 103, 104, 105, 105, 106, 106], 'Close': [105, 106, 107, 107, 108, 107, 108, 107] }) # Detect triangle patterns df = detect_triangle_pattern(df, window=3) # Column 'triangle_pattern' contains: # - NaN (no pattern) ``` -------------------------------- ### Detect Head and Shoulder Patterns Source: https://context7.com/keithorange/patternpy/llms.txt Identifies classic head and shoulder reversal patterns and their inverse variants using rolling window comparisons. Requires OHLCV data and returns a DataFrame with a 'head_shoulder_pattern' column indicating 'Head and Shoulder' or 'Inverse Head and Shoulder'. ```python import pandas as pd from tradingpatterns.tradingpatterns import detect_head_shoulder # Prepare OHLCV data stock_data = { 'Open': [90, 85, 80, 90, 85, 80, 75, 80, 85, 90], 'High': [95, 90, 85, 95, 90, 85, 80, 85, 90, 95], 'Low': [80, 75, 70, 80, 75, 70, 65, 70, 75, 80], 'Close': [90, 85, 80, 90, 85, 80, 75, 80, 85, 90], 'Volume': [1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000] } df = pd.DataFrame(stock_data) # Detect head and shoulder patterns with 3-period window df = detect_head_shoulder(df, window=3) # Output: New column 'head_shoulder_pattern' contains: # - NaN (no pattern detected) # - 'Head and Shoulder' (bearish reversal) # - 'Inverse Head and Shoulder' (bullish reversal) print(df[['High', 'Low', 'head_shoulder_pattern']].dropna()) # Example output: # High Low head_shoulder_pattern # 3 95 80 Head and Shoulder ``` -------------------------------- ### Detect Wedge Patterns in Python Source: https://context7.com/keithorange/patternpy/llms.txt Detects converging wedge patterns where both highs and lows trend in the same direction, indicating trend continuation or reversal. The output is stored in the 'wedge_pattern' column. ```python from tradingpatterns.tradingpatterns import detect_wedge # Data showing wedge formation df = pd.DataFrame({ 'High': [100, 101, 102, 103, 104, 105, 106], 'Low': [95, 96, 97, 98, 99, 100, 101], 'Close': [98, 99, 100, 101, 102, 103, 104] }) # Detect wedge patterns with window size df = detect_wedge(df, window=3) # Column 'wedge_pattern' contains: # - NaN (no pattern) # - 'Wedge Up' (rising wedge, both highs and lows rising) # - 'Wedge Down' (falling wedge, both highs and lows falling) print(df[['High', 'Low', 'wedge_pattern']].dropna()) # Trading strategy based on wedges for idx, row in df.iterrows(): if row['wedge_pattern'] == 'Wedge Up': # Rising wedge often bearish reversal print(f"Watch for bearish breakout at row {idx}") elif row['wedge_pattern'] == 'Wedge Down': # Falling wedge often bullish reversal print(f"Watch for bullish breakout at row {idx}") ``` -------------------------------- ### Pivot Point Detection (Python) Source: https://context7.com/keithorange/patternpy/llms.txt Identifies higher highs, lower lows, higher lows, and lower highs to track market structure and trend changes. The `find_pivots` function from the `tradingpatterns` library analyzes high and low price data to mark these significant points. The output column 'signal' indicates the type of pivot detected. ```python from tradingpatterns.tradingpatterns import find_pivots # Prepare data (NOTE: Uses lowercase 'high' and 'low' columns) df = pd.DataFrame({ 'high': [100, 102, 101, 103, 102, 105, 104, 103], 'low': [95, 97, 96, 98, 97, 100, 99, 98] }) # Find pivot points df = find_pivots(df) # Column 'signal' contains: # - '' (empty string, no pivot) # - 'HH' (Higher High - bullish continuation) # - 'LL' (Lower Low - bearish continuation) # - 'LH' (Lower High - bearish reversal) # - 'HL' (Higher Low - bullish reversal) print(df[['high', 'low', 'signal']]) # Analyze market structure hh_count = len(df[df['signal'] == 'HH']) ll_count = len(df[df['signal'] == 'LL']) lh_count = len(df[df['signal'] == 'LH']) hl_count = len(df[df['signal'] == 'HL']) # Determine trend if (hh_count + hl_count) > (ll_count + lh_count): trend = "UPTREND" else: trend = "DOWNTREND" print(f"Market structure: {trend}") print(f"HH: {hh_count}, LL: {ll_count}, LH: {lh_count}, HL: {hl_count}") # Filter for trend reversals reversals = df[df['signal'].isin(['LH', 'HL'])] print(f"\nPotential reversals:\n{reversals}") ``` -------------------------------- ### Detect Channel Patterns in Python Source: https://context7.com/keithorange/patternpy/llms.txt Identifies price channels where the stock moves within parallel trend lines. This function uses a hardcoded 10% range threshold and outputs to the 'channel_pattern' column. ```python from tradingpatterns.tradingpatterns import detect_channel # Data showing channel movement df = pd.DataFrame({ 'High': [105, 106, 107, 108, 109, 110], 'Low': [100, 101, 102, 103, 104, 105], 'Close': [103, 104, 105, 106, 107, 108] }) # Detect channels (uses hardcoded 10% range threshold) df = detect_channel(df, window=3) # Column 'channel_pattern' contains: # - NaN (no pattern) # - 'Channel Up' (upward trending channel) # - 'Channel Down' (downward trending channel) print(df[['High', 'Low', 'channel_pattern']]) # Trade within channel boundaries df['buy_signal'] = (df['channel_pattern'] == 'Channel Up') & (df['Close'] < df['Low'] * 1.02) df['sell_signal'] = (df['channel_pattern'] == 'Channel Up') & (df['Close'] > df['High'] * 0.98) print(df[df['buy_signal'] | df['sell_signal']]) ``` -------------------------------- ### Detect Ascending and Descending Triangles in Python Source: https://context7.com/keithorange/patternpy/llms.txt Identifies Ascending and Descending Triangles, which are common chart patterns indicating potential price movements. This function relies on the 'triangle_pattern' column generated by the library. ```python from tradingpatterns.tradingpatterns import detect_triangle # Sample DataFrame with price data df = pd.DataFrame({ 'High': [100, 102, 101, 103, 105, 104, 106], 'Low': [95, 97, 96, 98, 100, 99, 101], 'Close': [98, 101, 99, 102, 103, 102, 105] }) # Detect triangle patterns df = detect_triangle(df, window=3) # 'triangle_pattern' column contains: # - NaN (no pattern) # - 'Ascending Triangle' (bullish, rising lows with flat highs) # - 'Descending Triangle' (bearish, falling highs with flat lows) print(df[['High', 'Low', 'Close', 'triangle_pattern']]) # Filter and analyze ascdescending = df[df['triangle_pattern'] == 'Ascending Triangle'] descending = df[df['triangle_pattern'] == 'Descending Triangle'] print(f"Found {len(ascdescending)} ascending and {len(descending)} descending triangles") ``` -------------------------------- ### Calculate Trendline Strength (Python) Source: https://context7.com/keithorange/patternpy/llms.txt Calculates the strength of a trendline based on the slope and closing price. It then filters for trends with a strength above a specified threshold. This can be useful for identifying strong directional movements in the market. ```python df['trend_strength'] = abs(df['slope']) / df['Close'] strong_trends = df[df['trend_strength'] > 0.01] print(f"Strong trends: {len(strong_trends)}") ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.