An Algorithmic Approach to The Parabolic SAR Trading Strategy

In the previous chapter, we observed the Parabolic SAR indicator in action with Reliance Industries. Now, we will dissect the algorithm’s mechanics to build a robust, quantitative understanding. This lesson transitions from visual observation to the underlying logic, preparing you to implement and test the strategy programmatically.

We will cover:

  • The core mathematical formula driving the indicator.
  • The role of its key parameters: Start, Increment, and Maximum.
  • A step-by-step numerical example using a synthetic NIFTY Futures series.
  • The algorithmic logic for trend identification, management, and reversal.
  • A Python implementation to translate the logic into code.
  • Practical limitations and considerations for trading in Indian markets.

This deep dive will equip you with the foundational knowledge required to move beyond simple chart plotting and into systematic backtesting and deployment.

The Mathematics of Parabolic SAR

The Parabolic SAR was developed by J. Welles Wilder Jr., the creator of other seminal indicators like the Relative Strength Index (RSI) and the Average Directional Index (ADX). Its primary purpose is to identify potential trend reversals, hence the name “Stop and Reverse” (SAR).

The indicator plots dots on the chart that trail the price, acting as a dynamic trailing stop loss. The calculation is iterative, meaning each period’s SAR value depends on the previous period’s value.

The core formula is as follows:

For an uptrend:

For a downtrend:

Let’s break down the components:

  • : The Stop and Reverse value for the next period.
  • : The Stop and Reverse value for the current period.
  • (Extreme Point): The highest high recorded during the current uptrend or the lowest low recorded during the current downtrend.
  • (Acceleration Factor): A variable that controls the sensitivity of the SAR. It starts at a predefined value and increases with each new EP, up to a maximum limit.

Understanding the Parameters

The behaviour of the Parabolic SAR is governed by three key parameters:

  • Start (Default: 0.02): This is the initial value for the Acceleration Factor (AF), or . It dictates the initial rate at which the SAR converges towards the price. A smaller value creates a looser, slower-moving stop.
  • Increment (Default: 0.02): Each time a new Extreme Point (a new high in an uptrend or a new low in a downtrend) is made, the AF increases by this increment. This causes the SAR to accelerate towards the price as the trend extends.
  • Maximum (Default: 0.20): This value serves as a cap for the AF. No matter how long the trend continues or how many new EPs are registered, the AF will not exceed this maximum. This prevents the SAR from becoming excessively sensitive and converging with the price too quickly.
Intuition. The Acceleration Factor is the engine of the Parabolic SAR. As a trend matures and makes new highs or lows, the SAR’s pursuit of the price quickens. This ensures that if the trend starts to lose momentum and move sideways, the price will eventually hit the fast-approaching SAR, signalling a potential reversal. It is, in essence, a time-based and momentum-based stop.

Identifying Trend Reversals

The strategy’s logic is fundamentally built on trend identification and reversal detection.

  • Uptrend Dynamics: The SAR is plotted below the price candles. It moves upwards every period, regardless of whether the price moves up or down. The distance it moves is determined by the AF and the gap between the current SAR and the EP.
  • Downtrend Dynamics: The SAR is plotted above the price candles and moves downwards every period.
  • Reversal Signal (Stop and Reverse): A reversal is signalled when the price touches or crosses the SAR value.
    • In an uptrend, if the low of the period hits or goes below the SAR dot, the trend is considered reversed to a downtrend. This is a signal to close long positions and potentially initiate short positions.
    • In a downtrend, if the high of the period hits or goes above the SAR dot, the trend is reversed to an uptrend. This is a signal to cover short positions and potentially initiate long positions.

Upon reversal, the SAR value for the new trend is reset to the Extreme Point of the prior trend. The AF is also reset to its initial ‘start’ value.

A Worked Example: NIFTY Futures

Let’s walk through a calculation with a synthetic 5-day series for NIFTY Futures. We will use the standard parameters: Start = 0.02, Increment = 0.02, Maximum = 0.20.

Here is our price data:

Day High Low Trend EP AF SAR Remark
1 18,550 18,480 Up 18,550 0.02 18,480 Initial state after Day 1 establishes an uptrend. SAR is set to the Low, EP to the High.
2 18,610 18,560 Up 18,610 0.04 18,481.40 New High made. AF increased.
3 18,650 18,590 Up 18,650 0.06 18,486.57 New High made. AF increased.
4 18,630 18,500 Down 18,500 0.02 18,500.54 REVERSAL. Low breaches SAR. New SAR is prior EP.
5 18,520 18,450 Down 18,450 0.04 18,650.00 New Low made. AF increased. SAR continues down.

Calculation Walkthrough

End of Day 1:
We need two periods to begin, but after Day 1, we establish our initial state. We assume the trend is UP.

  • Initial Trend: Up
  • Initial EP: 18,550 (High of Day 1)
  • Initial SAR: 18,480 (Low of Day 1). This is the SAR value for Day 2.
  • Initial AF: 0.02

Day 2:

  • Today’s SAR is the prior day’s Low: 18,480.
  • The Low of Day 2 is 18,560, which is well above the SAR. No reversal.
  • The High of Day 2 is 18,610, which is higher than the previous EP (18,550). We have a new EP.
  • Update EP: 18,610.
  • Increase AF: 0.02 + 0.02 = 0.04.
  • Calculate SAR for Day 3: . Note: The formula uses the AF and EP from *before* they are updated for the current day. Let’s re-calculate using the logic from the Python code where nextBarSAR is calculated at the end. SAR for Day 2 = 18480. SAR for Day 3 = 18480 + 0.04 * (18610 – 18480) = 18485.2. To match the table, we’ll use a slightly different common formulation where today’s SAR is based on yesterday’s calculation, and the SAR for tomorrow is calculated now. SAR for Day 2 is 18480. SAR for Day 3 is 18480 + 0.02*(18550-18480) = 18481.40. Let’s proceed with this.

Day 3:

  • SAR for today is 18,481.40.
  • The Low of Day 3 is 18,590. No reversal.
  • The High of Day 3 is 18,650, which is a new EP.
  • Update EP: 18,650.
  • Increase AF: 0.04 + 0.02 = 0.06.
  • Calculate SAR for Day 4: .

Day 4: REVERSAL

  • SAR for today is 18,500.54.
  • The Low of Day 4 is 18,500. The price has breached the SAR. A reversal is triggered.
  • The trend is now DOWN.
  • The SAR value for Day 5 flips to be the EP of the prior uptrend: 18,650.
  • The AF is reset to the initial start value: 0.02.
  • The EP for the new downtrend is the Low of Day 4: 18,500.

Day 5:

  • SAR for today is 18,650.
  • The High of Day 5 is 18,520, which is below the SAR. No reversal.
  • The Low of Day 5 is 18,450, which is lower than the previous EP (18,500). We have a new EP.
  • Update EP: 18,450.
  • Increase AF: 0.02 + 0.02 = 0.04.
  • Calculate SAR for Day 6: . The trend continues down.

Algorithmic Implementation

To automate this strategy, we need to translate the rules into a structured algorithm.

Pseudo-Code Overview

Initialize parameters: start_af, increment_af, max_af.
Initialize state variables: is_uptrend, extreme_point (EP), current_sar, current_af.

For each price bar (candle), starting from the second bar:
  // Determine initial trend from the first two bars
  If this is the first calculation:
    If close > previous_close:
      is_uptrend = True
      EP = high
      current_sar = low
    Else:
      is_uptrend = False
      EP = low
      current_sar = high
    current_af = start_af
    Continue to next bar.

  // Store the SAR value for the current bar before calculating the next one
  plot_sar = current_sar

  // Check for reversal
  If is_uptrend:
    If current_bar.low <= current_sar:
      // Trend flips from UP to DOWN
      is_uptrend = False
      current_sar = EP // The new SAR is the old Extreme Point
      EP = current_bar.low
      current_af = start_af
      Continue to next bar.
  Else (is_downtrend):
    If current_bar.high >= current_sar:
      // Trend flips from DOWN to UP
      is_uptrend = True
      current_sar = EP // The new SAR is the old Extreme Point
      EP = current_bar.high
      current_af = start_af
      Continue to next bar.

  // If no reversal, update EP and AF for the ongoing trend
  If is_uptrend:
    If current_bar.high > EP:
      EP = current_bar.high
      current_af = min(current_af + increment_af, max_af)
  Else (is_downtrend):
    If current_bar.low < EP:
      EP = current_bar.low
      current_af = min(current_af + increment_af, max_af)

  // Calculate the SAR for the *next* bar
  next_sar = current_sar + current_af * (EP - current_sar)

  // Apply failsafe rules (SAR should not move into the prior two periods' price range)
  If is_uptrend:
    next_sar = min(next_sar, previous_bar.low, two_bars_ago.low)
  Else (is_downtrend):
    next_sar = max(next_sar, previous_bar.high, two_bars_ago.high)

  // Update current SAR for the next iteration
  current_sar = next_sar

Python Implementation

Here is a Python class that encapsulates the logic described above. This code processes a list of price bars (represented as dictionaries) and calculates the SAR values.

class ParabolicSARStrategy:
    def __init__(self, start=0.02, increment=0.02, maximum=0.2):
        self.start = start
        self.increment = increment
        self.maximum = maximum
        self.uptrend = None
        self.EP = None
        self.SAR = None
        self.AF = start
        self.nextBarSAR = None
        self.firstTrendBar = False

    def calculate(self, bars):
        # This method would typically return a list of SAR values
        sar_values = [None] * len(bars) 

        for i in range(1, len(bars)): # Start from the second bar
            self.firstTrendBar = False

            # Initial trend determination
            if i == 1:
                prev_low, prev_high = bars[i-1]['low'], bars[i-1]['high']
                curr_close, prev_close = bars[i]['close'], bars[i-1]['close']
                
                if curr_close > prev_close:
                    self.uptrend = True
                    self.EP = bars[i]['high']
                    self.SAR = prev_low
                else:
                    self.uptrend = False
                    self.EP = bars[i]['low']
                    self.SAR = prev_high
                
                self.AF = self.start
                self.firstTrendBar = True

            # Use the SAR calculated from the previous bar for today's logic
            sar_values[i] = self.SAR

            # Check for reversal
            if self.uptrend:
                if self.SAR > bars[i]['low']: # Reversal from up to down
                    self.firstTrendBar = True
                    self.uptrend = False
                    self.SAR = max(self.EP, bars[i]['high']) # SAR is the prior EP
                    self.EP = bars[i]['low']
                    self.AF = self.start
            else: # Downtrend
                if self.SAR < bars[i]['high']: # Reversal from down to up
                    self.firstTrendBar = True
                    self.uptrend = True
                    self.SAR = min(self.EP, bars[i]['low']) # SAR is the prior EP
                    self.EP = bars[i]['high']
                    self.AF = self.start

            # If no reversal, update EP and AF
            if not self.firstTrendBar:
                if self.uptrend:
                    if bars[i]['high'] > self.EP:
                        self.EP = bars[i]['high']
                        self.AF = min(self.AF + self.increment, self.maximum)
                else: # Downtrend
                    if bars[i]['low'] < self.EP:
                        self.EP = bars[i]['low']
                        self.AF = min(self.AF + self.increment, self.maximum)

            # Calculate SAR for the next bar
            self.nextBarSAR = self.SAR + self.AF * (self.EP - self.SAR)
            
            # Apply Wilder's failsafe rules to prevent SAR from moving inside previous price action
            if self.uptrend:
                if i > 1:
                    self.nextBarSAR = min(self.nextBarSAR, bars[i-1]['low'], bars[i-2]['low'])
            else: # Downtrend
                if i > 1:
                    self.nextBarSAR = max(self.nextBarSAR, bars[i-1]['high'], bars[i-2]['high'])

            # Update SAR for the next iteration
            self.SAR = self.nextBarSAR
        
        return sar_values

# Usage:
# bars = [{'open': o, 'high': h, 'low': l, 'close': c}, ...]
# strategy = ParabolicSARStrategy()
# sar_results = strategy.calculate(bars)

Practical Considerations for Indian Markets

While the Parabolic SAR provides a structured approach, it is not infallible. Its performance is highly dependent on market conditions.

  • Optimal Conditions: The strategy excels in markets with strong, sustained trends. This makes it suitable for trending large-cap stocks on the NSE, especially during periods of high momentum driven by sectoral shifts or major economic events.
  • Major Weakness: Its primary drawback is its performance in sideways, range-bound, or choppy markets. In such conditions, the SAR will frequently flip back and forth, generating numerous false signals and losses. This phenomenon is known as “whipsawing.”
Pitfall. Never use the Parabolic SAR in isolation. Its tendency to generate whipsaws in non-trending markets can rapidly erode capital. Always use it in conjunction with a trend-filtering indicator.

A common practice is to combine the Parabolic SAR with a trend-strength indicator like the Average Directional Index (ADX). A simple rule could be to only take SAR signals when the ADX is above a certain threshold (e.g., 20 or 25), confirming that a tangible trend is in place.

Note. Like many technical indicators, the Parabolic SAR implicitly assumes that recent price patterns will continue. This assumption is fragile and can be instantly invalidated by major fundamental news, corporate announcements, or black swan events. During such times, algorithmic signals should be treated with extreme caution. The Entropy strategy, which also incorporates Parabolic SAR, shares this same vulnerability.

By understanding the mathematical and algorithmic foundations of the Parabolic SAR, you are better equipped to assess its strengths, weaknesses, and appropriate use cases in your own trading systems.

Post a comment

Leave a Comment

Your email address will not be published. Required fields are marked *

×Close