Skip to content

Commit

Permalink
Add optional portfolio argument to backtest/walkforward.
Browse files Browse the repository at this point in the history
Allows overriding Portfolio that is used for backtests.
  • Loading branch information
edtechre committed Dec 15, 2023
1 parent 7ba0f2f commit ffabeea
Showing 1 changed file with 16 additions and 8 deletions.
24 changes: 16 additions & 8 deletions src/pybroker/strategy.py
Original file line number Diff line number Diff line change
Expand Up @@ -1022,6 +1022,7 @@ def backtest(
calc_bootstrap: bool = False,
disable_parallel: bool = False,
warmup: Optional[int] = None,
portfolio: Optional[Portfolio] = None,
) -> TestResult:
"""Backtests the trading strategy by running executions that were added
with :meth:`.add_execution`.
Expand Down Expand Up @@ -1070,6 +1071,8 @@ def backtest(
Defaults to ``False``.
warmup: Number of bars that need to pass before running the
executions.
portfolio: Custom :class:`pybroker.portfolio.Portfolio` to use for
backtests.
Returns:
:class:`.TestResult` containing portfolio balances, order
Expand All @@ -1088,6 +1091,7 @@ def backtest(
calc_bootstrap=calc_bootstrap,
disable_parallel=disable_parallel,
warmup=warmup,
portfolio=portfolio,
)

def walkforward(
Expand All @@ -1104,6 +1108,7 @@ def walkforward(
calc_bootstrap: bool = False,
disable_parallel: bool = False,
warmup: Optional[int] = None,
portfolio: Optional[Portfolio] = None,
) -> TestResult:
"""Backtests the trading strategy using `Walkforward Analysis
<https://www.pybroker.com/en/latest/notebooks/6.%20Training%20a%20Model.html#Walkforward-Analysis>`_.
Expand Down Expand Up @@ -1158,6 +1163,8 @@ def walkforward(
Defaults to ``False``.
warmup: Number of bars that need to pass before running the
executions.
portfolio: Custom :class:`pybroker.portfolio.Portfolio` to use for
backtests.
Returns:
:class:`.TestResult` containing portfolio balances, order
Expand Down Expand Up @@ -1217,14 +1224,15 @@ def walkforward(
and self._after_exec_fn is None
and all(map(lambda e: e.fn is None, self._executions))
)
portfolio = Portfolio(
self._config.initial_cash,
self._config.fee_mode,
self._config.fee_amount,
self._fractional_shares_enabled(),
self._config.max_long_positions,
self._config.max_short_positions,
)
if portfolio is None:
portfolio = Portfolio(
self._config.initial_cash,
self._config.fee_mode,
self._config.fee_amount,
self._fractional_shares_enabled(),
self._config.max_long_positions,
self._config.max_short_positions,
)
signals = self._run_walkforward(
portfolio=portfolio,
df=df,
Expand Down

0 comments on commit ffabeea

Please sign in to comment.