Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
DOC: Update docs and examples
  • Loading branch information
kernc committed Jul 14, 2020
commit a95b259aabea2f086a4f1322fb9329048251c241
47 changes: 25 additions & 22 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,9 @@ from backtesting.test import SMA, GOOG

class SmaCross(Strategy):
def init(self):
Close = self.data.Close
self.ma1 = self.I(SMA, Close, 10)
self.ma2 = self.I(SMA, Close, 20)
price = self.data.Close
self.ma1 = self.I(SMA, price, 10)
self.ma2 = self.I(SMA, price, 20)

def next(self):
if crossover(self.ma1, self.ma2):
Expand All @@ -44,8 +44,8 @@ class SmaCross(Strategy):
self.sell()


bt = Backtest(GOOG, SmaCross,
cash=10000, commission=.002)
bt = Backtest(GOOG, SmaCross, commission=.002,
exclusive_orders=True)
bt.run()
bt.plot()
```
Expand All @@ -56,30 +56,33 @@ Results in:
Start 2004-08-19 00:00:00
End 2013-03-01 00:00:00
Duration 3116 days 00:00:00
Exposure [%] 94.29
Equity Final [$] 69665.12
Equity Peak [$] 69722.15
Return [%] 596.65
Exposure Time [%] 94.27
Equity Final [$] 68935.12
Equity Peak [$] 68991.22
Return [%] 589.35
Buy & Hold Return [%] 703.46
Max. Drawdown [%] -33.61
Avg. Drawdown [%] -5.68
Max. Drawdown Duration 689 days 00:00:00
Max. Drawdown [%] -33.08
Avg. Drawdown [%] -5.58
Max. Drawdown Duration 688 days 00:00:00
Avg. Drawdown Duration 41 days 00:00:00
# Trades 93
Win Rate [%] 53.76
Best Trade [%] 56.98
Worst Trade [%] -17.03
Avg. Trade [%] 2.44
Best Trade [%] 57.12
Worst Trade [%] -16.63
Avg. Trade [%] 1.96
Max. Trade Duration 121 days 00:00:00
Avg. Trade Duration 32 days 00:00:00
Expectancy [%] 6.92
SQN 1.77
Sharpe Ratio 0.22
Sortino Ratio 0.54
Calmar Ratio 0.07
_strategy SmaCross
Profit Factor 2.13
Expectancy [%] 6.91
SQN 1.78
Sharpe Ratio 0.18
Sortino Ratio 0.44
Calmar Ratio 0.06
_strategy SmaCross(n1=10, n2=20)
_equity_curve Equ...
_trades Size EntryB...
```
[![plot of trading simulation](https://i.imgur.com/q6OSQD8.png)](https://kernc.github.io/backtesting.py/#example)
[![plot of trading simulation](https://i.imgur.com/xRFNHfg.png)](https://kernc.github.io/backtesting.py/#example)

Find more usage examples in the [documentation].

Expand Down
12 changes: 11 additions & 1 deletion backtesting/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
"""
# Backtesting.py Documentation

.. warning:: v0.2.0 breaking changes
Version 0.2.0 introduced some **breaking API changes**. For quick ways to
migrate existing 0.1.x code, see the implementing
[pull request](https://github.com/kernc/backtesting.py/pull/47/).

## Manuals

* [**Quick Start User Guide**](../examples/Quick Start User Guide.html)
Expand All @@ -11,7 +16,7 @@
* [Multiple Time Frames](../examples/Multiple Time Frames.html)
* [Parameter Heatmap](../examples/Parameter Heatmap.html)

These tutorials are also available as live notebooks:
These tutorials are also available to test as live Jupyter notebooks:
[![Binder](https://mybinder.org/badge_logo.svg)][binder]

[binder]: \
Expand All @@ -22,6 +27,11 @@

* (contributions welcome)

## FAQ

Potentially outdated answers to popular questions can be found on the
[issue tracker](https://github.com/kernc/backtesting.py/issues?q=label%3Aquestion).

## License

This software is licensed under the terms of [AGPL 3.0]{: rel=license},
Expand Down
46 changes: 41 additions & 5 deletions backtesting/backtesting.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
"""
Core backtesting data structures.
Objects from this module can be imported from the top-level
Core framework data structures.
Objects from this module can also be imported from the top-level
module directly, e.g.

from backtesting import Backtest, Strategy

.. warning:: v0.2.0 breaking changes
Version 0.2.0 introduced some **breaking API changes**. For quick ways to
migrate existing 0.1.x code, see the implementing
[pull request](https://github.com/kernc/backtesting.py/pull/47/).
"""
import multiprocessing as mp
import os
Expand Down Expand Up @@ -962,7 +967,7 @@ def __init__(self,
To run the backtest using e.g. 50:1 leverge that your broker allows,
set margin to `0.02` (1 / leverage).

If `trade_on_close` is `True`, market orders will be executed
If `trade_on_close` is `True`, market orders will be filled
with respect to the current bar's closing price instead of the
next bar's open.

Expand Down Expand Up @@ -1029,6 +1034,37 @@ def run(self, **kwargs) -> pd.Series:
Run the backtest. Returns `pd.Series` with results and statistics.

Keyword arguments are interpreted as strategy parameters.

>>> Backtest(GOOG, SmaCross).run()
Start 2004-08-19 00:00:00
End 2013-03-01 00:00:00
Duration 3116 days 00:00:00
Exposure Time [%] 93.9944
Equity Final [$] 51959.9
Equity Peak [$] 75787.4
Return [%] 419.599
Buy & Hold Return [%] 703.458
Max. Drawdown [%] -47.9801
Avg. Drawdown [%] -5.92585
Max. Drawdown Duration 584 days 00:00:00
Avg. Drawdown Duration 41 days 00:00:00
# Trades 65
Win Rate [%] 46.1538
Best Trade [%] 53.596
Worst Trade [%] -18.3989
Avg. Trade [%] 2.35371
Max. Trade Duration 183 days 00:00:00
Avg. Trade Duration 46 days 00:00:00
Profit Factor 2.08802
Expectancy [%] 8.79171
SQN 0.916893
Sharpe Ratio 0.179141
Sortino Ratio 0.55887
Calmar Ratio 0.049056
_strategy SmaCross
_equity_curve Eq...
_trades Size EntryB...
dtype: object
"""
data = _Data(self._data.copy(deep=False))
broker = self._broker(data=data) # type: _Broker
Expand Down Expand Up @@ -1160,7 +1196,7 @@ def __getattr__(self, item):
raise ValueError('No admissible parameter combinations to test')

if len(param_combos) > 300:
warnings.warn('Searching best of {} configurations.'.format(len(param_combos)),
warnings.warn('Searching for best of {} configurations.'.format(len(param_combos)),
stacklevel=2)

heatmap = pd.Series(np.nan,
Expand Down Expand Up @@ -1367,7 +1403,7 @@ def plot(self, *, results: pd.Series = None, filename=None, plot_width=None,
a separate drawdown graph section.

If `smooth_equity` is `True`, the equity graph will be
interpolated between points of cash-only positions,
interpolated between fixed points at trade closing times,
unaffected by any interim asset volatility.

If `relative_equity` is `True`, scale and label equity graph axis
Expand Down
4 changes: 2 additions & 2 deletions backtesting/lib.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ def resample_apply(rule: str,
a time frame to resample `series` to.

[Pandas offset string]: \
http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases
http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases

`func` is the indicator function to apply on the resampled series.

Expand All @@ -202,7 +202,7 @@ def init(self):
self.sma = resample_apply(
'D', SMA, self.data.Close, 10, plot=False)

This short snippet is roughly equivalent to:
The above short snippet is roughly equivalent to:

class System(Strategy):
def init(self):
Expand Down
Loading