Skip to content
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

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

Merged
merged 11 commits into from
Mar 30, 2025
28 changes: 23 additions & 5 deletions backtesting/lib.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@

from ._plotting import plot_heatmaps as _plot_heatmaps
from ._stats import compute_stats as _compute_stats
from ._util import SharedMemoryManager, _Array, _as_str, _batch, _tqdm
from ._util import SharedMemoryManager, _Array, _as_str, _batch, _tqdm, patch
from .backtesting import Backtest, Strategy

__pdoc__ = {}
Expand Down Expand Up @@ -533,10 +533,28 @@ def __init__(self,
'Use `FractionalBacktest(..., fractional_unit=)`.',
category=DeprecationWarning, stacklevel=2)
fractional_unit = 1 / kwargs.pop('satoshi')
data = data.copy()
data[['Open', 'High', 'Low', 'Close']] *= fractional_unit
data['Volume'] /= fractional_unit
super().__init__(data, *args, **kwargs)
self._fractional_unit = fractional_unit
with warnings.catch_warnings(record=True):
warnings.filterwarnings(action='ignore', message='frac')
super().__init__(data, *args, **kwargs)

def run(self, **kwargs) -> pd.Series:
data = self._data.copy()
data[['Open', 'High', 'Low', 'Close']] *= self._fractional_unit
data['Volume'] /= self._fractional_unit
with patch(self, '_data', data):
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:
if indicator._opts['overlay']:
indicator /= self._fractional_unit

return result


# Prevent pdoc3 documenting __init__ signature of Strategy subclasses
Expand Down
5 changes: 5 additions & 0 deletions backtesting/test/_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -934,6 +934,11 @@ 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)
trade = trades.iloc[0]
self.assertAlmostEqual(trade['EntryPrice'], 236.69)
self.assertAlmostEqual(stats['_strategy']._indicators[0][trade['EntryBar']], 234.14)

def test_MultiBacktest(self):
import backtesting
Expand Down