Beispiel #1
0
    def test_data_extra_columns(self):
        df = GOOG.copy()
        df['P/E'] = np.arange(len(df))
        df['MCap'] = np.arange(len(df))

        class S(Strategy):
            def init(self):
                assert len(self.data.MCap) == len(self.data.Close)
                assert len(self.data['P/E']) == len(self.data.Close)

            def next(self):
                assert len(self.data.MCap) == len(self.data.Close)
                assert len(self.data['P/E']) == len(self.data.Close)

        Backtest(df, S).run()
Beispiel #2
0
 def test_data_nan_columns(self):
     df = GOOG.copy()
     df['Open'] = np.nan
     with self.assertRaises(ValueError):
         Backtest(df, SmaCross).run()
# As a trade-off, _backtesting.py_ is a _blazing fast_, small and lightweight backtesting library that uses state-of-the-art Python data structures and procedures. The entire API easily fits into memory banks of a single human individual. It's best suited for optimizing position entrance and exit strategies, decisions upon values of technical indicators, and it's also a versatile interactive trading strategy visualization tool.
#
# ### Data
#
# _You bring your own data._ Backtesting ingests data as a [pandas.DataFrame](https://pandas.pydata.org/pandas-docs/stable/10min.html) with columns `'Open'`, `'High'`, `'Low'`, `'Close'`, and (optionally) `'Volume'`. Such data is easily obtainable (see e.g.
# [pandas-datareader](https://pandas-datareader.readthedocs.io/en/latest/),
# [Quandl](https://www.quandl.com/tools/python),
# [findatapy](https://github.com/cuemacro/findatapy), ...).
# Your data frames can have other columns, but these are necessary.
# DataFrame should ideally be indexed with a _datetime index_ (convert it with [`pd.to_datetime()`](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html)), otherwise a simple range index will do.

# +
# Example OHLC data for Google Inc.
from backtesting.test import GOOG

GOOG.tail()
# -

# ### Strategy
#
# Let's create our first strategy to backtest on these Google data. Let it be a simple [moving average (MA) cross-over strategy](https://en.wikipedia.org/wiki/Moving_average_crossover).
#
# _Backtesting.py_ doesn't contain its own set of technical indicators. In practice, the user should probably use functions from their favorite indicator library, such as
# [TA-Lib](https://github.com/mrjbq7/ta-lib),
# [Tulipy](https://tulipindicators.org),
# PyAlgoTrade, ...
# But for this example, we define a simple helper moving average function.

# +
import pandas as pd
Beispiel #4
0
 def test_data_missing_columns(self):
     df = GOOG.copy()
     del df['Open']
     with self.assertRaises(ValueError):
         Backtest(df, SmaCross).run()
from backtesting.test import GOOG

GOOG.tail()
GOOG.head()

import pandas as pd

def SMA(values, n):
    return pd.Series(values).rolling(n).mean()


from backtesting import Strategy
from backtesting.lib import crossover

class SmaCross(Strategy):
    n1 = 10
    n2 = 20

    def init(self):
        self.sma1 = self.I(SMA, self.data.Close, self.n1)
        self.sma2 = self.I(SMA, self.data.Close, self.n2)

    def next(self):
        if crossover(self.sma1, self.sma2):
            self.position.close()
            self.buy()        
        elif crossover(self.sma2, self.sma1):
            self.position.close()
            self.sell()

from backtesting import Backtest