Backtesting is A piece of Cake(signal backtester Guide)
Tags: python, backtest, programming, opensource
Published: 2022-03-05 08:25:16

some time is hard to back test your strategy with back test library i made easy . with 3 lines of code you can back test and see result of your strategy.

https://github.com/xibalbas/signal_backtester/
support the project with your stars :))

## what is [Signal Backtester](https://github.com/xibalbas/signal_backtester/)?

it is a tiny backtester Based on Backtesting Lib .
easiest way to backtest your generated signal. just need a csv file contain candleStick informations. OHLCV + signal 

## why??
some time writing good backtest for a strategy is not too easy . and you may have some challenge with backtest libraries.

so i decided to make a seprate repo for backtesting in easiest way.
what you need is a csv file contain `signal` column . for buy signal you should put `2`, and for sell signal you put `1`.

and good news is you did not need to write strategy for how trade we wrote it before you just choose yours and finish you did it :))
see [Strategy](https://github.com/xibalbas/signal_backtester#strategy) guide.


## First
prepare your data and prepare your signal .
you can write your strategy and generate signal like this 

here is an example of generating signal for EMA cross strategy and show you how generate your signal .
our signal generate as new column `signal` in our data frame .

**notice:** your data set column should contain `Date`,`Open`, `High`, `Low`, `Close`, `Volume`,`signal`

```python
import talib  # notice you can install talib manually
import pandas as pd


def cross_EMA_signals(df, fast_period, slow_period):
    """_summary_

    Args:
        df (_type_): _description_
        fast_period (_type_): _description_
        slow_period (_type_): _description_
    """
    signal = [0] * len(df)

    df["fast"] = talib.EMA(df.Close, timeperiod=fast_period)
    df["slow"] = talib.EMA(df.Close, timeperiod=slow_period)
    for idx in range(len(df)):
        if idx > slow_period:

            if (
                df.iloc[idx - 1].fast < df.iloc[idx - 1].slow
                and df.iloc[idx].fast > df.iloc[idx].slow
            ):
                # buy signal
                signal[idx] = 2

            if (
                df.iloc[idx - 1].fast > df.iloc[idx - 1].slow
                and df.iloc[idx].fast < df.iloc[idx].slow
            ):
                # sell signal
                signal[idx] = 1

    df["signal"] = signal
    df.to_csv("./final_dataset.csv")


df = pd.read_csv("./data.csv")

if __name__ == "__main__":
    cross_EMA_signals(df, 15, 30)

```

## second (Backtest in 3 line)

### installation
```bash
pip install signal-backtester
```

### make a backtest

```python
from signal_backtester import SignalBacktester


dataset_address = "./final_dataset.csv"

backtest = SignalBacktester(
    dataset=dataset_address,
    strategy="two_side_sl_tp_reversed",
    cash=100000,
    commission=0.0005,
    percent_of_portfolio=99,
    stop_loss=1,
    take_profit=2,
    trailing_stop=3,
    output_path="./result",  # path of result files
)

backtest.run()

```

and simply get result of [Backtesting](https://pypi.org/project/Backtesting/) lib:

**final_report.html**


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/356789k31998v5xgj7zt.png)

**final_report.csv**

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hb55mx1xb55rgmvudigt.png)

**order_report.csv**


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2b4q7agaed7ewt0otm0u.png)