Welcome to TED Optimus - backtesting’s documentation!

Indicator Usage:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
from optimus.backtesting.indicator import Indicator

indicator = Indicator()

# Option 1: Specifying indicators
indicator.sma()
indicator.ema()
indicator.pivot()

# Option 2: Select all indicators
indicator.all()

Universe Usage:

1
2
3
4
5
6
7
from optimus.backtesting.data import Universe

universe = Universe(selection=UniverseSelection.STOCKS, api_key='your api key',
                     indicator=indicator)

# Converting to DataFrame
df = universe.df

Performance Usage:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
from optimus.backtesting.performance import Performance

performance = Performance(portfolio)

# Don't want to show graph?
performance = Performance(portfolio, show=False)

performance.objective_function()

performance.performance_metric()

Common Usage:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
from optimus.backtesting.performance import Performance
from optimus.backtesting.portfolio import Portfolio
from optimus.backtesting.selection import PositionSizing, EquityModel, Reason
from optimus.backtesting.data import Universe, UniverseSelection
from optimus.backtesting.indicator import Indicator
from tqdm import tqdm
import numpy as np

# Initializing indicators
indicator = Indicator()
indicator.all()
indicator.macd([[10, 20, 7]])

# Initializing universe
universe = Universe(selection=UniverseSelection.STOCKS, api_key='your api key', indicator=indicator)
df = universe.df

# Entry and exit signal
df['sell_signal'] = np.where(df['MACDdiff_10_20_7'] < 0, 1, 0)
df['buy_signal'] = np.where(
    (df['close'] >= 0.2) & (df['volume'] >= 100000) & (df['MACDdiff_10_20_7'] >= 0) & (df['MACD_10_20_7'] >= 0) & (
            df['MACDsign_10_20_7'] >= 0) & (df['sell_signal'] == 0), df['momentum'].values, 0)
df['buy_signal'] = df['buy_signal'].fillna(0)

# Initializing portfolio
 portfolio = Portfolio(df, EquityModel.CORE_EQUITY, PositionSizing.EQUAL_UNIT, 100000)

 # Backtesting starts here!
 for index, frame in tqdm(df.groupby('date'), "Backtesting"):
     days_count = frame.index[0]
     frame.set_index('ticker', inplace=True)
     for ticker, info in portfolio.holding():
         # Check for cut loss first
         if frame.loc[ticker, 'low'] <= info['cut_loss']:
             portfolio.sell(ticker, Reason.CL, index, info['cut_loss'], days_count)
         # Check for exit signal
         elif frame.loc[ticker, 'sell_signal'] == 1:
             portfolio.sell(ticker, Reason.EXIT, index, frame.loc[ticker, 'close'], days_count)

     # Sort remaining stocks that have buy signals by momentum (High to low)
     frame = frame.loc[
                 (frame['buy_signal'].values != 0) & (~frame.index.isin(portfolio.list()))].sort_values(
         'buy_signal', ascending=False)[:portfolio.free()]

     for item in frame.index.to_list():
         # Buy it!
         portfolio.buy(item, index, frame.loc[item, 'close'], days_count)

# Measuring performance
performance = Performance(portfolio)
performance.objective_function()
performance.performance_metric()

CHANGELOG v5.0.0

  • Indicator
    • Added gainer loser indicator

    • Added sma_ema indicator

  • Tick data
    • Added raw tick data

    • Added feature to resample a timeframe from tick data

    • Added dataframe of an intraday timeframe

    • Added technical analysis of an intraday timeframe

    • Added tick data examples

  • Universe
    • Added Indices in Universe Selection

  • Bug Fixes
    • Fixed code examples on website

    • Fixed SQN (R-Multiple)

CHANGELOG v4.0.0

  • Indicator
    • Fractal breakout indicator

    • Smart money indicator

    • Percentage change indicator

    • Year to date change indicator

  • Portfolio
    • Get position size based on equity model and position size model

    • Get portfolio value given specific date

    • Get equity based on different models

    • Get commission given unit size and price

  • Equity models
      1. Core equity

      1. Total equity

      1. Reduced total equity

  • Position sizing models
      1. Equal unit

      1. Percent volatility

      1. Percent risk

  • Ted Optimus flowcharts
    • Trading strategy

    • Walk forward - main

    • Walk forward - backtest

CHANGELOG v3.3.0

  • Indicator
    • Donchian channel

    • High low

    • Fibonacci pullback

  • Features
    • Portfolio clear

    • Walk forward module (NEW!)

  • Documentation
    • Walk forward

CHANGELOG v3.2.2

  • Bug fixes
    • EMA related

    • Commissions/ Brokerage Fee

CHANGELOG v3.2.1

  • Indicator
    • Parabolic SAR

  • Features
    • Generate all performance file and performance image in one function

  • Examples
    • Time stop

    • Consider commissions and set brokerage fee in portfolio

    • Sell based on yesterday’s condition

    • View all performances of strategy

    • Dataframe list for multi period backtesting

    • Stocks to buy tomorrow at market open

    • Backtest on different parameters

    • Plot heatmap for specific metric

CHANGELOG v3.2.0

  • Indicator
    • Average daily turnover

    • Biggest drop

    • Average Directional Index Rating (ADXR)

    • William Fractal Indicator (fractal)

    • Schaff Trend Cycle (STC)

    • On Balance Volume (OBV)

    • Smoothed Moving Average (SMMA)

  • Features
    • Commissions can be enabled through Portfolio

    • Stop loss price can be updated using portfolio.set_cut_loss_price(ticker, price)

  • Examples
    • Trailing stop loss

    • Take profit

CHANGELOG v3.1.2

  • Fixed several EMA calculation issue

  • Added ATR

CHANGELOG v3.1.1

  • Fixed matplotlib memory leakage issue

CHANGELOG v3.1.0

  • Fixed RSI indicator

  • Refactor .values to .to_numpy()

  • Performance remains unchanged

CHANGELOG v3.0.0

  • Added multi period support

  • Added multi period shifting support

  • Added transactions list to CSV

  • Added objective function to CSV

  • Added performance metrics to CSV

  • Bug Fixes