overfitting 0.4.1__tar.gz → 0.4.2__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {overfitting-0.4.1 → overfitting-0.4.2}/PKG-INFO +5 -11
- {overfitting-0.4.1 → overfitting-0.4.2}/README.md +4 -9
- {overfitting-0.4.1 → overfitting-0.4.2}/overfitting/__init__.py +0 -1
- overfitting-0.4.2/overfitting/data.py +89 -0
- overfitting-0.4.2/overfitting/indicators.py +210 -0
- {overfitting-0.4.1 → overfitting-0.4.2}/overfitting/strategy.py +58 -12
- {overfitting-0.4.1 → overfitting-0.4.2}/overfitting.egg-info/PKG-INFO +5 -11
- {overfitting-0.4.1 → overfitting-0.4.2}/overfitting.egg-info/SOURCES.txt +1 -2
- {overfitting-0.4.1 → overfitting-0.4.2}/overfitting.egg-info/requires.txt +0 -1
- {overfitting-0.4.1 → overfitting-0.4.2}/pyproject.toml +1 -2
- overfitting-0.4.1/overfitting/analysis/viewer.py +0 -894
- overfitting-0.4.1/overfitting/data.py +0 -89
- overfitting-0.4.1/overfitting/indicators.py +0 -207
- {overfitting-0.4.1 → overfitting-0.4.2}/LICENSE +0 -0
- {overfitting-0.4.1 → overfitting-0.4.2}/overfitting/analysis/__init__.py +0 -0
- {overfitting-0.4.1 → overfitting-0.4.2}/overfitting/analysis/graph.py +0 -0
- {overfitting-0.4.1 → overfitting-0.4.2}/overfitting/analysis/report.py +0 -0
- {overfitting-0.4.1 → overfitting-0.4.2}/overfitting/broker.py +0 -0
- {overfitting-0.4.1 → overfitting-0.4.2}/overfitting/errors.py +0 -0
- {overfitting-0.4.1 → overfitting-0.4.2}/overfitting/order.py +0 -0
- {overfitting-0.4.1 → overfitting-0.4.2}/overfitting/position.py +0 -0
- {overfitting-0.4.1 → overfitting-0.4.2}/overfitting/slippage.py +0 -0
- {overfitting-0.4.1 → overfitting-0.4.2}/overfitting/types.py +0 -0
- {overfitting-0.4.1 → overfitting-0.4.2}/overfitting.egg-info/dependency_links.txt +0 -0
- {overfitting-0.4.1 → overfitting-0.4.2}/overfitting.egg-info/top_level.txt +0 -0
- {overfitting-0.4.1 → overfitting-0.4.2}/setup.cfg +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: overfitting
|
|
3
|
-
Version: 0.4.
|
|
3
|
+
Version: 0.4.2
|
|
4
4
|
Summary: A Robust Futures CryptoCurrency Backtesting Library.
|
|
5
5
|
Author-email: Dohyun Kim <dohyun.k.july@gmail.com>
|
|
6
6
|
License: MIT
|
|
@@ -24,7 +24,6 @@ Requires-Dist: seaborn
|
|
|
24
24
|
Requires-Dist: matplotlib
|
|
25
25
|
Requires-Dist: scipy
|
|
26
26
|
Requires-Dist: plotly
|
|
27
|
-
Requires-Dist: PySide6
|
|
28
27
|
Provides-Extra: examples
|
|
29
28
|
Requires-Dist: notebook; extra == "examples"
|
|
30
29
|
Requires-Dist: ipykernel; extra == "examples"
|
|
@@ -41,15 +40,13 @@ Overfitting simulates a realistic crypto futures trading environment including
|
|
|
41
40
|
- Four Different Order Types: LIMIT, MARKET, STOP_LIMIT, STOP_MARKET
|
|
42
41
|
- Slippage/Commission Setting
|
|
43
42
|
|
|
44
|
-

|
|
45
|
-
|
|
46
43
|
## Installation
|
|
47
44
|
$ pip install overfitting
|
|
48
45
|
|
|
49
46
|
## Usage
|
|
50
47
|
```python
|
|
51
48
|
import pandas as pd
|
|
52
|
-
from overfitting import Strategy
|
|
49
|
+
from overfitting import Strategy
|
|
53
50
|
from overfitting.indicators import SMA
|
|
54
51
|
|
|
55
52
|
def load_data():
|
|
@@ -62,14 +59,14 @@ def load_data():
|
|
|
62
59
|
df = df.loc[start_time:]
|
|
63
60
|
|
|
64
61
|
return df, benchamrk_df
|
|
65
|
-
|
|
62
|
+
|
|
66
63
|
class MyStrategy(Strategy):
|
|
67
64
|
def init(self):
|
|
68
65
|
self.asset = 'BTC'
|
|
69
66
|
self.set_leverage(self.asset, 1)
|
|
70
67
|
|
|
71
|
-
self.sma_short = SMA
|
|
72
|
-
self.sma_long = SMA
|
|
68
|
+
self.sma_short = self.indicator(SMA, self.asset, window=20)
|
|
69
|
+
self.sma_long = self.indicator(SMA, self.asset, window=50)
|
|
73
70
|
|
|
74
71
|
def next(self, i):
|
|
75
72
|
if i == 0:
|
|
@@ -109,9 +106,6 @@ strategy = MyStrategy(
|
|
|
109
106
|
)
|
|
110
107
|
returns = strategy.run()
|
|
111
108
|
strategy.plot(returns)
|
|
112
|
-
|
|
113
|
-
# Show Backtest Viewer UI
|
|
114
|
-
# BacktestViewer(strategy).show()
|
|
115
109
|
```
|
|
116
110
|
|
|
117
111
|
Results
|
|
@@ -6,15 +6,13 @@ Overfitting simulates a realistic crypto futures trading environment including
|
|
|
6
6
|
- Four Different Order Types: LIMIT, MARKET, STOP_LIMIT, STOP_MARKET
|
|
7
7
|
- Slippage/Commission Setting
|
|
8
8
|
|
|
9
|
-

|
|
10
|
-
|
|
11
9
|
## Installation
|
|
12
10
|
$ pip install overfitting
|
|
13
11
|
|
|
14
12
|
## Usage
|
|
15
13
|
```python
|
|
16
14
|
import pandas as pd
|
|
17
|
-
from overfitting import Strategy
|
|
15
|
+
from overfitting import Strategy
|
|
18
16
|
from overfitting.indicators import SMA
|
|
19
17
|
|
|
20
18
|
def load_data():
|
|
@@ -27,14 +25,14 @@ def load_data():
|
|
|
27
25
|
df = df.loc[start_time:]
|
|
28
26
|
|
|
29
27
|
return df, benchamrk_df
|
|
30
|
-
|
|
28
|
+
|
|
31
29
|
class MyStrategy(Strategy):
|
|
32
30
|
def init(self):
|
|
33
31
|
self.asset = 'BTC'
|
|
34
32
|
self.set_leverage(self.asset, 1)
|
|
35
33
|
|
|
36
|
-
self.sma_short = SMA
|
|
37
|
-
self.sma_long = SMA
|
|
34
|
+
self.sma_short = self.indicator(SMA, self.asset, window=20)
|
|
35
|
+
self.sma_long = self.indicator(SMA, self.asset, window=50)
|
|
38
36
|
|
|
39
37
|
def next(self, i):
|
|
40
38
|
if i == 0:
|
|
@@ -74,9 +72,6 @@ strategy = MyStrategy(
|
|
|
74
72
|
)
|
|
75
73
|
returns = strategy.run()
|
|
76
74
|
strategy.plot(returns)
|
|
77
|
-
|
|
78
|
-
# Show Backtest Viewer UI
|
|
79
|
-
# BacktestViewer(strategy).show()
|
|
80
75
|
```
|
|
81
76
|
|
|
82
77
|
Results
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import pandas as pd
|
|
2
|
+
import numpy as np
|
|
3
|
+
from types import SimpleNamespace
|
|
4
|
+
from pandas.api.types import is_datetime64_any_dtype, is_integer_dtype, is_float_dtype
|
|
5
|
+
from overfitting.errors import InitializationError
|
|
6
|
+
|
|
7
|
+
REQUIRED_OHLC = ("open", "high", "low", "close")
|
|
8
|
+
|
|
9
|
+
class Data(dict):
|
|
10
|
+
"""
|
|
11
|
+
data = Data({"BTCUSDT": df_btc, "ETHUSDT": df_eth})
|
|
12
|
+
data["BTCUSDT"].close[i] # close price of BTC at step i
|
|
13
|
+
data.index[i] # the timestamp at step i
|
|
14
|
+
data.symbols # ("BTCUSDT", "ETHUSDT")
|
|
15
|
+
len(data) # how many bars there are
|
|
16
|
+
"""
|
|
17
|
+
def __init__(self, frames: dict[str, pd.DataFrame]):
|
|
18
|
+
if not isinstance(frames, dict) or not frames:
|
|
19
|
+
raise InitializationError("Pass a non-empty dict mapping symbol -> DataFrame.")
|
|
20
|
+
|
|
21
|
+
bars = {symbol: self._bars_from_frame(df, symbol) for symbol, df in frames.items()}
|
|
22
|
+
self._check_aligned_timelines(bars)
|
|
23
|
+
|
|
24
|
+
super().__init__(bars)
|
|
25
|
+
self.symbols = tuple(bars)
|
|
26
|
+
self.index = next(iter(bars.values())).timestamp
|
|
27
|
+
|
|
28
|
+
def __len__(self) -> int:
|
|
29
|
+
return len(self.index)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _bars_from_frame(self, df: pd.DataFrame, symbol: str) -> SimpleNamespace:
|
|
33
|
+
"""Turn one symbol's DataFrame into a namespace of numpy arrays."""
|
|
34
|
+
if not isinstance(df, pd.DataFrame) or df.empty:
|
|
35
|
+
raise InitializationError(f"'{symbol}': expected a non-empty DataFrame.")
|
|
36
|
+
|
|
37
|
+
missing = [c for c in REQUIRED_OHLC if c not in df.columns]
|
|
38
|
+
if missing:
|
|
39
|
+
raise InitializationError(
|
|
40
|
+
f"'{symbol}': missing required columns {missing}. Got: {list(df.columns)}"
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
timestamps = self._pull_timestamps(df, symbol)
|
|
44
|
+
|
|
45
|
+
arrays = {col: df[col].to_numpy() for col in df.columns}
|
|
46
|
+
arrays["timestamp"] = timestamps
|
|
47
|
+
return SimpleNamespace(**arrays)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _pull_timestamps(self, df: pd.DataFrame, symbol: str) -> np.ndarray:
|
|
51
|
+
"""Find the timestamp series — either a column or the DatetimeIndex — and normalise it."""
|
|
52
|
+
if "timestamp" in df.columns:
|
|
53
|
+
ts = df["timestamp"]
|
|
54
|
+
elif isinstance(df.index, pd.DatetimeIndex) or df.index.name == "timestamp":
|
|
55
|
+
ts = pd.Series(df.index, name="timestamp")
|
|
56
|
+
else:
|
|
57
|
+
raise InitializationError(
|
|
58
|
+
f"'{symbol}': add a 'timestamp' column or use a DatetimeIndex."
|
|
59
|
+
)
|
|
60
|
+
return self._to_datetime_ns(ts).to_numpy()
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _to_datetime_ns(self, ts: pd.Series) -> pd.Series:
|
|
64
|
+
"""Coerce whatever the user gave us into tz-naive datetime64[ns]."""
|
|
65
|
+
if is_datetime64_any_dtype(ts):
|
|
66
|
+
dt = pd.to_datetime(ts)
|
|
67
|
+
try:
|
|
68
|
+
return dt.tz_localize(None)
|
|
69
|
+
except Exception:
|
|
70
|
+
return dt
|
|
71
|
+
|
|
72
|
+
if is_integer_dtype(ts) or is_float_dtype(ts):
|
|
73
|
+
# Big numbers look like milliseconds; smaller ones look like seconds.
|
|
74
|
+
unit = "ms" if pd.Series(ts).max() > 1e12 else "s"
|
|
75
|
+
return pd.to_datetime(ts, unit=unit)
|
|
76
|
+
|
|
77
|
+
return pd.to_datetime(ts, errors="raise")
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _check_aligned_timelines(self, bars: dict[str, SimpleNamespace]) -> None:
|
|
81
|
+
"""All symbols must share the same timeline — for now."""
|
|
82
|
+
# TODO: auto-fill / reindex so symbols with different timelines can co-exist.
|
|
83
|
+
iterator = iter(bars.items())
|
|
84
|
+
_, first = next(iterator)
|
|
85
|
+
for symbol, b in iterator:
|
|
86
|
+
if len(b.timestamp) != len(first.timestamp) or not np.array_equal(b.timestamp, first.timestamp):
|
|
87
|
+
raise InitializationError(
|
|
88
|
+
f"'{symbol}' timeline doesn't match the other symbols."
|
|
89
|
+
)
|
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
import pandas as pd
|
|
2
|
+
from abc import ABC, abstractmethod
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class Indicator(ABC):
|
|
6
|
+
"""
|
|
7
|
+
Base class for indicators. Subclasses take pandas Series as inputs and
|
|
8
|
+
write their result to ``self._values`` inside ``compute()``.
|
|
9
|
+
|
|
10
|
+
Single-output indicators set ``self._values`` to a Series.
|
|
11
|
+
Multi-output indicators set it to a DataFrame; each column is exposed
|
|
12
|
+
as an attribute (e.g. ``macd.signal``).
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
def __init__(self):
|
|
16
|
+
self._values: pd.Series | pd.DataFrame | None = None
|
|
17
|
+
self.compute()
|
|
18
|
+
if isinstance(self._values, pd.DataFrame):
|
|
19
|
+
for col in self._values.columns:
|
|
20
|
+
setattr(self, col, self._values[col])
|
|
21
|
+
|
|
22
|
+
@property
|
|
23
|
+
def values(self) -> pd.Series | pd.DataFrame | None:
|
|
24
|
+
return self._values
|
|
25
|
+
|
|
26
|
+
@abstractmethod
|
|
27
|
+
def compute(self):
|
|
28
|
+
pass
|
|
29
|
+
|
|
30
|
+
def __getitem__(self, i: int):
|
|
31
|
+
if self._values is None:
|
|
32
|
+
raise ValueError(f"{self.__class__.__name__} has not computed yet")
|
|
33
|
+
return self._values.iloc[i]
|
|
34
|
+
|
|
35
|
+
def ready(self, i: int) -> bool:
|
|
36
|
+
"""True if the indicator has a non-NaN value at index ``i``."""
|
|
37
|
+
if self._values is None or i < 0 or i >= len(self._values):
|
|
38
|
+
return False
|
|
39
|
+
row = self._values.iloc[i]
|
|
40
|
+
if isinstance(row, pd.Series):
|
|
41
|
+
return not row.isna().any()
|
|
42
|
+
return not pd.isna(row)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class SMA(Indicator):
|
|
46
|
+
def __init__(self, series: pd.Series, window: int = 20):
|
|
47
|
+
self.series = series
|
|
48
|
+
self.window = window
|
|
49
|
+
super().__init__()
|
|
50
|
+
|
|
51
|
+
def compute(self):
|
|
52
|
+
self._values = self.series.rolling(self.window).mean().shift(1)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class EMA(Indicator):
|
|
56
|
+
def __init__(self, series: pd.Series, span: int = 20):
|
|
57
|
+
self.series = series
|
|
58
|
+
self.span = span
|
|
59
|
+
super().__init__()
|
|
60
|
+
|
|
61
|
+
def compute(self):
|
|
62
|
+
self._values = self.series.ewm(span=self.span, adjust=False).mean().shift(1)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class WMA(Indicator):
|
|
66
|
+
def __init__(self, series: pd.Series, window: int = 20):
|
|
67
|
+
self.series = series
|
|
68
|
+
self.window = window
|
|
69
|
+
super().__init__()
|
|
70
|
+
|
|
71
|
+
def compute(self):
|
|
72
|
+
weights = pd.Series(range(1, self.window + 1), dtype=float)
|
|
73
|
+
|
|
74
|
+
def _wma(x):
|
|
75
|
+
return (x * weights).sum() / weights.sum()
|
|
76
|
+
|
|
77
|
+
self._values = self.series.rolling(self.window).apply(_wma, raw=False).shift(1)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
class RSI(Indicator):
|
|
81
|
+
def __init__(self, series: pd.Series, window: int = 14):
|
|
82
|
+
self.series = series
|
|
83
|
+
self.window = window
|
|
84
|
+
super().__init__()
|
|
85
|
+
|
|
86
|
+
def compute(self):
|
|
87
|
+
delta = self.series.diff()
|
|
88
|
+
gain = delta.clip(lower=0)
|
|
89
|
+
loss = -delta.clip(upper=0)
|
|
90
|
+
|
|
91
|
+
avg_gain = gain.ewm(alpha=1 / self.window, adjust=False, min_periods=self.window).mean()
|
|
92
|
+
avg_loss = loss.ewm(alpha=1 / self.window, adjust=False, min_periods=self.window).mean()
|
|
93
|
+
|
|
94
|
+
rs = avg_gain / avg_loss
|
|
95
|
+
self._values = (100 - (100 / (1 + rs))).shift(1)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
class MACD(Indicator):
|
|
99
|
+
def __init__(
|
|
100
|
+
self,
|
|
101
|
+
series: pd.Series,
|
|
102
|
+
fast: int = 12,
|
|
103
|
+
slow: int = 26,
|
|
104
|
+
signal: int = 9,
|
|
105
|
+
):
|
|
106
|
+
self.series = series
|
|
107
|
+
self.fast = fast
|
|
108
|
+
self.slow = slow
|
|
109
|
+
self.signal = signal
|
|
110
|
+
super().__init__()
|
|
111
|
+
|
|
112
|
+
def compute(self):
|
|
113
|
+
fast_ema = self.series.ewm(span=self.fast, adjust=False).mean()
|
|
114
|
+
slow_ema = self.series.ewm(span=self.slow, adjust=False).mean()
|
|
115
|
+
|
|
116
|
+
macd = fast_ema - slow_ema
|
|
117
|
+
signal = macd.ewm(span=self.signal, adjust=False).mean()
|
|
118
|
+
hist = macd - signal
|
|
119
|
+
|
|
120
|
+
self._values = pd.DataFrame({
|
|
121
|
+
"macd": macd.shift(1),
|
|
122
|
+
"signal": signal.shift(1),
|
|
123
|
+
"hist": hist.shift(1),
|
|
124
|
+
})
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
class Stochastic(Indicator):
|
|
128
|
+
def __init__(
|
|
129
|
+
self,
|
|
130
|
+
high: pd.Series,
|
|
131
|
+
low: pd.Series,
|
|
132
|
+
close: pd.Series,
|
|
133
|
+
k_window: int = 14,
|
|
134
|
+
d_window: int = 3,
|
|
135
|
+
smooth_k: int = 3,
|
|
136
|
+
):
|
|
137
|
+
self.high = high
|
|
138
|
+
self.low = low
|
|
139
|
+
self.close = close
|
|
140
|
+
self.k_window = k_window
|
|
141
|
+
self.d_window = d_window
|
|
142
|
+
self.smooth_k = smooth_k
|
|
143
|
+
super().__init__()
|
|
144
|
+
|
|
145
|
+
def compute(self):
|
|
146
|
+
lowest_low = self.low.rolling(self.k_window).min()
|
|
147
|
+
highest_high = self.high.rolling(self.k_window).max()
|
|
148
|
+
|
|
149
|
+
raw_k = 100 * (self.close - lowest_low) / (highest_high - lowest_low)
|
|
150
|
+
k = raw_k.rolling(self.smooth_k).mean()
|
|
151
|
+
d_line = k.rolling(self.d_window).mean()
|
|
152
|
+
|
|
153
|
+
self._values = pd.DataFrame({
|
|
154
|
+
"k": k.shift(1),
|
|
155
|
+
"d": d_line.shift(1),
|
|
156
|
+
})
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
class BollingerBands(Indicator):
|
|
160
|
+
def __init__(
|
|
161
|
+
self,
|
|
162
|
+
series: pd.Series,
|
|
163
|
+
window: int = 20,
|
|
164
|
+
num_std: float = 2.0,
|
|
165
|
+
):
|
|
166
|
+
self.series = series
|
|
167
|
+
self.window = window
|
|
168
|
+
self.num_std = num_std
|
|
169
|
+
super().__init__()
|
|
170
|
+
|
|
171
|
+
def compute(self):
|
|
172
|
+
mid = self.series.rolling(self.window).mean()
|
|
173
|
+
std = self.series.rolling(self.window).std()
|
|
174
|
+
|
|
175
|
+
upper = mid + self.num_std * std
|
|
176
|
+
lower = mid - self.num_std * std
|
|
177
|
+
|
|
178
|
+
self._values = pd.DataFrame({
|
|
179
|
+
"middle": mid.shift(1),
|
|
180
|
+
"upper": upper.shift(1),
|
|
181
|
+
"lower": lower.shift(1),
|
|
182
|
+
"bandwidth": ((upper - lower) / mid).shift(1),
|
|
183
|
+
})
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
class ATR(Indicator):
|
|
187
|
+
def __init__(
|
|
188
|
+
self,
|
|
189
|
+
high: pd.Series,
|
|
190
|
+
low: pd.Series,
|
|
191
|
+
close: pd.Series,
|
|
192
|
+
window: int = 14,
|
|
193
|
+
):
|
|
194
|
+
self.high = high
|
|
195
|
+
self.low = low
|
|
196
|
+
self.close = close
|
|
197
|
+
self.window = window
|
|
198
|
+
super().__init__()
|
|
199
|
+
|
|
200
|
+
def compute(self):
|
|
201
|
+
prev_close = self.close.shift(1)
|
|
202
|
+
|
|
203
|
+
tr1 = self.high - self.low
|
|
204
|
+
tr2 = (self.high - prev_close).abs()
|
|
205
|
+
tr3 = (self.low - prev_close).abs()
|
|
206
|
+
|
|
207
|
+
tr = pd.concat([tr1, tr2, tr3], axis=1).max(axis=1)
|
|
208
|
+
atr = tr.ewm(alpha=1 / self.window, adjust=False, min_periods=self.window).mean()
|
|
209
|
+
|
|
210
|
+
self._values = atr.shift(1)
|
|
@@ -1,14 +1,18 @@
|
|
|
1
|
+
import inspect
|
|
1
2
|
import os
|
|
2
3
|
import pandas as pd
|
|
3
4
|
import numpy as np
|
|
4
5
|
from abc import abstractmethod
|
|
5
|
-
from typing import List, Optional, Dict
|
|
6
|
+
from typing import List, Optional, Dict, Type
|
|
6
7
|
from overfitting.data import Data
|
|
7
8
|
from overfitting.broker import Broker
|
|
8
9
|
from overfitting.order import Order
|
|
9
10
|
from overfitting.position import Position
|
|
10
11
|
from overfitting.analysis.report import Report
|
|
11
12
|
from overfitting.slippage import SlippageModel
|
|
13
|
+
from overfitting.indicators import Indicator
|
|
14
|
+
|
|
15
|
+
_OHLCV_NAMES = ("open", "high", "low", "close", "volume")
|
|
12
16
|
|
|
13
17
|
class Strategy:
|
|
14
18
|
def __init__(self,
|
|
@@ -123,17 +127,59 @@ class Strategy:
|
|
|
123
127
|
"""
|
|
124
128
|
return dict(self.broker.open_orders.get(symbol, {}))
|
|
125
129
|
|
|
126
|
-
def open(self, symbol: str, i: int):
|
|
127
|
-
return self.
|
|
128
|
-
|
|
129
|
-
def high(self, symbol: str, i: int):
|
|
130
|
-
return self.
|
|
131
|
-
|
|
132
|
-
def low(self, symbol: str, i: int):
|
|
133
|
-
return self.
|
|
134
|
-
|
|
135
|
-
def close(self, symbol: str, i: int):
|
|
136
|
-
return self.
|
|
130
|
+
def open(self, symbol: str, i: Optional[int] = None):
|
|
131
|
+
return self._ohlcv(symbol, "open", i)
|
|
132
|
+
|
|
133
|
+
def high(self, symbol: str, i: Optional[int] = None):
|
|
134
|
+
return self._ohlcv(symbol, "high", i)
|
|
135
|
+
|
|
136
|
+
def low(self, symbol: str, i: Optional[int] = None):
|
|
137
|
+
return self._ohlcv(symbol, "low", i)
|
|
138
|
+
|
|
139
|
+
def close(self, symbol: str, i: Optional[int] = None):
|
|
140
|
+
return self._ohlcv(symbol, "close", i)
|
|
141
|
+
|
|
142
|
+
def _ohlcv(self, symbol: str, name: str, i: Optional[int]):
|
|
143
|
+
"""Scalar at bar ``i`` when ``i`` is given; otherwise the full pandas Series."""
|
|
144
|
+
arr = getattr(self.broker._d(symbol), name)
|
|
145
|
+
if i is None:
|
|
146
|
+
return pd.Series(arr, name=name)
|
|
147
|
+
return arr[i]
|
|
148
|
+
|
|
149
|
+
def indicator(self, cls: Type[Indicator], symbol: str, *, source: str = "close", **kwargs) -> Indicator:
|
|
150
|
+
"""
|
|
151
|
+
Build an indicator by binding the symbol's OHLCV series to ``cls``'s constructor.
|
|
152
|
+
|
|
153
|
+
- Constructor params named one of ``open / high / low / close / volume``
|
|
154
|
+
are filled with the matching series for ``symbol``.
|
|
155
|
+
- A param named ``series`` is filled with the ``source`` column
|
|
156
|
+
(default ``"close"``; override per-call with ``source=`` ).
|
|
157
|
+
- Any other kwargs are forwarded as-is.
|
|
158
|
+
"""
|
|
159
|
+
sig = inspect.signature(cls.__init__)
|
|
160
|
+
bound = {}
|
|
161
|
+
|
|
162
|
+
for name, param in sig.parameters.items():
|
|
163
|
+
if name == "self":
|
|
164
|
+
continue
|
|
165
|
+
if name in _OHLCV_NAMES:
|
|
166
|
+
bound[name] = self._ohlcv(symbol, name, None)
|
|
167
|
+
elif name == "series":
|
|
168
|
+
if source not in _OHLCV_NAMES:
|
|
169
|
+
raise ValueError(
|
|
170
|
+
f"source={source!r} must be one of {_OHLCV_NAMES}"
|
|
171
|
+
)
|
|
172
|
+
bound[name] = self._ohlcv(symbol, source, None)
|
|
173
|
+
elif name in kwargs:
|
|
174
|
+
bound[name] = kwargs.pop(name)
|
|
175
|
+
# else: rely on the indicator's default
|
|
176
|
+
|
|
177
|
+
if kwargs:
|
|
178
|
+
raise TypeError(
|
|
179
|
+
f"{cls.__name__}: unexpected keyword arguments {list(kwargs)}"
|
|
180
|
+
)
|
|
181
|
+
|
|
182
|
+
return cls(**bound)
|
|
137
183
|
|
|
138
184
|
def bars(self, symbol: str, i: int) -> tuple:
|
|
139
185
|
"""
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: overfitting
|
|
3
|
-
Version: 0.4.
|
|
3
|
+
Version: 0.4.2
|
|
4
4
|
Summary: A Robust Futures CryptoCurrency Backtesting Library.
|
|
5
5
|
Author-email: Dohyun Kim <dohyun.k.july@gmail.com>
|
|
6
6
|
License: MIT
|
|
@@ -24,7 +24,6 @@ Requires-Dist: seaborn
|
|
|
24
24
|
Requires-Dist: matplotlib
|
|
25
25
|
Requires-Dist: scipy
|
|
26
26
|
Requires-Dist: plotly
|
|
27
|
-
Requires-Dist: PySide6
|
|
28
27
|
Provides-Extra: examples
|
|
29
28
|
Requires-Dist: notebook; extra == "examples"
|
|
30
29
|
Requires-Dist: ipykernel; extra == "examples"
|
|
@@ -41,15 +40,13 @@ Overfitting simulates a realistic crypto futures trading environment including
|
|
|
41
40
|
- Four Different Order Types: LIMIT, MARKET, STOP_LIMIT, STOP_MARKET
|
|
42
41
|
- Slippage/Commission Setting
|
|
43
42
|
|
|
44
|
-

|
|
45
|
-
|
|
46
43
|
## Installation
|
|
47
44
|
$ pip install overfitting
|
|
48
45
|
|
|
49
46
|
## Usage
|
|
50
47
|
```python
|
|
51
48
|
import pandas as pd
|
|
52
|
-
from overfitting import Strategy
|
|
49
|
+
from overfitting import Strategy
|
|
53
50
|
from overfitting.indicators import SMA
|
|
54
51
|
|
|
55
52
|
def load_data():
|
|
@@ -62,14 +59,14 @@ def load_data():
|
|
|
62
59
|
df = df.loc[start_time:]
|
|
63
60
|
|
|
64
61
|
return df, benchamrk_df
|
|
65
|
-
|
|
62
|
+
|
|
66
63
|
class MyStrategy(Strategy):
|
|
67
64
|
def init(self):
|
|
68
65
|
self.asset = 'BTC'
|
|
69
66
|
self.set_leverage(self.asset, 1)
|
|
70
67
|
|
|
71
|
-
self.sma_short = SMA
|
|
72
|
-
self.sma_long = SMA
|
|
68
|
+
self.sma_short = self.indicator(SMA, self.asset, window=20)
|
|
69
|
+
self.sma_long = self.indicator(SMA, self.asset, window=50)
|
|
73
70
|
|
|
74
71
|
def next(self, i):
|
|
75
72
|
if i == 0:
|
|
@@ -109,9 +106,6 @@ strategy = MyStrategy(
|
|
|
109
106
|
)
|
|
110
107
|
returns = strategy.run()
|
|
111
108
|
strategy.plot(returns)
|
|
112
|
-
|
|
113
|
-
# Show Backtest Viewer UI
|
|
114
|
-
# BacktestViewer(strategy).show()
|
|
115
109
|
```
|
|
116
110
|
|
|
117
111
|
Results
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "overfitting"
|
|
7
|
-
version = "0.4.
|
|
7
|
+
version = "0.4.2"
|
|
8
8
|
description = "A Robust Futures CryptoCurrency Backtesting Library."
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.8"
|
|
@@ -37,7 +37,6 @@ dependencies = [
|
|
|
37
37
|
"matplotlib",
|
|
38
38
|
"scipy",
|
|
39
39
|
"plotly",
|
|
40
|
-
"PySide6",
|
|
41
40
|
]
|
|
42
41
|
|
|
43
42
|
[project.optional-dependencies]
|