Python

Using SL and PT in backtesting in Python with vectrobt

Using SL and PT in backtesting in Python with vectrobt

When you backtest the strategies you most often you use Profit Target and Stop Loss to protect your earnings and limit your loss. All modern backtesting engines should have these essential features. In this article, I will show you how you can use SL and PT in vectorbt library. In vectorbt framework, you can do as simple as passing 2 parameters to the backtesting function. This is why I like this library so much because you can do quite complicated things very simply.

Let’s first start with the code that will download data and compute signals. I posted this code in a few of my articles already so there is nothing to add to it:

import vectorbt as vbt

aapl_data = vbt.YFData.download(
    'AAPL',
    missing_index='drop',
    interval = '1d'
)

aapl_close = aapl_data.get('Close')

fast_ma = vbt.MA.run(aapl_close, 10, short_name='fast MA')
slow_ma = vbt.MA.run(aapl_close, 50, short_name='fast MA')

long_entries = fast_ma.ma_crossed_above(slow_ma)
short_entries = fast_ma.ma_crossed_below(slow_ma)

This code will download data for Apple from Yahoo Finance and will compute signals for entries and exits. Interesting part start when running the “from_signal” function:

pf = vbt.Portfolio.from_signals(
    aapl_close,
    entries       = long_entries,
    short_entries = short_entries,
    
    sl_stop=0.025,
    tp_stop=0.05,
    
    freq = '1d',
    upon_opposite_entry='close'
)

As you can see I provided 2 new parameters for this function:

  • sl_stop – responsible for % of stop loss. If you’ll pass the value of 0.025 for example it is equal to 2.5%.
  • tp_stop – responsible for % of take profit (profit target). The value of 0.05 in my example is equal to 5%.

If the price for my trades will go above 5% in profits or below 2.5% in losses they will be closed. As you can see it’s quite simple to add SL and PT for your strategies in vectorbt . In the next articles, I’ll introduce you to more advanced concepts of backtesting in Python.

To check the performance of your strategy you can run the following code:

pf.stats()

To plot your perfor

Start                         1980-12-12 00:00:00+00:00
End                           2022-08-17 00:00:00+00:00
Period                              10509 days 00:00:00
Start Value                                       100.0
End Value                                    543.963721
Total Return [%]                             443.963721
Benchmark Return [%]                      174381.127209
Max Gross Exposure [%]                            100.0
Total Fees Paid                                     0.0
Max Drawdown [%]                              31.350131
Max Drawdown Duration                2219 days 00:00:00
Total Trades                                        237
Total Closed Trades                                 237
Total Open Trades                                     0
Open Trade PnL                                      0.0
Win Rate [%]                                  45.147679
Best Trade [%]                                16.746513
Worst Trade [%]                              -12.430596
Avg Winning Trade [%]                          6.631319
Avg Losing Trade [%]                          -3.902731
Avg Winning Trade Duration    6 days 19:03:55.514018691
Avg Losing Trade Duration     5 days 05:01:23.720930232
Profit Factor                                  1.304415
Expectancy                                     1.825562
Sharpe Ratio                                   0.450664
Calmar Ratio                                   0.193272
Omega Ratio                                    1.201434
Sortino Ratio                                  0.682337

To show performance in a chart you can run following :

fig = pf.plot(subplots=['cum_returns'])
fig.show()

Follow me on TradingView and YouTube.

This image has an empty alt attribute; its file name is wide.png

Leave a Comment

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

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

Pine Script Programming Courses
Pine Script Programming Courses
Learn to build your own TradingView Indicators and Strategies
Sidebar Signup Form
If you want to be the first in this business, subscribe to the latest news