PROTECTED SOURCE SCRIPT

NSE Pairs Screener-20 pair

90
This advanced Pine Script screener is designed for pairs trading on the National Stock Exchange (NSE) of India. It simultaneously monitors up to 20 stock pairs, calculates key statistical metrics, and provides real-time trading signals based on mean reversion strategies.

Key Features
1. Multi-Pair Analysis

Monitor up to 20 stock pairs simultaneously
Customizable number of pairs to display (1-20)
Pre-configured with popular NSE stock pairs across various sectors

2. Statistical Calculations

Correlation Analysis: Measures the strength of relationship between paired stocks
Z-Score Calculation: Identifies extreme deviations from the mean spread
Cointegration Score: Validates long-term equilibrium relationships
Dynamic Hedge Ratio: Calculates optimal position sizing between pairs

3. Trading Signals

Long Signal: When spread is oversold (Z-score ≤ -2.0)
Short Signal: When spread is overbought (Z-score ≥ 2.0)
Exit Signal: When spread returns to mean (Z-score ≤ 0.5)
Watch Status: Pairs requiring monitoring

4. Automated Alert System

Single comprehensive alert for all qualifying pairs
Customizable alert thresholds for correlation, Z-score, and cointegration
On-chart visual alerts with detailed information
Notification support via TradingView's alert system

5. Visual Display

Clean, color-coded table interface
Adjustable table position (9 positions available)
Highlighted trading opportunities
Real-time metric updates

Configuration Parameters
Screener Settings

Number of Pairs to Display: 1-20 pairs (default: 20)

Calculation Parameters
Parameter Default Range Description Correlation Lookback Period25220-500Historical period for correlation calculation Z-Score SMA Length205-100Moving average length for spread calculation Hedge Ratio Length205-100Period for hedge ratio smoothing Minimum Correlation0.70.5-1.0Threshold for pair validation
Alert Settings
Parameter Default Range Description Alert Correlation Threshold0.70.5-1.0Minimum correlation for alerts Alert Z-Score Threshold2.01.0-3.0Z-score trigger level Alert Cointegration Threshold90%80-99%Minimum cointegration percentage
Display Settings

Table Position: 9 position options (default: middle_center)
Table Background Color: Customizable
Highlight Opportunities: Toggle visual highlighting of trading signals


Pre-Configured Stock Pairs
The script includes 20 carefully selected NSE pairs across various sectors:
Financial Services

RELIANCE / ONGC
HDFCBANK / ICICIBANK
SBIN / PNB
KOTAKBANK / AXISBANK
BAJFINANCE / BAJAJFINSV

Information Technology

TCS / INFY
WIPRO / HCLTECH
TECHM / LTIM

Consumer Goods

ITC / HINDUNILVR
TITAN / TANLA
ASIANPAINT / BERGEPAINT

Telecommunications

BHARTIARTL / IDEA

Automotive

MARUTI / TATAMOTORS

Infrastructure & Industrials

LT / UBL
POWERGRID / NTPC

Pharmaceuticals

SUNPHARMA / CIPLA
DIVISLAB / DRREDDY

Materials

ULTRACEMCO / ACC
UPL / JSWSTEEL

Energy

ADANIENT / ADANIPOWER


🎨 Color-Coded Metrics
Correlation

🟢 Green: ≥ Minimum threshold (strong relationship)
🔴 Red: < Minimum threshold (weak relationship)

Z-Score

🔴 Red: |Z| ≥ 2.0 (extreme deviation - trading opportunity)
🟡 Yellow: 0.5 < |Z| < 2.0 (normal range - watch)
🟢 Green: |Z| ≤ 0.5 (mean reversion - exit signal)

Cointegration

🟢 Green: ≥ 70% (strong cointegration)
🟡 Yellow: 50-70% (moderate cointegration)
🔴 Red: < 50% (weak cointegration)

Status

🟢 Green: Long (buy spread)
🔴 Red: Short (sell spread)
🔵 Blue: Exit (close positions)
⚪ Gray: Watch (monitor)

Validation

🟢 Green: Pass (meets all criteria)
🔴 Red: Fail (doesn't meet criteria)


How It Works
1. Data Collection
The script fetches real-time closing prices for all 20 stock pairs from NSE.
2. Statistical Analysis
For each pair, the script calculates:

Log Returns: Natural logarithm of price changes
Correlation: Pearson correlation coefficient between returns
Hedge Ratio: Price ratio smoothed over specified period
Spread: Price difference adjusted by hedge ratio
Z-Score: Standardized spread deviation

3. Signal Generation
Based on Z-score thresholds:

Z ≥ 2.0: Short spread (short overvalued, long undervalued)
Z ≤ -2.0: Long spread (long overvalued, short undervalued)
|Z| ≤ 0.5: Exit positions (spread reverted to mean)

4. Validation
Pairs must meet criteria:

Correlation ≥ minimum threshold
Valid trading signal (entry or exit)

5. Alert Triggering
Alerts fire when pairs simultaneously meet:

Correlation ≥ alert threshold
|Z-score| ≥ alert threshold
Cointegration ≥ alert threshold


Alert System
The script features a single comprehensive alert that monitors all pairs:

Consolidated Notifications: One alert for all qualifying pairs
Detailed Information: Includes pair names, signal type, and key metrics
Visual Indicators: Red label on chart with complete details
Customizable Thresholds: Adjust sensitivity based on trading style

Alert Message Format
PAIR TRADING OPPORTUNITIES

Pair X: STOCK1/STOCK2
Signal: LONG/SHORT Spread
Z-Score: X.XX
Correlation: X.XXX
Cointegration: XX.X%

Trading Strategy Guide
Entry Rules

Long Spread (Z-score ≤ -2.0):

Buy Stock Y
Sell Stock X (in ratio of hedge ratio)


Short Spread (Z-score ≥ 2.0):

Sell Stock Y
Buy Stock X (in ratio of hedge ratio)



Exit Rules

Close positions when Z-score returns to ±0.5
Set stop-loss at Z-score ±3.0 (extreme deviations)

Risk Management

Only trade pairs with correlation ≥ 0.7
Prefer cointegration scores ≥ 90%
Monitor hedge ratio changes
Diversify across multiple pairs


Customization Options
Adding New Pairs
Simply modify the stock symbol inputs in the respective pair groups (Pair 1 through Pair 20).
Adjusting Sensitivity

Conservative: Increase Z-score threshold to 2.5-3.0
Aggressive: Decrease Z-score threshold to 1.5-2.0
Long-term: Increase lookback period to 500
Short-term: Decrease lookback period to 50-100

Visual Preferences

Change table position to suit your layout
Adjust background colors for better contrast
Toggle opportunity highlighting on/off


Technical Notes
Calculation Method

Uses logarithmic returns for correlation (better statistical properties)
Z-score normalized by standard deviation
Cointegration approximated using correlation strength
Hedge ratio smoothed using simple moving average

Performance Considerations

Calculations update on every bar close
Table displays only on the last bar
Alert checks occur at bar close
Maximum 500 labels supported (more than sufficient)

Limitations

Does not account for transaction costs
Assumes linear relationships between pairs
Historical correlation doesn't guarantee future behaviour
Requires sufficient liquidity in both stocks


Best Practices

Back test Thoroughly: Test parameters on historical data before live trading
Monitor Regularly: Check pairs daily for validation changes
Diversify: Trade multiple pairs to reduce risk
Stay Informed: Be aware of corporate actions, news affecting pairs
Adjust Parameters: Optimize for current market conditions
Use Stop-Losses: Protect against extreme divergences
Track Performance: Maintain trading journal for continuous improvement


Indicator Information

Version: Pine Script v5
Overlay: False (separate pane)
Max Labels: 500
Update Frequency: Every bar close
Compatible Timeframes: All (works best on daily or higher)


Getting Started

Add to Chart: Apply indicator to any NSE stock
Configure Pairs: Adjust stock symbols as needed
Set Parameters: Customize calculation and alert settings
Create Alert: Set up Trading View alert for notifications
Monitor: Watch the table for trading opportunities
Execute: Trade based on validated signals


📞Support & Updates
This script is designed for educational and research purposes. Always:

Conduct thorough back testing
Use proper risk management
Consider transaction costs
Consult with financial advisors
Trade responsibly



Disclaimer: This indicator is for educational purposes only. Past performance does not guarantee future results. Always conduct your own research and risk assessment before trading.

Penafian

Maklumat dan penerbitan adalah tidak dimaksudkan untuk menjadi, dan tidak membentuk, nasihat untuk kewangan, pelaburan, perdagangan dan jenis-jenis lain atau cadangan yang dibekalkan atau disahkan oleh TradingView. Baca dengan lebih lanjut di Terma Penggunaan.