In [2]:
# In this example we'll use Finta paired with excellent backtest.py library

In [ ]:
# https://github.com/kernc/backtesting.py

In [2]:
import os
import pandas as pd

from backtesting import Backtest, Strategy
from backtesting.lib import crossover

from finta import TA


/home/cookie/.local/lib/python3.7/site-packages/backtesting/_plotting.py:37: UserWarning: Jupyter Notebook detected. Setting Bokeh output to notebook. This may not work in Jupyter clients without JavaScript support (e.g. PyCharm, Spyder IDE). Reset with `bokeh.io.reset_output()`.
  warnings.warn('Jupyter Notebook detected. '
Loading BokehJS ...

In [3]:
# Using same data set as unittests
data_file = os.path.join("tests/data/bittrex:btc-usdt.csv")

ohlc = pd.read_csv(data_file, index_col="date", parse_dates=True)

# Backtest.py wants column names as following:

# ohlc.columns = ["Close", "High", "Low", "Open", "Volume"]

# While finta wants it all in lowercase
# Simplest solution is to copy the columns

ohlc["Low"] = ohlc["low"]
ohlc["High"] = ohlc["high"]
ohlc["Open"] = ohlc["open"]
ohlc["Close"] = ohlc["close"]
ohlc["Volume"] = ohlc["volume"]

In [4]:
# Defining DEMA cross strategy
class DemaCross(Strategy):

    def init(self):

        self.ma1 = self.I(TA.DEMA, ohlc, 10)
        self.ma2 = self.I(TA.DEMA, ohlc, 20)

    def next(self):
        if crossover(self.ma1, self.ma2):
            self.buy()
        elif crossover(self.ma2, self.ma1):
            self.sell()

In [5]:
bt = Backtest(ohlc, DemaCross,
              cash=10000, commission=0.025)

In [6]:
bt.run()


Out[6]:
Start                     2015-12-12 00:00:00
End                       2018-06-18 00:00:00
Duration                    919 days 00:00:00
Exposure [%]                          97.8237
Equity Final [$]                      9588.54
Equity Peak [$]                       11137.7
Return [%]                           -4.11458
Buy & Hold Return [%]                 1428.68
Max. Drawdown [%]                    -73.7911
Avg. Drawdown [%]                    -15.2969
Max. Drawdown Duration      872 days 00:00:00
Avg. Drawdown Duration      178 days 00:00:00
# Trades                                   66
Win Rate [%]                          36.3636
Best Trade [%]                        110.863
Worst Trade [%]                      -24.2184
Avg. Trade [%]                        1.38524
Max. Trade Duration          56 days 00:00:00
Avg. Trade Duration          14 days 00:00:00
Expectancy [%]                        12.1681
SQN                                 -0.108971
Sharpe Ratio                        0.0668906
Sortino Ratio                        0.201305
Calmar Ratio                        0.0187725
_strategy                           DemaCross
dtype: object

In [7]:
# As you can see DEMA cross (10, 20) is not profitable on this data set,