figured it out

df.loc[a, 'PSAR'] = df.loc[a-1, 'PSAR'] + (df.loc[a-1, 'AF']*(df.loc[a-1, 'EP']-df.loc[a-1, 'PSAR'])) 

Should be df.loc[a, 'PSAR'] = df.loc[a-1, 'PSAR'] + (df.loc[a-1, 'AF']*(df.loc[a-1, 'PSAR']-df.loc[a-1, 'EP']))

last two variables transposed!

now I can clean up the function and make it better.

Answer from Greg D on Stack Overflow
🌐
QuantInsti
blog.quantinsti.com › parabolic-sar
Parabolic SAR: Formula, Calculation, and Python Code
December 26, 2023 - Import the required libraries. This function uses the yfinance library to download historical price data for a given stock (ticker) within a specified date range (start_date to end_date). This function implements the Parabolic SAR trading strategy.
Top answer
1 of 4
4

figured it out

df.loc[a, 'PSAR'] = df.loc[a-1, 'PSAR'] + (df.loc[a-1, 'AF']*(df.loc[a-1, 'EP']-df.loc[a-1, 'PSAR'])) 

Should be df.loc[a, 'PSAR'] = df.loc[a-1, 'PSAR'] + (df.loc[a-1, 'AF']*(df.loc[a-1, 'PSAR']-df.loc[a-1, 'EP']))

last two variables transposed!

now I can clean up the function and make it better.

2 of 4
0

I updated the script, fixed the bug with the increasing PSAR value and also overlapping PSAR with high/low price. Now this function gives the exact same PSAR like TradingView.

def PSAR(df, af=0.02, max=0.2):
df.loc[0, 'AF'] = 0.02
df.loc[0, 'PSAR'] = df.loc[0, 'low']
df.loc[0, 'EP'] = df.loc[0, 'high']
df.loc[0, 'PSARdir'] = "bull"

for a in range(1, len(df)):
    if df.loc[a-1, 'PSARdir'] == 'bull':
        df.loc[a, 'PSAR'] = df.loc[a-1, 'PSAR'] + (df.loc[a-1, 'AF']*(df.loc[a-1, 'EP']-df.loc[a-1, 'PSAR']))
        df.loc[a, 'PSARdir'] = "bull"

        if df.loc[a, 'low'] < df.loc[a-1, 'PSAR'] or df.loc[a, 'low'] < df.loc[a, 'PSAR']:
            df.loc[a, 'PSARdir'] = "bear"
            df.loc[a, 'PSAR'] = df.loc[a-1, 'EP']
            df.loc[a, 'EP'] = df.loc[a-1, 'low']
            df.loc[a, 'AF'] = af
        else:
            if df.loc[a, 'high'] > df.loc[a-1, 'EP']:
                df.loc[a, 'EP'] = df.loc[a, 'high']
                if df.loc[a-1, 'AF'] <= 0.18:
                    df.loc[a, 'AF'] =df.loc[a-1, 'AF'] + af
                else:
                    df.loc[a, 'AF'] = df.loc[a-1, 'AF']
            elif df.loc[a, 'high'] <= df.loc[a-1, 'EP']:
                df.loc[a, 'AF'] = df.loc[a-1, 'AF']
                df.loc[a, 'EP'] = df.loc[a-1, 'EP']

    elif df.loc[a-1, 'PSARdir'] == 'bear':
        df.loc[a, 'PSAR'] = df.loc[a-1, 'PSAR'] - (df.loc[a-1, 'AF']*(df.loc[a-1, 'PSAR']-df.loc[a-1, 'EP']))
        df.loc[a, 'PSARdir'] = "bear"

        if df.loc[a, 'high'] > df.loc[a-1, 'PSAR'] or df.loc[a, 'high'] > df.loc[a, 'PSAR']:
            df.loc[a, 'PSARdir'] = "bull"
            df.loc[a, 'PSAR'] = df.loc[a-1, 'EP']
            df.loc[a, 'EP'] = df.loc[a-1, 'high']
            df.loc[a, 'AF'] = af
        else:
            if df.loc[a, 'low'] < df.loc[a-1, 'EP']:
                df.loc[a, 'EP'] = df.loc[a, 'low']
                if df.loc[a-1, 'AF'] < max:
                    df.loc[a, 'AF'] = df.loc[a-1, 'AF'] + af
                else:
                    df.loc[a, 'AF'] = df.loc[a-1, 'AF']

            elif df.loc[a, 'low'] >= df.loc[a-1, 'EP']:
                df.loc[a, 'AF'] = df.loc[a-1, 'AF']
                df.loc[a, 'EP'] = df.loc[a-1, 'EP']
return df
Discussions

How to use Parabolic SAR indicator? - QuantConnect.com
User seeks simple Python algorithm for Parabolic SAR indicator to buy when trend is up and sell when down. More on quantconnect.com
🌐 quantconnect.com
Help with a parabolic SAR

Maybe post what your algorithm to calculate the parabolic SAR is?

Have you compared your derivation to the reference? Is it possible that IG has tweaked or made theirs custom?

More on reddit.com
🌐 r/Python
1
0
July 25, 2018
pandas - Parabolic SAR calculated in Python seems to be reversed - Stack Overflow
When I use Pandas and the TA-lib library, my Parabolic SAR line is reversed. This is my CSV records: import pandas as pd import matplotlib.pyplot as plt import talib data = pd.read_csv("/cont... More on stackoverflow.com
🌐 stackoverflow.com
Stop Trading with backtrader in Python

Yeah that title is terrible. Is “Stop Trading” even a term anyone uses? I’ve always hear Stop Order

More on reddit.com
🌐 r/algotrading
8
40
February 1, 2018
🌐
Raposa
raposa.trade › blog › the-complete-guide-to-calculating-the-parabolic-sar-in-python
The Complete Guide to Calculating the Parabolic SAR in Python — Raposa
January 24, 2022 - You're just taking some min/max values and updating SAR and AF at each time step. Despite that, the entire algorithm is a bit complicated because of all of the if/else statements. We have a class called PSAR that allows you to adjust the initialization for the acceleration factor, its step size, and the maximum acceleration factor to calculate the Parabolic SAR.
🌐
GitHub
github.com › je-suis-tm › quant-trading › blob › master › Parabolic SAR backtest.py
quant-trading/Parabolic SAR backtest.py at master · je-suis-tm/quant-trading
Python quantitative trading strategies including VIX Calculator, Pattern Recognition, Commodity Trading Advisor, Monte Carlo, Options Straddle, Shooting Star, London Breakout, Heikin-Ashi, Pair Trading, RSI, Bollinger Bands, Parabolic SAR, Dual Thrust, Awesome, MACD - quant-trading/Parabolic SAR backtest.py at master · je-suis-tm/quant-trading
Author   je-suis-tm
🌐
Medium
kaabar-sofien.medium.com › how-to-really-use-this-underrated-technical-indicator-in-trading-4d2e2d613ec3
How Python and Parabolic SAR Improved My Stock Trading | by Sofien Kaabar, CFA | Medium
August 16, 2021 - I believe that combining elements from different angles yields a better decision. This time we will discuss Wilder’s Parabolic Stop-and-Reverse indicator, code it, and see three different strategies on how we can use it. I have just published a new book after the success of New Technical Indicators in Python.
🌐
GitHub
github.com › ryu878 › binance_psar_dashboard
GitHub - ryu878/binance_psar_dashboard: Parabolic SAR python implementation for Binance Futures
Parabolic SAR python implementation for Binance Futures - ryu878/binance_psar_dashboard
Starred by 2 users
Forked by 4 users
Languages   Python 100.0% | Python 100.0%
🌐
GitHub
github.com › mementum › backtrader › blob › master › backtrader › indicators › psar.py
backtrader/backtrader/indicators/psar.py at master · mementum/backtrader
__all__ = ['ParabolicSAR', 'PSAR'] · · class _SarStatus(object): sar = None · tr = None · af = 0.0 · ep = 0.0 ·
Author   mementum
🌐
Stockindicators
python.stockindicators.dev › indicators › ParabolicSar
Parabolic SAR | Stock Indicators for Python
November 3, 2024 - from stock_indicators import indicators # This method is NOT a part of the library. quotes = get_historical_quotes("SPY") # calculate ParabolicSar(0.02,0.2) results = indicators.get_parabolic_sar(quotes, 0.02, 0.2)
Find elsewhere
🌐
YouTube
youtube.com › watch
AI & Machine Learning for Trading (PROFITABLE) - ADX, Parabolic SAR using Python - Part 2 - YouTube
To download the Jupyter Notebook associated with this video ❤️:https://116-admin.systeme.io/algotradingsajidJoin the discord group:https://discord.gg/xYwCVRV...
Published   September 9, 2021
🌐
Raposa
raposa.trade › blog › 3-ways-to-trade-the-parabolic-sar-in-python
3 Ways To Trade The Parabolic SAR In Python — Raposa
Learn to build an automated, momentum trading system using the Parabolic Stop and Reverse (PSAR) indicator with step-by-step examples.
🌐
v-frog
virtualizedfrog.wordpress.com › 2014 › 12 › 09 › parabolic-sar-implementation-in-python
Parabolic SAR implementation in Python – v-frog
December 11, 2014 - I have recently tried to use the Parabolic Stop and Reverse indicator to track the VIX index (volatility on the S&P 500). A while back, I had used TA-lib and many of its indicators, but it was a while back. And I found it fairly painful to setup for Python this time. Given that I…
🌐
PeoplePerHour
peopleperhour.com › freelance-jobs › technology-programming › programming-coding › creation-of-a-parabolic-sar-technical-indicator-in-python-2094952
Creation of a Parabolic SAR technical indicator in Python
Hello, I am looking for someone to re-produce the Parabolic SAR technical trading indicator in python for a forex trading application. The program is currently set up to download data from IG.com every minute and calculate indicator values from this data. I have attempted to produce the PSAR ...
🌐
GitHub
github.com › FreddieWitherden › ta
GitHub - FreddieWitherden/ta: Technical analysis routines for Python
Technical analysis routines for Python built on top of Pandas. Current indicators: hhv · llv · ema · macd · aroon · rsi · stoch · dtosc · atr · cci · cmf · force · kst · ichimoku · ultimate · auto_envelope · bbands · safezone · sar (parabolic) adx ·
Starred by 105 users
Forked by 43 users
Languages   Python 100.0% | Python 100.0%
🌐
Unofficed
unofficed.com › home › lessons › how parabolic sar is calculated
How Parabolic SAR is Calculated - Unofficed
December 3, 2023 - Gain an understanding of how the Parabolic SAR is calculated, including its parameters and step-by-step coding using Python for precise trading analysis.
🌐
Stocksharp
stocksharp.com › store › stocksharp.strategies.0004_parabolic_sar_trend.py
Parabolic SAR Trend (Python). StockSharp
July 19, 2025 - The method trades both long and short without using additional stops beyond the SAR reversal. Entry Criteria: Signals based on Parabolic, SAR.
🌐
Reddit
reddit.com › r/python › help with a parabolic sar
r/Python on Reddit: Help with a parabolic SAR
July 25, 2018 -

Hi all!

This is my first post on r/python but I’ve been using the language for a while to make small projects, mainly using API for a number of websites.

My current project is to create an automated forex trading software using data from the IG.com API and the parabolic SAR indicator. With IG you cannot download indicator values live as this isn’t supported so I am having to calculate it myself. However I really cannot get my calculation to remain in check with the value displayed in the IG.com trading window and sometimes the SAR value I calculate rises when it should be falling?!

Does anyone have any experience dealing with a parabolic SAR calculation using values attained every minute?

Thank you all!

🌐
Madradavid
madradavid.com › stop-and-reverse-strategy
The Stop and Reverse Strategy : Using the Parabolic SAR and ADX
def combined_strategy(df): sar_buy, sar_sell = parabolic_sar_strategy(df) adx_buy, adx_sell = adx_strategy(df) buy_signals = sar_buy & adx_buy sell_signals = sar_sell & adx_sell return buy_signals, sell_signals · These Python examples provide a foundation for integrating the Parabolic SAR and ADX into your trading system.
🌐
GitHub
github.com › shaktisd › talibpython › blob › master › src › org › example › talib › sarexample.py
talibpython/src/org/example/talib/sarexample.py at master · shaktisd/talibpython
Implemented http://www.earnforex.com/forex-strategy/parabolic-sar-strategy · Entry Conditions · Enter Long position when the current price touches the indicator from below and it changes its direction.
Author   shaktisd
🌐
Stack Overflow
stackoverflow.com › questions › 63216682 › parabolic-sar-calculated-in-python-seems-to-be-reversed
pandas - Parabolic SAR calculated in Python seems to be reversed - Stack Overflow
@RichieV has posted a link to just a wrapper, the actual computation is being held inside TA-lib legacy code: retCode = lib.TA_SAR( 0 , endidx , <double *>(high.data)+begidx , <double *>(low.data)+begidx , acceleration , maximum , &outbegidx , &outnbelement , <double *>(outreal.data)+lookback ), so the debugging will be painful.