Skip to content

Commit e5da148

Browse files
committed
Restore original unit of fractional backtest for results/plot.
1 parent b1a869c commit e5da148

File tree

1 file changed

+53
-1
lines changed

1 file changed

+53
-1
lines changed

backtesting/lib.py

Lines changed: 53 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@
2424
import numpy as np
2525
import pandas as pd
2626

27-
from ._plotting import plot_heatmaps as _plot_heatmaps
27+
from ._plotting import plot_heatmaps as _plot_heatmaps, plot
2828
from ._stats import compute_stats as _compute_stats
2929
from ._util import SharedMemoryManager, _Array, _as_str, _batch, _tqdm
3030
from .backtesting import Backtest, Strategy
@@ -537,8 +537,60 @@ def __init__(self,
537537
data = data.copy()
538538
data[['Open', 'High', 'Low', 'Close']] *= fractional_unit
539539
data['Volume'] /= fractional_unit
540+
self._fractional_unit = fractional_unit
540541
super().__init__(data, *args, **kwargs)
541542

543+
def run(self, **kwargs) -> pd.Series:
544+
result = super().run(**kwargs)
545+
546+
trades: pd.DataFrame = result['_trades']
547+
trades['Size'] *= self._fractional_unit
548+
trades[['EntryPrice', 'ExitPrice', 'TP', 'SL']] /= self._fractional_unit
549+
550+
indicators = result['_strategy']._indicators
551+
for indicator in indicators:
552+
is_overlay = indicator._opts['overlay']
553+
if np.all(is_overlay):
554+
indicator /= self._fractional_unit
555+
556+
return result
557+
558+
def plot(self, *, results: pd.Series = None, filename=None, plot_width=None,
559+
plot_equity=True, plot_return=False, plot_pl=True,
560+
plot_volume=True, plot_drawdown=False, plot_trades=True,
561+
smooth_equity=False, relative_equity=True,
562+
superimpose: Union[bool, str] = True,
563+
resample=True, reverse_indicators=False,
564+
show_legend=True, open_browser=True):
565+
566+
data = self._data.copy()
567+
data[['Open', 'High', 'Low', 'Close']] /= self._fractional_unit
568+
data['Volume'] *= self._fractional_unit
569+
570+
if results is None:
571+
if self._results is None:
572+
raise RuntimeError('First issue `backtest.run()` to obtain results.')
573+
results = self._results
574+
575+
return plot(
576+
results=results,
577+
df=data,
578+
indicators=results._strategy._indicators,
579+
filename=filename,
580+
plot_width=plot_width,
581+
plot_equity=plot_equity,
582+
plot_return=plot_return,
583+
plot_pl=plot_pl,
584+
plot_volume=plot_volume,
585+
plot_drawdown=plot_drawdown,
586+
plot_trades=plot_trades,
587+
smooth_equity=smooth_equity,
588+
relative_equity=relative_equity,
589+
superimpose=superimpose,
590+
resample=resample,
591+
reverse_indicators=reverse_indicators,
592+
show_legend=show_legend,
593+
open_browser=open_browser)
542594

543595
# Prevent pdoc3 documenting __init__ signature of Strategy subclasses
544596
for cls in list(globals().values()):

0 commit comments

Comments
 (0)