optimus.backtesting package¶
Submodules¶
optimus.backtesting.data module¶
-
class
optimus.backtesting.data.
Universe
(selection: optimus.backtesting.selection.UniverseSelection, indicator: optimus.backtesting.indicator.Indicator, auto_run: bool = True)¶ Bases:
optimus.backtesting.api_key.ApiKey
Generate an Universe for backtesting
- Parameters
selection (UniverseSelection) – Stocks, Warrants, or Indices
indicator (Indicator) – Indicator
auto_run (bool) – Computation, defaults to True
-
property
df
¶ Translate into DataFrame
- Returns
pd.DataFrame
-
df_multi_period
(*args)¶ Slicing DataFrame into multi period time frame.
Usage:
1 2 3 4
first_date = datetime(2015, 1, 1) second_date = datetime(2016, 1, 1) third_date = datetime(2017, 1, 1) df_multi_period(first_date, second_date, third_date)
- Parameters
args (python.datetime.datetime) – datetime(2015, 1, 1), datetime(2016, 1, 1), datetime(2017, 1, 1)
- Returns
Lists of DataFrame according to specified time frame
-
df_period_shifting
(date: datetime.datetime, shift: int, multiplier: int = 1)¶ Slicing DataFrame into multi period time frame with shifting
Usage:
1 2
date = datetime(2016, 1, 4) df_period_shifting(date, 10, 2)
Results:
¶ date
…
2016-01-04
…
2016-01-05
…
… 7 more rows …
…
2016-01-15
…
2016-01-18
…
¶ date
…
2016-01-18
…
2016-01-19
…
… 7 more rows …
…
2016-02-02
…
2016-02-03
…
- Parameters
date (python.datetime.datetime) – datetime(2016, 1, 4)
shift (int) – period shifting, can be positive (look forward), or negative (look backward)
multiplier – shift multiplier, repeat shifting, defaults to 1
- Returns
Lists of DataFrame shifted
-
plot_heatmap
(path, metric, rows, cols, x_label, y_label, width=15, height=10, save_figure=False, name='heatmap.png')¶ Plot heatmap according to csv file from two changing parameters
- Parameters
path (path) – path of objective function / performance metric
metric (string) – name of metric in csv file
rows (list) – list containing values of row parameter
cols (list) – list containing values of col parameter
x_label (string) – name of x-axis label
y_label (string) – name of y-axis label
width (int) – width of figure
height (int) – height of figure
save_figure (bool) – save figure as png
name (string) – name of figure
optimus.backtesting.performance module¶
-
class
optimus.backtesting.performance.
Performance
(portfolio: optimus.backtesting.portfolio.Portfolio, show: bool = True)¶ Bases:
object
Performance module for backtesting
- Parameters
portfolio (Portfolio) – Portfolio
show (bool) – Show graph or not
-
property
average_losing_trade
¶ Average loss of all losing trades. Losing trades is defined as < 0
-
property
average_number_of_bars_in_losers
¶ Average number of days for all round losing trades. Losing trades is defined as < 0
-
property
average_number_of_bars_in_winners
¶ Average number of days for all round winning trades. Winning trades is defined as > 0
-
property
average_trade
¶ Average profit of all trades
-
property
average_winning_trade
¶ Average profit of all winning trades. Winning trades is defined as > 0
-
generate_all_files
(strategy_name, code_path, version, plot_image=True)¶ Generate performances for all files
- Parameters
strategy_name (string) – folder name of strategy
code_path (file path) – path of code file
version (string) – version of the strategy
plot_image (bool) – save images into folder
-
property
gross_loss
¶ Sum of all loss. Loss is defined as value < 0
-
property
gross_profit
¶ Sum of all profit. Profit is defined as value > 0
-
property
largest_losing_trade
¶ Largest loss among all losing trades. Losing trades is defined as < 0
-
property
largest_winning_trade
¶ Largest profit among all winning trades. Winning trades is defined as > 0
-
property
max_daily_drawdown
¶ Daily drawdown means difference between Cumulative net profit and Maximum Cumulative net profit
Maximum daily drawdown means Largest drawdown or decline in the equity curve of a trading strategy from an equity peak
Measures the downside of the system but ignores the upside potential
Maximum daily drawdown is in % to cater for the size of portfolio throughout time
Look for smaller maximum daily drawdown
-
property
maximum_intraday_drawdown
¶ Largest possible net loss in the system throughout the trading period.
-
property
maximum_intraday_profit
¶ Largest possible net profit in the system throughout the trading period.
-
property
net_profit
¶ Sum of all profit and loss at the end date
Measures the upside of the system but ignores the distribution of trades and downside risk
Look for larger net profit
-
property
number_losing_trades
¶ Number of complete round losing trades. Losing trades is defined as < 0
-
property
number_winning_trades
¶ Number of complete round winning trades. Winning trades is defined as > 0
-
objective_function
(need_print=True)¶
-
objective_to_csv
(strategy_name, file_path)¶ Convert transactions to csv file
- Parameters
strategy_name (str) – Name of the strategy
file_path (path) – File path
-
property
percent_profitable
¶ - \[\dfrac{Number\ winning\ trades}{Total\ number\ of\ trades}\]
Look for percent profitable above 50%, especially in mean reversion strategy
-
performance_metric
(need_print=True)¶
-
performance_to_csv
(strategy_name, file_path)¶ Convert transactions to csv file
- Parameters
strategy_name (str) – Name of the strategy
file_path (path) – File path
-
plot_objective_function
(save_figure=False)¶
-
plot_performance_metric
(save_figure=False)¶
-
property
profit_factor
¶ - \[\dfrac{Gross\ profit}{Gross\ loss}\]
Look for factor > 1, for all type of system
-
property
prom
¶ PROM assumes trading strategy will win less and lose more in real-time trading.
\[PROM = \dfrac{(AW×(WT-\sqrt{WT}))-(AL×(LT-\sqrt{LT}))}{Initial\ Capital}\]WT = Number of Wins
AW = Average Wins
LT = Number of Losses
AL = Average Loss
Look for higher PROM.
-
property
prom_less
¶ PROM minus biggest win removes the largest single profitable trade from the gross profit.
Look for higher PROM minus biggest win
-
property
ratio_average_win_over_average_loss
¶ Average winning trade / average losing trade in absolute term
Look for ratio above 1, especially in momentum trend following system
-
property
sharpe_ratio
¶ Formula:
\[\dfrac{Mean[Asset\ return - Risk\ free\ return]}{Standard\ deviation\ of\ asset\ excess\ return}\]We take 2.8% for Risk free return, 10Y MGS rate.
Look for Sharpe ratio above 1
-
property
sqn
¶ SQN is trademark of Van Tharp, based on R-multiples.
\[R-multiples = \dfrac{Exit\ price - Entry\ price}{Entry\ price - Cut\ loss\ price}\]\[SQN = \dfrac{Mean\ of\ R-multiples}{Standard\ Deviation\ of\ R-multiples}×{\sqrt{Number\ of\ Trades}}\]Number of Trades we take min (number of trades, 100 ) because too many trades will overestimate the quality of the system
Look for sqn above 2. Above 7 is considered holy grail.
-
property
total_number_of_trades
¶ Number of complete round trades. Round trades defined as opening position with a Buy and closing postion with a Sell
-
transactions_to_csv
(path)¶ Convert transactions to csv file
- Parameters
path – File path
optimus.backtesting.portfolio module¶
-
class
optimus.backtesting.portfolio.
Portfolio
(df: pandas.core.frame.DataFrame, equity_model: optimus.backtesting.selection.EquityModel = <EquityModel.CORE_EQUITY: 1>, position_sizing: optimus.backtesting.selection.PositionSizing = <PositionSizing.EQUAL_UNIT: 1>, initial_capital: int = 100000, size: int = 10, take_profit: Optional[float] = None, cut_loss: float = 0.08, commission: bool = False, brokerage_fee: float = 0.08)¶ Bases:
object
Constructs a Portfolio
- Parameters
df (pd.DataFrame) – Dataframe used to calculate portfolio value
equity_model (EquityModel) – Must be an instance of EquityModel
position_sizing (PositionSizing) – Must be an instance of PositionSizing
initial_capital (int) – Initial capital allocated for the portfolio
size (int) – Portfolio size
take_profit (float) – Take profit percentage
cut_loss (float) – Cut loss percentage
commission (bool) – Calculate commission into transactions
brokerage_fee (float) – Brokerage fee calculated in percentage of total value traded
-
allocation
() → float¶ Capital allocated for transactions
- Returns
Capital allocated
-
property
brokerage_fee
¶ Brokerage fee calculated in percentage of total value traded.
- Returns
Float
-
buy
(ticker, date, price, index, tp_price=None, cl_price=None, risk_percent=0.02)¶ Create a buy transaction. If successful ticker will be added into portfolio and added into transaction list.
- Parameters
ticker – ticker symbol
date – order date
price – order price
index – index of open date, used to compute holding days
tp_price – Custom take profit price
cl_price – Custom cut loss price
risk_percent – percentage of equity to risk (percent volatility & percent risk model)
-
calculate_commission
(unit, price)¶ Calculate commission given unit size and price
-
calculate_position_size
(date, ticker, price, risk_percent, cl_price)¶ Calculate position size based on equity model and position size model
-
property
capital
¶ Current capital
- Returns
Integer/ Float
-
clear
()¶ Clear portfolio
-
property
commission
¶ Calculate commission into transactions.
- Returns
Bool
-
property
cut_loss
¶ Cut loss percentage set by user.
- Returns
Float
-
free
() → int¶ Slots available in portfolio.
- Returns
Free slot in portfolio
-
get_equity
(date)¶ Get equity based on different models
-
holding
() → List[Dict]¶ Portfolio holding
- Returns
List of portfolio holdings
-
property
initial_capital
¶ Initial capital set by user
- Returns
Integer
-
list
() → List[str]¶ Portfolio holding ticker list
- Returns
List of portfolio holdings’ ticker list
-
portfolio_value
(date)¶ Calculate portfolio value given specific date
-
sell
(ticker, reason, date, price, index)¶ Create a sell transaction. If successful ticker will be removed from portfolio and added into transaction list.
- Parameters
ticker – ticker symbol
reason – reason for selling
date – order date
price – order price
index – index of close date, used to compute holding days
-
set_cut_loss_price
(ticker, cl_price)¶ Update the cut loss price of a ticker in portfolio holding
- Parameters
ticker – ticker symbol
cl_price – cut loss price
-
property
size
¶ Size of the portfolio.
- Returns
Integer
-
property
take_profit
¶ Take profit percentage set by user.
- Returns
Float
-
property
transactions
¶ Transactions list generated.
- Returns
List
optimus.backtesting.indicator module¶
-
class
optimus.backtesting.indicator.
Indicator
¶ Bases:
object
Indicator class.
-
adxr
(params: Optional[List[List[int]]] = None)¶ Average Directional Index Rating
Series named as ADX_[ADX Smoothing]_[DI Length], ADXR_[ADX Smoothing]_[DI Length]_[Lookback Period]
- Parameters
params (List[List[int, int, int]]) – List[List[ADX Smoothing, DI Length, Lookback Period]], defaults to [[14, 14, 14]]
-
all
()¶ Includes all indicators
SMA, EMA, VMA, WMA, HMA, On Balance Volume, Bollinger Band, Stochastic Oscillator, MACD, Pivot, Momentum, RSI, Keltner Channel, Biggest Drop
-
atr
(params: Optional[List[int]] = None)¶ Average True Range
Series named as ATR_[Period]. E.g. ATR_14.
- Parameters
params (List[int]) – Arrays of ATR period, defaults to [14]
-
average_daily_turnover
(params: Optional[List[int]] = None)¶ Average daily turnover
Series named as average_daily_turnover_[Period]. E.g. average_daily_turnover_20.
- Parameters
params (List[int]) – Arrays of average daily turnover period, defaults to [20]
-
biggest_drop
(params: Optional[List[int]] = None)¶ Biggest Drop
Series named as biggest_drop_[Period]. E.g. biggest_drop_3.
- Parameters
params (List[int]) – Arrays of biggest_drop period, defaults to [3]
-
bollinger_band
(params: Optional[List[List[int]]] = None)¶ Bollinger Band
Series named as LowerBand_[MA]_[STD], MiddleBand_[MA]_[STD], UpperBand_[MA]_[STD], BbWidth_[MA]_[STD]. E.g. LowerBand_20_2, MiddleBand_20_2, UpperBand_20_2, BbWidth_20_2
- Parameters
params (List[List[int, int]]) – List[List[MA, STD]], defaults to [[20, 2], [20, 3]]
-
candle_bearish_abandoned_baby
(params: Optional[List[int]] = None)¶ Candlestick pattern - bearish abandoned baby
Series named as candle_bearish_abandoned_baby_[Period]. E.g. candle_bearish_abandoned_baby_3
- Parameters
params (List[int]) – Arrays of candle_bearish_abandoned_baby period, defaults to [3]
-
candle_bearish_engulfing
(params: Optional[List[int]] = None)¶ Candlestick pattern - bearish engulfing
Series named as candle_bearish_engulfing_[Period]. E.g. candle_bearish_engulfing_3
- Parameters
params (List[int]) – Arrays of candle_bearish_engulfing period, defaults to [3]
-
candle_bearish_harami
(params: Optional[List[int]] = None)¶ Candlestick pattern - bearish harami
Series named as candle_bearish_harami_[Period]. E.g. candle_bearish_harami_3
- Parameters
params (List[int]) – Arrays of candle_bearish_harami period, defaults to [3]
-
candle_bullish_abandoned_baby
(params: Optional[List[int]] = None)¶ Candlestick pattern - bullish abandoned baby
Series named as candle_bullish_abandoned_baby_[Period]. E.g. candle_bullish_abandoned_baby_3
- Parameters
params (List[int]) – Arrays of candle_bullish_abandoned_baby period, defaults to [3]
-
candle_bullish_engulfing
(params: Optional[List[int]] = None)¶ Candlestick pattern - bullish engulfing
Series named as candle_bullish_engulfing_[Period]. E.g. candle_bullish_engulfing_3
- Parameters
params (List[int]) – Arrays of candle_bullish_engulfing period, defaults to [3]
-
candle_bullish_harami
(params: Optional[List[int]] = None)¶ Candlestick pattern - bullish harami
Series named as candle_bullish_harami_[Period]. E.g. candle_bullish_harami_3
- Parameters
params (List[int]) – Arrays of candle_bullish_harami period, defaults to [3]
-
candle_evening_star
(params: Optional[List[int]] = None)¶ Candlestick pattern - evening star
Series named as candle_evening_star_[Period]. E.g. candle_evening_star_3
- Parameters
params (List[int]) – Arrays of candle_evening_star period, defaults to [3]
-
candle_hammer
(params: Optional[List[int]] = None)¶ Candlestick pattern - hammer
Series named as candle_hammer_[Period]. E.g. candle_hammer_3
- Parameters
params (List[int]) – Arrays of candle_hammer period, defaults to [3]
-
candle_hanging_man
(params: Optional[List[int]] = None)¶ Candlestick pattern - hanging man
Series named as candle_hanging_man_[Period]. E.g. candle_hanging_man_3
- Parameters
params (List[int]) – Arrays of candle_hanging_man period, defaults to [3]
-
candle_morning_star
(params: Optional[List[int]] = None)¶ Candlestick pattern - morning star
Series named as candle_morning_star_[Period]. E.g. candle_morning_star_3
- Parameters
params (List[int]) – Arrays of candle_morning_star period, defaults to [3]
-
donchian_channels
(params: Optional[List[int]] = None)¶ Donchian channels
Series named as DC_Lower_[period], DC_Upper_[period], DC_Basis_[period], DC_Lower_last_[period], DC_Upper_last_[period]. E.g. DC_Upper_20.
DC_Lower_last_[period]: Date of candle that created donchian low DC_Upper_last_[period]: Date of candle that created donchian high
- Parameters
params (List[int]) – Arrays of donchian channels period, defaults to [20]
-
ema
(params: Optional[List[int]] = None)¶ Exponential Moving Average
Series named as EMA_[param]. E.g. EMA_4, EMA_5.
- Parameters
params (List[int]) – Arrays of EMA period, defaults to [4, 5, 10, 13, 20, 26, 50, 150]
-
fibonacci_pullback
(params: Optional[List[int]] = None)¶ Fibonacci Pullback
Series named as pullback_[Period]. E.g. pullback_14.
- Parameters
params (List[int]) – Arrays of Donchian channels period to calculate fibonacci pullback, defaults to [14]
-
fractal
(params: Optional[List[int]] = None)¶ William fractal indicator
Series named as bullish_fractal_count_[period], bearish_fractal_count_[period].
- Parameters
params (List[int]) – Arrays of fractal period, defaults to [2,4]
-
fractal_breakout
(params: Optional[List[int]] = None)¶ Fractal breakout indicator Calculate breakout percentage from fractal high
Series named as breakout%_[period].
- Parameters
params (List[int]) – Arrays of fractal breakout period, defaults to [3]
-
gainer_loser
(enabled: bool = True)¶ Gainer loser indicator
Series named as gainer_loser
- Parameters
enabled (bool) – defaults to True
-
high_low
(params: Optional[List[int]] = None)¶ High low indicator
Series named as high_[period], low_[period]. E.g. high_21, low_21. Difference with Donchian channel: Before specified period - Calculate cumulative high / low After specified period - Calculate rolling high / low
- Parameters
params (List[int]) – List[high_low_periods], defaults to [21, 63, 126, 252]
-
hma
(params: Optional[List[int]] = None)¶ Hull Moving Average
Series named as HMA_[param]. E.g. HMA_5, HMA_10.
- Parameters
params (List[int]) – Arrays of HMA period, defaults to [5, 10]
-
keltner
(params: Optional[List[List[Union[int, float]]]] = None)¶ Keltner Channel
Series named as KelChU_[MA]_[ATR]_[Multiplier], KelChD_[MA]_[ATR]_[Multiplier], squeeze_[MA]_[ATR]_[Multiplier]. E.g. KelChU_[20]_[20]_[1.5], KelChD_[20]_[20]_[1.5], squeeze_[20]_[20]_[1.5]
- Parameters
params (List[List[Union[int, float], Union[int, float], Union[int, float]]]) – List[List[MA, ATR, Multiplier]], defaults to [[20, 20, 1.5]]
-
length
()¶ Indicators size
-
macd
(params: Optional[List[List[int]]] = None)¶ Moving Average Convergence Divergence
Series named as MACD_[fast]_[slow]_[ema], MACDsign_[fast]_[slow]_[ema], MACDdiff_[fast]_[slow]_[ema]. E.g. MACD_12_26_9.
- Parameters
params (List[List[int, int, int]]) – List[List[SMA Fast, SMA Slow, EMA]], defaults to [[12, 26, 9]]
-
momentum
(params: Optional[List[int]] = None, weightage: Optional[List[float]] = None)¶ Proprietary momentum indicator
Series named as momentum
- Parameters
params (List[float]) – 4 windows, defaults to [63, 126, 189, 252]
weightage – Weightage of each window, summation of it must be equals to 1, defaults to [0.4, 0.2, 0.2, 0.2]
-
on_balance_volume
(enabled: bool = True)¶ On balance volume indicator
Series named as OBV
- Parameters
enabled (bool) – defaults to True
-
parabolic_sar
(params: Optional[List[List[Union[int, float]]]] = None)¶ Parabolic SAR
Series named as SAR_[start]_[increment]_[maxValue], SAR_status_[start]_[increment]_[maxValue]. E.g. SAR_0.02_0.02_0.2.
- Parameters
params (List[List[Union[int, float], Union[int, float], Union[int, float]]]) – List[List[Start, Increment, Max value]], defaults to [[0.02, 0.02, 0.2]]
-
percentage_change
(enabled: bool = True)¶ Percentage change indicator (today against yesterday)
Series named as percentage_change
- Parameters
enabled (bool) – defaults to True
-
pivot
(enabled: bool = True)¶ Proprietary pivot indicator
Series named as upPivot, downPivot
- Parameters
enabled (bool) – defaults to True
-
roc
(params: Optional[List[int]] = None)¶ Rate of change
Series named as ROC_[Period]. E.g. ROC_9.
- Parameters
params (List[int]) – Arrays of roc period, defaults to [9]
-
rsi
(params: Optional[List[int]] = None)¶ Relative Strength Index
Series named as RSI_[period]. E.g. RSI_14
- Parameters
params (List[int]) – Arrays of RSI period, defaults to [14]
-
sma
(params: Optional[List[int]] = None)¶ Simple Moving Average.
Series named as SMA_[param]. E.g. SMA_5, SMA_10.
- Parameters
params (List[int]) – Arrays of SMA period, defaults to [5, 10, 13, 20, 26, 50, 150, 200]
-
sma_ema
(params: Optional[List[List[Union[str, int]]]] = None)¶ Sma_ema indicator
Series named as breadth_sma5_[confidence_level], breadth_ema4_[confidence_level]. E.g. breadth_sma5_75
Confidence level is restricted to 75, 80, 85, 90.
- Parameters
params (List[List[Union[str, int]]]) – List[List[Union[sma5/ema4, confidence_level]]]
-
smart_money
(params: Optional[List[List[Union[int, float]]]] = None)¶ Optimus smart money indicator
Series named as: retailer_[banker_base]_[banker_rsi_period]_[hot_money_rsi_base]_[hot_money_rsi_period]_[sensitivity_banker]_[sensitivity_hot_money]_[banker_ma]_[retailer_ma] hotMoney_[banker_base]_[banker_rsi_period]_[hot_money_rsi_base]_[hot_money_rsi_period]_[sensitivity_banker]_[sensitivity_hot_money]_[banker_ma]_[retailer_ma] banker_[banker_base]_[banker_rsi_period]_[hot_money_rsi_base]_[hot_money_rsi_period]_[sensitivity_banker]_[sensitivity_hot_money]_[banker_ma]_[retailer_ma] bankerMA_[banker_base]_[banker_rsi_period]_[hot_money_rsi_base]_[hot_money_rsi_period]_[sensitivity_banker]_[sensitivity_hot_money]_[banker_ma]_[retailer_ma] retailerMA_[banker_base]_[banker_rsi_period]_[hot_money_rsi_base]_[hot_money_rsi_period]_[sensitivity_banker]_[sensitivity_hot_money]_[banker_ma]_[retailer_ma] E.g. retailer_50_50_30_40_1.5_0.7_10_10.
- Parameters
params (List[List[int, int, int, int, Union[int, float], Union[int, float], int, int]]) – List[List[banker_base, banker_rsi_period, hot_money_rsi_base, hot_money_rsi_period, sensitivity_banker, sensitivity_hot_money, banker_ma, retailer_ma]], defaults to [[50_50_30_40_1.5_0.7_10_10]]
-
smma
(params: Optional[List[int]] = None)¶ Smoothed Moving Average
Series named as SMMA_[param]. E.g. SMMA_4, SMMA_5.
- Parameters
params (List[int]) – Arrays of SMMA period, defaults to [50, 200]
-
stc
(params: Optional[List[List[int]]] = None)¶ Schaff Trend Cycle
Series named as STC_[fast]_[slow]_[percK]_[percD]_[stc].
- Parameters
params (List[List[int, int, int, int, int]]) – List[List[EMA Fast, EMA Slow, Stoch %K Length, Stoch %D Length, STC Length]], defaults to [[23, 50, 10, 3, 3]]
-
stochastic
(params: Optional[List[List[int]]] = None)¶ Stochastic Oscillator
Series named as SOk_[Period]_[MA], SOd_[Period]_[MA]. E.g. SOk_14_3, SOd_14_3.
- Parameters
params (List[List[int, int]]) – List[List[Period, MA]], defaults to [[14, 3]]
-
trend
(params: Optional[List[List[Union[int, float]]]] = None)¶ Trend
Series named as Trend_[MA length]_[Stdev multiple]_[Strong Stdev multiple]_[Lookback Period]
- Parameters
params (List[List[Union[int, float], Union[int, float], Union[int, float], Union[int, float]]]) – List[List[MA length, Stdev multiple, Strong Stdev multiple, Lookback Period]], defaults to [[150, 0.06, 0.16, 15]]
-
vma
(params: Optional[List[int]] = None)¶ Volume Moving Average
Series named as VMA_[param]. E.g. VMA_5, VMA_10.
- Parameters
params (List[int]) – Arrays of VMA period, defaults to [5, 10, 20]
-
volume_average
(params: Optional[List[int]] = None)¶ Volume average
Series named as volume_average_[param]. E.g. volume_average_10.
- Parameters
params (List[int]) – Arrays of volume average period, defaults to [10]
-
wma
(params: Optional[List[int]] = None)¶ Weighted Moving Average
Series named as WMA_[param]. E.g. WMA_5, WMA_10.
- Parameters
params (List[int]) – Arrays of WMA period, defaults to [5, 10]
-
ytd_change
(enabled: bool = True)¶ Year to date change (in percent) indicator
Series named as ytd_change
- Parameters
enabled (bool) – defaults to True
-
optimus.backtesting.selection module¶
-
class
optimus.backtesting.selection.
Action
(value)¶ Bases:
enum.Enum
An enumeration.
-
BUY
= 1¶
-
SELL
= 2¶
-
-
class
optimus.backtesting.selection.
EquityModel
(value)¶ Bases:
enum.Enum
An enumeration.
-
CORE_EQUITY
= 1¶
-
REDUCED_TOTAL_EQUITY
= 3¶
-
TOTAL_EQUITY
= 2¶
-
-
class
optimus.backtesting.selection.
PositionSizing
(value)¶ Bases:
enum.Enum
An enumeration.
-
EQUAL_UNIT
= 1¶
-
PERCENT_RISK
= 3¶
-
PERCENT_VOLATILITY
= 2¶
-
optimus.backtesting.walk_forward module¶
-
class
optimus.backtesting.walk_forward.
WalkForward
(dataframe, data_set, split_ratio_train, split_ratio_test, objective_function, portfolio, backtest, *args)¶ Bases:
object
Walk forward optimization for multiple dataframe.
- Parameters
dataframe (pandas.DataFrame) – Dataframe of stock data
data_set (int) – Number of data set to be split
split_ratio_train (int) – Split ratio of train set
split_ratio_test (int) – Split ratio of test set
objective_function (str) – Objective function to optimize
portfolio (Portfolio) – Portfolio of test set
backtest (types.FunctionType) – Backtest function
*args (args) – values for each parameter to be optimized
-
backtest_test_set
(complete_search=True, strategy_name=None, file_path=None)¶ Start backtest for test set using best params of train set (complete search or prioritized search), store results in folder
- Parameters
complete_search (boolean) – true if train set is backtested using complete search, false if train set is backtested using prioritized search
strategy_name (string) – folder name of strategy
file_path (file path) – file path for csv file of complete search train set
-
backtest_train_set_complete
()¶ Start backtest for train set using complete search.
-
backtest_train_set_prioritized
()¶ Start backtest for train set using prioritized search.
optimus.backtesting.tick_data module¶
-
class
optimus.backtesting.tick_data.
TickData
¶ Bases:
object
Generate a DataFrame for tick data
-
get_TA
(timeframe, indicator: optimus.backtesting.indicator.Indicator)¶ Get technical indicators for a timeframe.
- Parameters
timeframe (string) – Desired timeframe
indicator (Indicator) – Desired indicators
-
get_timeframe
(timeframe, date)¶ Get a timeframe given a date.
- Parameters
timeframe (string) – Desired timeframe
date (string) – Desired date
-
resample
(timeframe)¶ Resample intraday timeframe from tick data dataframe and save into file
Intraday timeframe examples: min, H
- Parameters
timeframe (string) – Desired timeframe
-