Here's a Pine Script indicator that compares the momentum of a stock with Nifty:
//@version=5
indicator("Stock vs Nifty Momentum", overlay=false)
// Input for stock symbol
stockSymbol = input.symbol("RELIANCE", "Stock Symbol")
// Get stock and Nifty data
stockClose = request.security(stockSymbol, timeframe.period, close)
niftyClose = request.security("NIFTY", timeframe.period, close)
// Calculate momentum (rate of change) for both
momentumPeriod = input.int(14, "Momentum Period")
stockMomentum = ta.roc(stockClose, momentumPeriod)
niftyMomentum = ta.roc(niftyClose, momentumPeriod)
// Calculate relative momentum
relativeMomentum = stockMomentum - niftyMomentum
// Plot the results
plot(relativeMomentum, title="Relative Momentum", color=color.blue)
hline(0, "Zero Line", color=color.gray)
// Add overbought/oversold levels
obLevel = input.float(2, "Overbought Level")
osLevel = input.float(-2, "Oversold Level")
hline(obLevel, "Overbought", color=color.red)
hline(osLevel, "Oversold", color=color.green)
// Generate signals
if ta.crossover(relativeMomentum, obLevel)
label.new(bar_index, high, "Overbought", color=color.red, style=label.style_label_down)
if ta.crossunder(relativeMomentum, osLevel)
label.new(bar_index, low, "Oversold", color=color.green, style=label.style_label_up)
This indicator does the following:
-
It allows you to input a stock symbol to compare against Nifty[1][2].
-
It calculates the momentum (rate of change) for both the selected stock and Nifty using the ta.roc() function[5].
-
It then computes the relative momentum by subtracting Nifty's momentum from the stock's momentum[3].
-
The relative momentum is plotted as a blue line. A zero line is added for reference[9].
-
Overbought and oversold levels are included, which you can adjust in the indicator settings[10].
-
The indicator generates "Overbought" and "Oversold" signals when the relative momentum crosses these levels[14].
To use this indicator:
- Copy the code into the Pine Editor in TradingView.
- Click "Save" and give your indicator a name.
- Click "Add to Chart" to apply the indicator[6].
The indicator will appear in a separate pane below your main chart. When the blue line is above zero, it means the stock has stronger momentum than Nifty. When it's below zero, Nifty has stronger momentum[15].
This indicator can help you identify stocks that are outperforming or underperforming Nifty in terms of momentum, which could be useful for momentum-based trading strategies[2][3].