overfitting 0.3.0__tar.gz → 0.3.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.

Potentially problematic release.


This version of overfitting might be problematic. Click here for more details.

Files changed (28) hide show
  1. {overfitting-0.3.0 → overfitting-0.3.2}/PKG-INFO +13 -16
  2. {overfitting-0.3.0 → overfitting-0.3.2}/README.md +12 -15
  3. overfitting-0.3.2/overfitting/__init__.py +3 -0
  4. overfitting-0.3.0/overfitting/plot/performance.py → overfitting-0.3.2/overfitting/analysis/report.py +2 -2
  5. {overfitting-0.3.0/overfitting → overfitting-0.3.2/overfitting/analysis}/viewer.py +0 -2
  6. {overfitting-0.3.0 → overfitting-0.3.2}/overfitting/broker.py +3 -3
  7. {overfitting-0.3.0 → overfitting-0.3.2}/overfitting/data.py +2 -2
  8. overfitting-0.3.2/overfitting/indicators.py +207 -0
  9. {overfitting-0.3.0 → overfitting-0.3.2}/overfitting/order.py +1 -1
  10. {overfitting-0.3.0 → overfitting-0.3.2}/overfitting/strategy.py +5 -3
  11. {overfitting-0.3.0 → overfitting-0.3.2}/overfitting.egg-info/PKG-INFO +13 -16
  12. {overfitting-0.3.0 → overfitting-0.3.2}/overfitting.egg-info/SOURCES.txt +8 -10
  13. {overfitting-0.3.0 → overfitting-0.3.2}/pyproject.toml +1 -1
  14. overfitting-0.3.0/overfitting/__init__.py +0 -4
  15. overfitting-0.3.0/overfitting/execution/__init__.py +0 -0
  16. overfitting-0.3.0/overfitting/plot/__init__.py +0 -0
  17. overfitting-0.3.0/overfitting/utils/__init__.py +0 -0
  18. {overfitting-0.3.0 → overfitting-0.3.2}/LICENSE +0 -0
  19. {overfitting-0.3.0/overfitting/entities → overfitting-0.3.2/overfitting/analysis}/__init__.py +0 -0
  20. {overfitting-0.3.0/overfitting/plot → overfitting-0.3.2/overfitting/analysis}/graph.py +0 -0
  21. /overfitting-0.3.0/overfitting/utils/error.py → /overfitting-0.3.2/overfitting/errors.py +0 -0
  22. {overfitting-0.3.0 → overfitting-0.3.2}/overfitting/position.py +0 -0
  23. {overfitting-0.3.0/overfitting/execution → overfitting-0.3.2/overfitting}/slippage.py +0 -0
  24. /overfitting-0.3.0/overfitting/entities/order.py → /overfitting-0.3.2/overfitting/types.py +0 -0
  25. {overfitting-0.3.0 → overfitting-0.3.2}/overfitting.egg-info/dependency_links.txt +0 -0
  26. {overfitting-0.3.0 → overfitting-0.3.2}/overfitting.egg-info/requires.txt +0 -0
  27. {overfitting-0.3.0 → overfitting-0.3.2}/overfitting.egg-info/top_level.txt +0 -0
  28. {overfitting-0.3.0 → overfitting-0.3.2}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: overfitting
3
- Version: 0.3.0
3
+ Version: 0.3.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
@@ -59,41 +59,38 @@ def load_data():
59
59
 
60
60
  start_time = pd.to_datetime('2023-01-01 00:00:00')
61
61
  df = df.loc[start_time:]
62
- # Compute short and long SMAs
63
- df['sma_short'] = df['close'].rolling(window=20).mean().shift(1)
64
- df['sma_long'] = df['close'].rolling(window=50).mean().shift(1)
65
62
 
66
63
  return df, benchamrk_df
67
-
64
+
68
65
  class MyStrategy(Strategy):
69
66
  def init(self):
70
67
  self.asset = 'BTC'
71
68
  self.set_leverage(self.asset, 1)
72
69
 
70
+ self.sma_short = SMA(self, self.asset, source="close", window=20)
71
+ self.sma_long = SMA(self, self.asset, source="close", window=50)
72
+
73
73
  def next(self, i):
74
74
  if i == 0:
75
75
  return
76
76
 
77
- sma_short = self.val(self.asset, i, "sma_short")
78
- sma_long = self.val(self.asset, i, "sma_long")
79
- previous_sma_short = self.val(self.asset, i - 1, "sma_short")
80
- previous_sma_long = self.val(self.asset, i - 1, "sma_long")
77
+ sma_short = self.sma_short[i]
78
+ sma_long = self.sma_long[i]
79
+ previous_sma_short = self.sma_short[i - 1]
80
+ previous_sma_long = self.sma_long[i - 1]
81
81
 
82
- # Also skip if values are not available
83
- if (pd.isna(sma_short) or pd.isna(sma_long) or
84
- pd.isna(previous_sma_short) or pd.isna(previous_sma_long)):
82
+ if (
83
+ pd.isna(sma_short) or pd.isna(sma_long) or
84
+ pd.isna(previous_sma_short) or pd.isna(previous_sma_long)
85
+ ):
85
86
  return
86
87
 
87
- # Fetch the current position
88
88
  position = self.get_position(self.asset)
89
89
 
90
90
  # Golden cross (entry)
91
91
  if previous_sma_short <= previous_sma_long and sma_short > sma_long and position.qty == 0:
92
- # First fetch current open price which is the target Price
93
92
  open_price = self.open(self.asset, i)
94
- # Determine Lot Size
95
93
  lot_size = self.get_balance() // open_price
96
- # Create LIMIT ORDER
97
94
  self.limit_order(self.asset, lot_size, open_price)
98
95
 
99
96
  # Death cross (exit)
@@ -24,41 +24,38 @@ def load_data():
24
24
 
25
25
  start_time = pd.to_datetime('2023-01-01 00:00:00')
26
26
  df = df.loc[start_time:]
27
- # Compute short and long SMAs
28
- df['sma_short'] = df['close'].rolling(window=20).mean().shift(1)
29
- df['sma_long'] = df['close'].rolling(window=50).mean().shift(1)
30
27
 
31
28
  return df, benchamrk_df
32
-
29
+
33
30
  class MyStrategy(Strategy):
34
31
  def init(self):
35
32
  self.asset = 'BTC'
36
33
  self.set_leverage(self.asset, 1)
37
34
 
35
+ self.sma_short = SMA(self, self.asset, source="close", window=20)
36
+ self.sma_long = SMA(self, self.asset, source="close", window=50)
37
+
38
38
  def next(self, i):
39
39
  if i == 0:
40
40
  return
41
41
 
42
- sma_short = self.val(self.asset, i, "sma_short")
43
- sma_long = self.val(self.asset, i, "sma_long")
44
- previous_sma_short = self.val(self.asset, i - 1, "sma_short")
45
- previous_sma_long = self.val(self.asset, i - 1, "sma_long")
42
+ sma_short = self.sma_short[i]
43
+ sma_long = self.sma_long[i]
44
+ previous_sma_short = self.sma_short[i - 1]
45
+ previous_sma_long = self.sma_long[i - 1]
46
46
 
47
- # Also skip if values are not available
48
- if (pd.isna(sma_short) or pd.isna(sma_long) or
49
- pd.isna(previous_sma_short) or pd.isna(previous_sma_long)):
47
+ if (
48
+ pd.isna(sma_short) or pd.isna(sma_long) or
49
+ pd.isna(previous_sma_short) or pd.isna(previous_sma_long)
50
+ ):
50
51
  return
51
52
 
52
- # Fetch the current position
53
53
  position = self.get_position(self.asset)
54
54
 
55
55
  # Golden cross (entry)
56
56
  if previous_sma_short <= previous_sma_long and sma_short > sma_long and position.qty == 0:
57
- # First fetch current open price which is the target Price
58
57
  open_price = self.open(self.asset, i)
59
- # Determine Lot Size
60
58
  lot_size = self.get_balance() // open_price
61
- # Create LIMIT ORDER
62
59
  self.limit_order(self.asset, lot_size, open_price)
63
60
 
64
61
  # Death cross (exit)
@@ -0,0 +1,3 @@
1
+ from .strategy import Strategy
2
+ from .slippage import Slippage
3
+ from .analysis.viewer import BacktestViewer
@@ -2,13 +2,13 @@ import pandas as pd
2
2
  import numpy as np
3
3
  import matplotlib.pyplot as plt
4
4
  import seaborn as sns
5
- import overfitting.plot.graph as graph
5
+ import overfitting.analysis.graph as graph
6
6
  from overfitting.order import Order
7
7
  from typing import Optional, Sequence
8
8
  from matplotlib.colors import LinearSegmentedColormap
9
9
  from scipy.stats import skew, kurtosis
10
10
 
11
- class PerformanceReport:
11
+ class Report:
12
12
  def __init__(self,
13
13
  returns_series: pd.Series,
14
14
  trades_list: Sequence[Order],
@@ -1,5 +1,3 @@
1
- from __future__ import annotations
2
-
3
1
  import os, sys, tempfile
4
2
  import pandas as pd
5
3
  import numpy as np
@@ -3,9 +3,9 @@ from typing import List, Dict, Optional, Union, Tuple
3
3
  from overfitting.data import Data, MultiCurrency
4
4
  from overfitting.order import Order
5
5
  from overfitting.position import Position
6
- from overfitting.execution.slippage import SlippageModel
7
- from overfitting.entities.order import OrderType
8
- from overfitting.utils.error import EmptyOrderParameters, InvalidOrderParameters, LiquidationError
6
+ from overfitting.slippage import SlippageModel
7
+ from overfitting.types import OrderType
8
+ from overfitting.errors import EmptyOrderParameters, InvalidOrderParameters, LiquidationError
9
9
 
10
10
  class Broker:
11
11
  def __init__(self,
@@ -1,7 +1,7 @@
1
1
  import pandas as pd
2
2
  import numpy as np
3
3
  from pandas.api.types import is_datetime64_any_dtype, is_integer_dtype, is_float_dtype
4
- from overfitting.utils.error import InitializationError
4
+ from overfitting.errors import InitializationError
5
5
 
6
6
  REQUIRED_OHLC = ("open", "high", "low", "close")
7
7
 
@@ -85,7 +85,7 @@ class Data(dict):
85
85
  object.__setattr__(self, key, value)
86
86
  else:
87
87
  raise AttributeError("Data is read-only; modify the source DataFrame before wrapping.")
88
-
88
+
89
89
  class MultiCurrency(dict):
90
90
 
91
91
  symbols: tuple[str, ...] # List of symbols in this container
@@ -0,0 +1,207 @@
1
+ import pandas as pd
2
+ from abc import ABC, abstractmethod
3
+ from overfitting import Strategy
4
+
5
+ class Indicator(ABC):
6
+ def __init__(self, strategy: Strategy, symbol: str):
7
+ self.strategy: Strategy = strategy
8
+ self.symbol: str = symbol
9
+ self._values: pd.Series | pd.DataFrame | None = None
10
+ self.compute()
11
+
12
+ @property
13
+ def values(self) -> pd.Series | pd.DataFrame | None:
14
+ return self._values
15
+
16
+ def get_series(self, name: str) -> pd.Series:
17
+ d = self.strategy.broker._d(self.symbol)
18
+ values = getattr(d, name, None)
19
+ if values is None:
20
+ raise AttributeError(f"Column '{name}' not found for symbol '{self.symbol}'")
21
+
22
+ return pd.Series(values)
23
+
24
+ @abstractmethod
25
+ def compute(self):
26
+ pass
27
+
28
+ def value(self, i: int):
29
+ if self._values is None:
30
+ raise ValueError(f"{self.__class__.__name__} has not computed yet")
31
+ return self._values.iloc[i]
32
+
33
+ def __getitem__(self, i: int):
34
+ return self.value(i)
35
+
36
+
37
+ class SMA(Indicator):
38
+ def __init__(self, strategy: Strategy, symbol: str, source: str = "close", window: int = 20):
39
+ self.source = source
40
+ self.window = window
41
+ super().__init__(strategy, symbol)
42
+
43
+ def compute(self):
44
+ s = self.get_series(self.source)
45
+ self._values = s.rolling(self.window).mean().shift(1)
46
+
47
+
48
+ class EMA(Indicator):
49
+ def __init__(self, strategy: Strategy, symbol: str, source: str = "close", span: int = 20):
50
+ self.source = source
51
+ self.span = span
52
+ super().__init__(strategy, symbol)
53
+
54
+ def compute(self):
55
+ s = self.get_series(self.source)
56
+ self._values = s.ewm(span=self.span, adjust=False).mean().shift(1)
57
+
58
+
59
+ class WMA(Indicator):
60
+ def __init__(self, strategy: Strategy, symbol: str, source: str = "close", window: int = 20):
61
+ self.source = source
62
+ self.window = window
63
+ super().__init__(strategy, symbol)
64
+
65
+ def compute(self):
66
+ s = self.get_series(self.source)
67
+ weights = pd.Series(range(1, self.window + 1), dtype=float)
68
+
69
+ def _wma(x):
70
+ return (x * weights).sum() / weights.sum()
71
+
72
+ self._values = s.rolling(self.window).apply(_wma, raw=False).shift(1)
73
+
74
+
75
+ class RSI(Indicator):
76
+ def __init__(self, strategy: Strategy, symbol: str, source: str = "close", window: int = 14):
77
+ self.source = source
78
+ self.window = window
79
+ super().__init__(strategy, symbol)
80
+
81
+ def compute(self):
82
+ s = self.get_series(self.source)
83
+ delta = s.diff()
84
+
85
+ gain = delta.clip(lower=0)
86
+ loss = -delta.clip(upper=0)
87
+
88
+ avg_gain = gain.ewm(alpha=1 / self.window, adjust=False, min_periods=self.window).mean()
89
+ avg_loss = loss.ewm(alpha=1 / self.window, adjust=False, min_periods=self.window).mean()
90
+
91
+ rs = avg_gain / avg_loss
92
+ self._values = (100 - (100 / (1 + rs))).shift(1)
93
+
94
+
95
+ class MACD(Indicator):
96
+ def __init__(
97
+ self,
98
+ strategy: Strategy,
99
+ symbol: str,
100
+ source: str = "close",
101
+ fast: int = 12,
102
+ slow: int = 26,
103
+ signal: int = 9,
104
+ ):
105
+ self.source = source
106
+ self.fast = fast
107
+ self.slow = slow
108
+ self.signal = signal
109
+ super().__init__(strategy, symbol)
110
+
111
+ def compute(self):
112
+ s = self.get_series(self.source)
113
+ fast_ema = s.ewm(span=self.fast, adjust=False).mean()
114
+ slow_ema = s.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
+ strategy: Strategy,
131
+ symbol: str,
132
+ k_window: int = 14,
133
+ d_window: int = 3,
134
+ smooth_k: int = 3,
135
+ ):
136
+ self.k_window = k_window
137
+ self.d_window = d_window
138
+ self.smooth_k = smooth_k
139
+ super().__init__(strategy, symbol)
140
+
141
+ def compute(self):
142
+ d = self.strategy.broker._d(self.symbol)
143
+ high = d.high
144
+ low = d.low
145
+ close = d.close
146
+
147
+ lowest_low = low.rolling(self.k_window).min()
148
+ highest_high = high.rolling(self.k_window).max()
149
+
150
+ raw_k = 100 * (close - lowest_low) / (highest_high - lowest_low)
151
+ k = raw_k.rolling(self.smooth_k).mean()
152
+ d_line = k.rolling(self.d_window).mean()
153
+
154
+ self._values = pd.DataFrame({
155
+ "%K": k.shift(1),
156
+ "%D": d_line.shift(1),
157
+ })
158
+
159
+
160
+ class BollingerBands(Indicator):
161
+ def __init__(
162
+ self,
163
+ strategy: Strategy,
164
+ symbol: str,
165
+ source: str = "close",
166
+ window: int = 20,
167
+ num_std: float = 2.0,
168
+ ):
169
+ self.source = source
170
+ self.window = window
171
+ self.num_std = num_std
172
+ super().__init__(strategy, symbol)
173
+
174
+ def compute(self):
175
+ s = self.get_series(self.source)
176
+ mid = s.rolling(self.window).mean()
177
+ std = s.rolling(self.window).std()
178
+
179
+ upper = mid + self.num_std * std
180
+ lower = mid - self.num_std * std
181
+
182
+ self._values = pd.DataFrame({
183
+ "middle": mid.shift(1),
184
+ "upper": upper.shift(1),
185
+ "lower": lower.shift(1),
186
+ "bandwidth": ((upper - lower) / mid).shift(1),
187
+ })
188
+
189
+
190
+ class ATR(Indicator):
191
+ def __init__(self, strategy: Strategy, symbol: str, window: int = 14):
192
+ self.window = window
193
+ super().__init__(strategy, symbol)
194
+
195
+ def compute(self):
196
+ d = self.strategy.broker._d(self.symbol)
197
+ prev_close = d.close.shift(1)
198
+
199
+ tr1 = d.high - d.low
200
+ tr2 = (d.high - prev_close).abs()
201
+ tr3 = (d.low - prev_close).abs()
202
+
203
+ tr = pd.concat([tr1, tr2, tr3], axis=1).max(axis=1)
204
+ atr = tr.ewm(alpha=1 / self.window, adjust=False, min_periods=self.window).mean()
205
+
206
+ self._values = atr.shift(1)
207
+
@@ -1,6 +1,6 @@
1
1
  import uuid
2
2
  import pandas as pd
3
- from overfitting.entities.order import OrderType, Status
3
+ from overfitting.types import OrderType, Status
4
4
 
5
5
  class Order:
6
6
  def __init__(self,
@@ -7,8 +7,8 @@ from overfitting.data import Data, MultiCurrency
7
7
  from overfitting.broker import Broker
8
8
  from overfitting.order import Order
9
9
  from overfitting.position import Position
10
- from overfitting.plot.performance import PerformanceReport
11
- from overfitting.execution.slippage import SlippageModel
10
+ from overfitting.analysis.report import Report
11
+ from overfitting.slippage import SlippageModel
12
12
 
13
13
  class Strategy:
14
14
  def __init__(self,
@@ -200,7 +200,7 @@ class Strategy:
200
200
  trades_list = self.broker.trades
201
201
  captial = self.broker.initial_captial
202
202
 
203
- p = PerformanceReport(
203
+ p = Report(
204
204
  returns_series=returns,
205
205
  trades_list=trades_list,
206
206
  initial_capital=captial,
@@ -234,3 +234,5 @@ class Strategy:
234
234
  trade_history_df = self.fetch_trades()
235
235
 
236
236
  trade_history_df.to_csv(full_path, index=False)
237
+
238
+
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: overfitting
3
- Version: 0.3.0
3
+ Version: 0.3.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
@@ -59,41 +59,38 @@ def load_data():
59
59
 
60
60
  start_time = pd.to_datetime('2023-01-01 00:00:00')
61
61
  df = df.loc[start_time:]
62
- # Compute short and long SMAs
63
- df['sma_short'] = df['close'].rolling(window=20).mean().shift(1)
64
- df['sma_long'] = df['close'].rolling(window=50).mean().shift(1)
65
62
 
66
63
  return df, benchamrk_df
67
-
64
+
68
65
  class MyStrategy(Strategy):
69
66
  def init(self):
70
67
  self.asset = 'BTC'
71
68
  self.set_leverage(self.asset, 1)
72
69
 
70
+ self.sma_short = SMA(self, self.asset, source="close", window=20)
71
+ self.sma_long = SMA(self, self.asset, source="close", window=50)
72
+
73
73
  def next(self, i):
74
74
  if i == 0:
75
75
  return
76
76
 
77
- sma_short = self.val(self.asset, i, "sma_short")
78
- sma_long = self.val(self.asset, i, "sma_long")
79
- previous_sma_short = self.val(self.asset, i - 1, "sma_short")
80
- previous_sma_long = self.val(self.asset, i - 1, "sma_long")
77
+ sma_short = self.sma_short[i]
78
+ sma_long = self.sma_long[i]
79
+ previous_sma_short = self.sma_short[i - 1]
80
+ previous_sma_long = self.sma_long[i - 1]
81
81
 
82
- # Also skip if values are not available
83
- if (pd.isna(sma_short) or pd.isna(sma_long) or
84
- pd.isna(previous_sma_short) or pd.isna(previous_sma_long)):
82
+ if (
83
+ pd.isna(sma_short) or pd.isna(sma_long) or
84
+ pd.isna(previous_sma_short) or pd.isna(previous_sma_long)
85
+ ):
85
86
  return
86
87
 
87
- # Fetch the current position
88
88
  position = self.get_position(self.asset)
89
89
 
90
90
  # Golden cross (entry)
91
91
  if previous_sma_short <= previous_sma_long and sma_short > sma_long and position.qty == 0:
92
- # First fetch current open price which is the target Price
93
92
  open_price = self.open(self.asset, i)
94
- # Determine Lot Size
95
93
  lot_size = self.get_balance() // open_price
96
- # Create LIMIT ORDER
97
94
  self.limit_order(self.asset, lot_size, open_price)
98
95
 
99
96
  # Death cross (exit)
@@ -4,21 +4,19 @@ pyproject.toml
4
4
  overfitting/__init__.py
5
5
  overfitting/broker.py
6
6
  overfitting/data.py
7
+ overfitting/errors.py
8
+ overfitting/indicators.py
7
9
  overfitting/order.py
8
10
  overfitting/position.py
11
+ overfitting/slippage.py
9
12
  overfitting/strategy.py
10
- overfitting/viewer.py
13
+ overfitting/types.py
11
14
  overfitting.egg-info/PKG-INFO
12
15
  overfitting.egg-info/SOURCES.txt
13
16
  overfitting.egg-info/dependency_links.txt
14
17
  overfitting.egg-info/requires.txt
15
18
  overfitting.egg-info/top_level.txt
16
- overfitting/entities/__init__.py
17
- overfitting/entities/order.py
18
- overfitting/execution/__init__.py
19
- overfitting/execution/slippage.py
20
- overfitting/plot/__init__.py
21
- overfitting/plot/graph.py
22
- overfitting/plot/performance.py
23
- overfitting/utils/__init__.py
24
- overfitting/utils/error.py
19
+ overfitting/analysis/__init__.py
20
+ overfitting/analysis/graph.py
21
+ overfitting/analysis/report.py
22
+ overfitting/analysis/viewer.py
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "overfitting"
7
- version = "0.3.0"
7
+ version = "0.3.2"
8
8
  description = "A Robust Futures CryptoCurrency Backtesting Library."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.8"
@@ -1,4 +0,0 @@
1
- from .plot.performance import PerformanceReport
2
- from .strategy import Strategy
3
- from .execution.slippage import Slippage
4
- from .viewer import BacktestViewer
File without changes
File without changes
File without changes
File without changes
File without changes