**Introduction**

This tutorial will explain how to implement the Parabolic SAR indicator to build a trading strategy in Python, and along the way, it will introduce the Object Oriented Programming (OOP) approach to download the data, calculate the Parabolic SAR strategy, and generate the buy and sell signals. It’s all about **how to build a profitable Parabolic SAR trading strategy using Python**.

This tutorial will use data from the ETF AGG; additionally, in the last section, it will implement the QuantStats Python package to obtain performance and risk metrics. But please keep in mind that the main aim of the article is to show how it can be coded using Python. The trading strategy itself is of minor importance.

**Python trading strategy (Backtesting, Code, List, And Plenty of Python Coding Examples)****Hundreds of free backtested trading strategies**

**Parabolic SAR**

The Parabolic SAR is a trading indicator developed by Welles Wilder, and it aims to identify trends and reversals. This indicator finds short-term entry and exit signals. The Parabolic SAR has as a characteristic that its formula changes depending on whether there is a downtrend or upward trend.

Welles Wilder does not recommend applying this indicator in intervals below an hour or when the price fluctuation is flat.

The calculation for an upward trend is:

\text{PSAR}_t = \text{PSAR}_{t-1} + a_{t-1} (\text{EP}_{t-1} - \text{PSAR}_{t-1})

Meanwhile, the calculation for a downtrend is

\text{PSAR}_t = \text{PSAR}_{t-1} - a_{t-1} (\text{EP}_{t-1} - \text{PSAR}_{t-1})

The idea is to add +a_{t-1}(EP_{t-1} – PSAR_{t-1}) in an upward trend or subtract -a_{t-1}(EP_{t-1} – PSAR_{t-1}) in a downward trend, the expected result, to the previous Parabolic SAR value.

Where:

**PSAR _{t} **

*is the Parabolic SAR of the previous t.*

**PSAR _{t-1} **is the Parabolic SAR of the previous period t-1. Example: if today is day ten (or week ten), then t-1 is day nine (or week nine)

**a _{t-1} **is the accelerating factor starts at 0.02, and in an upward trend, it will increase 0.02 every time there is a higher high, until 0.2; in a downtrend, it will increase 0.02 every moment there is a lower low, until 0.2.

**EP _{t-1}** is the lowest low for a downtrend or the highest high for an upward trend.

**Python Example**

**Download Data and Parabolic SAR Estimation in Python**

As in the previous example, the first step is to import the Python libraries:

Then, we will implement in Python the ** Strategy** class that has the following structure:

- A function to instantiate the initial parameters
*__init__* - A function to download data from Yahoo Finance
*download_data* - A function to calculate the Parabolic SAR indicator
*get_psar* - A function to calculate the entry and exit signal for the
*strategy get_signals* - A function to calculate the performance of the strategy
*get_equity_curve*

The logical order is to download the data because, without data, it is not possible to do anything. Then, it is to estimate the indicator (Parabolic SAR). Next, it is to find the buy and sell signals. Finally, it is to calculate the performance of the strategy. The ** Strategy** class follows this order.

The following image shows the initial parameters: the security ** “AGG”**, the start date

**, and the end date**

*“2020-01-01”***.**

*“2023-01-01”*The next image shows how to instantiate the class ** Strategy**,

**; the**

*mystrategy=Strategy(security_name, start_date, end_date)***parameter in**

*self***does not represent an input to add is a Python convention. Then, the three parameters go to the**

*__init__***function, and the inner variables will get the following values:**

*__init__***,**

*self.security_name=”AGG”***, and**

*self.start=”2020-01-01”***. The print output shows how to access the values from the class already instantiated:**

*self.end=”2023-01-01”*In the following image, the ** download_data** function uses the values instantiated in the

**function and downloads the historical prices**

*__init__***.**

*result = mystrategy.download_data()*Meanwhile, the function ** get_psar** uses the historical data

**as input, and inside of this function**

*result***calculates the Parabolic SAR indicator; then, the method**

*ta.trend.PSARIndicator(data.High, data.Low, data.Close)***does the trick to return a pandas series with the values from the indicator.**

*.psar()*The pandas series ** data.High**,

**, and**

*data.Low***represents the historical pandas series with the daily high, daily low, and daily close, respectively.**

*data.Close*The output from ** result** and

**are:**

*mypsar***Trading Strategy and Descriptive Analysis**

This tutorial will implement a simple rule.

- Hold a
**long**position when the closing price is above the Parabolic SAR - Hold a
**short**position when the closing price is under or equal to the Parabolic SAR.

It is important to plot the closing price and the Parabolic SAR to have a first impression of the previous rules and identify the entry and exit signals in the chart; this is the descriptive analysis of the strategy.

The following image shows how to plot the closing price ** result.Close**, and the Parabolic SAR

**.**

*mypsar.values*Meanwhile, ** cross_above** and

**are pandas series with**

*cross_below***and**

*True***values; when**

*False***is**

*cross_above***, the closing price moved below the Parabolic SAR indicator, and when**

*True***is**

*cross_above***, the closing price moved above or is equal to the Parabolic SAR indicator**

*False***.**

*mypsar*Subsequently, the two scatter plots will generate arrows; the green arrow indicates the entry point for a long position, and the red arrow indicates the entry point for a short position.

The result from the previous image is:

The above image shows the result from the previous code.

Only for demonstration, the following image shows the strategy from 2022-05 to 2023-01 (this is not in the code); additionally, it has some annotations to identify the trend and the formula to estimate the Parabolic SAR depending on whether the financial price is in a downtrend or upward trend:

The previous image shows how the PSAR indicator tends to identify the reversal points.

**Calculate Entry Points for the Long and Short Positions (The Signals)**

The next step is to calculate the entry and exit signals. From the class ** Strategy**, it is necessary to implement the

**function and the**

*get_signals***function.**

*get_equity_curve*The following image illustrates how to obtain the signals using ** mystrategy.get_signals(result, mypsar)**. Subsequently,

**estimates the cumulative return from the strategy.**

*result = mystrategy.get_equity_curve(result)*The equity curve plot is:

The previous chart shows the equity curve for the strategy. The total return is around 18%.

**The QuantStats Python package**

The QuantStats python package is a powerful tool for quantitative analysis. It provides essential metrics to analyze the performance and risk of a trading strategy. Additionally, it implements different graphs to see in more detail the strategy.

The main recommendation is to go to the main website of the Python package QuantStats because it has different examples using this package in Jupyter Notebook.

The following image shows how to implement QauntStats for the strategy.

It generates an html file:** qs.reports.html(result[‘Cumulative Returns’], output= “report_strategy.html”)**. Subsequently,

**opens the HTML file**

*webbrowser.open_new_tab(“report_strategy.html”)***report_strategy.html**in a browser.

In your browser, you should see the following result:

In the previous image, there are multiple charts and metrics to enhance your analysis.