Rajandran R Creator of OpenAlgo Sketchmaker, RagZ. Building GenAI Applications. Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, High Liquid Stock Derivatives. Trading the Markets Since 2006 onwards. Using Market Profile and Orderflow for more than a decade. Designed and published 100+ open source trading systems on various trading tools. Now the recent curiosity on building Trading AI Agents.

Generating Real-Time Equity Curve Using Amibroker and Enhancing Backtesting Metrics with Quantstats Python Library

2 min read

Generating Real-Time Equity Curve Using Amibroker and Enhancing Backtesting Metrics with Quantstats Python Library

Amibroker, a popular trading system development platform, offers solid tools for creating and analyzing trading strategies. Adding the Quantstats Python library lets traders go deeper into backtesting metrics that help refine their trading strategies. This post builds a QuantStats Amibroker equity curve report step by step.

QuantStats Python library performs portfolio profiling, allowing quants and portfolio managers to understand their performance better by providing them with in-depth analytics and risk metrics.

Step 1: Generating the Real-Time Equity Curve in Amibroker

To begin, traders need to integrate specific codes into their Amibroker trading system(AFL Code). This code is designed to generate a real-time equity curve, providing a visual representation of the trading strategy’s performance over time. Here’s the process:

Masterclass on AmiBroker AFL coding

AMIBROKER

Masterclass on AmiBroker AFL coding

Write trading systems, explorations and backtests in AFL, and use ChatGPT to code faster.

  • AFL from basics to trading systems
  • Backtesting and optimisation done right
  • 7 courses in one masterclass
Learn AFL coding →by Marketcalls

Code Integration: The following code needs to be added to the Amibroker trading system:

_SECTION_BEGIN("Realtime Equity Curve - Exploration");


SetOption( "InitialEquity", 200000);
SetOption("FuturesMode" ,True);
SetOption("MinShares",1);
SetOption("CommissionMode",1);
SetOption("CommissionAmount",.02);
//SetOption(“AccountMargin”,10);
SetOption("RefreshWhenCompleted",True);

e=Equity(1);
Plot(e,"Equity",colorYellow,styleleftAxisScale);




Filter = 1;

AddColumn(Open,"Open",1.2);
AddColumn(High,"High",1.2);
AddColumn(Low,"Low",1.2);
AddColumn(Close,"Close",1.2);
AddColumn(e,"Equity",1.2);
AddColumn(ROC(e,1)/100,"PerEquity",1.6);

SetSortColumns(2);

_SECTION_END();

Running the Analysis: Go to ‘New Analysis’, select the Amibroker trading system(AFL Code), and press ‘Explore’.

Exporting Data: Use the File menu to export the data as an HTML/CSV file, and save it as backtesting.csv.

Step 2: Deepening Backtesting Metrics with Quantstats

Once the data is exported from Amibroker, it’s time to use Quantstats, a Python library designed for performance and risk analytics.

Import and Prepare Data: Use Python to import the backtesting.csv file and prepare it for analysis. The following sample code illustrates how to do this:

%matplotlib inline
import pandas as pd
import quantstats as qs
backtest_data = pd.read_csv("C:\\Users\\Dell\\OneDrive\\Documents\\Python\\backtesting.csv")

# Convert the 'Date' column to datetime and set it as the index
backtest_data['Date/Time'] = pd.to_datetime(backtest_data['Date/Time'], format='%d-%m-%Y %H:%M:%S')

backtest_data['Date/Time'] = backtest_data['Date/Time'].dt.strftime('%Y-%m-%d %H:%M:%S')
backtest_data['Date/Time'] = pd.to_datetime(backtest_data['Date/Time'])
backtest_data.set_index('Date/Time', inplace=True)

# Now use returns in QuantStats
qs.reports.full(backtest_data["PerEquity"].dropna())

Analysis and Metrics: Quantstats offers a variety of metrics that provide a deeper understanding of the trading strategy’s performance. Some of these metrics include:

Detailed Performance Metrics

                           Strategy
-------------------------  ----------
Start Period               2011-01-05
End Period                 2022-10-31
Risk-Free Rate             0.0%
Time in Market             100.0%

Cumulative Return          841.01%
CAGR﹪                     13.98%

Sharpe                     1.52
Prob. Sharpe Ratio         100.0%
Smart Sharpe               1.46
Sortino                    3.07
Smart Sortino              2.96
Sortino/√2                 2.17
Smart Sortino/√2           2.09
Omega                      1.35

Max Drawdown               -12.66%
Longest DD Days            233
Volatility (ann.)          9.53%
Calmar                     1.1
Skew                       2.05
Kurtosis                   12.59

Expected Daily %           0.06%
Expected Monthly %         1.59%
Expected Yearly %          20.54%
Kelly Criterion            10.36%
Risk of Ruin               0.0%
Daily Value-at-Risk        -0.93%
Expected Shortfall (cVaR)  -0.93%

Max Consecutive Wins       8
Max Consecutive Losses     17
Gain/Pain Ratio            0.45
Gain/Pain (1M)             4.27

Payoff Ratio               2.02
Profit Factor              1.35
Common Sense Ratio         2.58
CPC Index                  1.09
Tail Ratio                 1.91
Outlier Win Ratio          3.93
Outlier Loss Ratio         4.24

MTD                        -0.03%
3M                         3.98%
6M                         4.73%
YTD                        16.3%
1Y                         23.18%
3Y (ann.)                  13.76%
5Y (ann.)                  14.04%
10Y (ann.)                 12.56%
All-time (ann.)            13.98%

Best Day                   6.71%
Worst Day                  -4.19%
Best Month                 16.05%
Worst Month                -8.95%
Best Year                  38.19%
Worst Year                 6.33%

Avg. Drawdown              -1.09%
Avg. Drawdown Days         12
Recovery Factor            18.28
Ulcer Index                0.03
Serenity Index             10.86

Avg. Up Month              2.78%
Avg. Down Month            -1.41%
Win Days %                 51.95%
Win Month %                72.54%
Win Quarter %              83.33%
Win Year %                 100.0%


Worst 5 Drawdowns


Strategy Visualization


End of the Year Returns (EOY Returns)


Distribution of Monthly Returns


Daily Active Returns


Rolling Volatility


Rolling Sharpe Ratio

Rolling Sortino Ratio

Visualization of 5 worst Drawdown Periods


Underwater Plot (% Drawdown)


Strategy – Monthly Returns %


With a QuantStats Amibroker equity curve report, combining Amibroker’s real-time equity curve generation with Quantstats’ detailed backtesting metrics, traders get a fuller picture of their trading strategy’s performance. It helps evaluate current strategies and shows where they can be improved.

Marketcalls Elite Traders Club

MEMBERSHIP

Marketcalls Elite Traders Club

Every Marketcalls course and live mentorship in one membership: 127 courses and 2,500+ hours of learning.

  • Market Profile, Orderflow, AFL, Pine Script and Python
  • Live mentorship and TradEdge trading room
  • Premium tools and the Elite Slack community

Learn by watching: free videos every week

Market Profile, order flow, Python, AI and OpenAlgo tutorials on YouTube.

Rajandran R Creator of OpenAlgo Sketchmaker, RagZ. Building GenAI Applications. Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, High Liquid Stock Derivatives. Trading the Markets Since 2006 onwards. Using Market Profile and Orderflow for more than a decade. Designed and published 100+ open source trading systems on various trading tools. Now the recent curiosity on building Trading AI Agents.

Leave a Reply

Get Notifications, Alerts on Market Updates, Trading Tools, Automation & More