Skip to content

Restore original unit of fractional backtest for results/plot. #1247

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 11 commits into from
Mar 30, 2025
55 changes: 54 additions & 1 deletion backtesting/lib.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
import numpy as np
import pandas as pd

from ._plotting import plot_heatmaps as _plot_heatmaps
from ._plotting import plot_heatmaps as _plot_heatmaps, plot
from ._stats import compute_stats as _compute_stats
from ._util import SharedMemoryManager, _Array, _as_str, _batch, _tqdm
from .backtesting import Backtest, Strategy
Expand Down Expand Up @@ -537,8 +537,61 @@ def __init__(self,
data = data.copy()
data[['Open', 'High', 'Low', 'Close']] *= fractional_unit
data['Volume'] /= fractional_unit
self._fractional_unit = fractional_unit
super().__init__(data, *args, **kwargs)

def run(self, **kwargs) -> pd.Series:
result = super().run(**kwargs)

trades: pd.DataFrame = result['_trades']
trades['Size'] *= self._fractional_unit
trades[['EntryPrice', 'ExitPrice', 'TP', 'SL']] /= self._fractional_unit

indicators = result['_strategy']._indicators
for indicator in indicators:
is_overlay = indicator._opts['overlay']
if np.all(is_overlay):
indicator /= self._fractional_unit

return result

def plot(self, *, results: pd.Series = None, filename=None, plot_width=None,
plot_equity=True, plot_return=False, plot_pl=True,
plot_volume=True, plot_drawdown=False, plot_trades=True,
smooth_equity=False, relative_equity=True,
superimpose: Union[bool, str] = True,
resample=True, reverse_indicators=False,
show_legend=True, open_browser=True):

data = self._data.copy()
data[['Open', 'High', 'Low', 'Close']] /= self._fractional_unit
data['Volume'] *= self._fractional_unit

if results is None:
if self._results is None:
raise RuntimeError('First issue `backtest.run()` to obtain results.')
results = self._results

return plot(
results=results,
df=data,
indicators=results._strategy._indicators,
filename=filename,
plot_width=plot_width,
plot_equity=plot_equity,
plot_return=plot_return,
plot_pl=plot_pl,
plot_volume=plot_volume,
plot_drawdown=plot_drawdown,
plot_trades=plot_trades,
smooth_equity=smooth_equity,
relative_equity=relative_equity,
superimpose=superimpose,
resample=resample,
reverse_indicators=reverse_indicators,
show_legend=show_legend,
open_browser=open_browser)


# Prevent pdoc3 documenting __init__ signature of Strategy subclasses
for cls in list(globals().values()):
Expand Down
6 changes: 6 additions & 0 deletions backtesting/test/_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -932,6 +932,12 @@ def test_FractionalBacktest(self):
ubtc_bt = FractionalBacktest(BTCUSD['2015':], SmaCross, fractional_unit=1/1e6, cash=100)
stats = ubtc_bt.run(fast=2, slow=3)
self.assertEqual(stats['# Trades'], 41)
trades = stats['_trades']
self.assertEqual(len(trades), 41)
first_trade = trades[['Size', 'EntryPrice', 'ExitPrice']].head(1)
self.assertEqual(first_trade['Size'][0], -0.422493) # Fractional value -422493
self.assertAlmostEqual(first_trade['EntryPrice'][0], 236.69) # Fractional value 0.000236689
self.assertAlmostEqual(first_trade['ExitPrice'][0], 261.7) # Fractional value 0.000261699

def test_MultiBacktest(self):
btm = MultiBacktest([GOOG, EURUSD, BTCUSD], SmaCross, cash=100_000)
Expand Down
1 change: 1 addition & 0 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
'jupyter_client', # for nbconvert
],
'test': [
'pytest',
'matplotlib',
'scikit-learn',
'sambo',
Expand Down