user1526586
user1526586

Reputation: 93

How to Backtest a Strategy in Python

I need to be able to determine whether a particular "trade" (indicated by "signal") resulted in a profit or loss by indicating a win or loss for each.

I need Python to check the next location ( the signal or entry point or date + 1 ) in the High and Low lists ( the lists: close, highs, and lows will have the same number of values ) for an increase in value equal to or greater than 2.5% at some point beyond the entry signal.

However, I also want Python to determine if the value drops 3% or more prior to appreciating 2.5% or more.

This must occur for each entry in signal.

In essence, I need a limit to sell at 102.5% and a stop at 97%.

Unfortunately, the code I developed so far doesn't seem to be working.

What am I missing?

signals = [1,5,7]
close   = [5,10,10,10.5,11,12,11.9,14,14,15,16]
highs   = [7,10.2,10.1,11,12,12.1,12.2,14.5,18,19,20]
lows    = [4,9.9,9.8,10,10,11.8,11.8,12,13.8,13.85,14]

for i in signals:
    entry = close[i]
    print i
    for high in highs[i+1:]:
        profit = ( ( high - entry ) / entry ) * 100
    for low in lows[i+1:]:
        loss   = ( ( low  - entry ) / entry ) * 100
    if abs( loss ) <  3:
        if profit  >= 2.5:
            print 'Win'
        else:
            print 'Loss'

Upvotes: 2

Views: 3687

Answers (2)

Stephan Hutterer
Stephan Hutterer

Reputation: 67

Did you already check python-libraries for backtesting? In fact I use other libraries, but there are some very popular python-based solutions such as "pybacktest", "PyAlgoTrade", or "UltraFinance". Maybe integrating such a library could be advantageous for your use case...

Upvotes: 2

Martijn Pieters
Martijn Pieters

Reputation: 1124060

Your profit is only calculated for highs[-1] while loss is only calculated for lows[-1]. Everything else is discarded, as you replace profit and loss in each loop.

You want to find the set of values where your condition is true. Use zip to put lows and highs together:

for i in signals:
    entry = float(close[i])
    for high, low in zip(high[i + 1:], low[i + 1:]):
        profit = ((high - entry) / entry) * 100
        loss = ((low - entry) / entry) * 100
        if loss > -3:
            if profit >= 2.5:
                print "Win"
            else:
                print "Loss"

Upvotes: 2

Related Questions