overfitting 0.4.0__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.
Files changed (27) hide show
  1. {overfitting-0.4.0 → overfitting-0.4.2}/PKG-INFO +7 -13
  2. {overfitting-0.4.0 → overfitting-0.4.2}/README.md +6 -11
  3. {overfitting-0.4.0 → overfitting-0.4.2}/overfitting/__init__.py +0 -1
  4. {overfitting-0.4.0 → overfitting-0.4.2}/overfitting/analysis/report.py +29 -25
  5. {overfitting-0.4.0 → overfitting-0.4.2}/overfitting/broker.py +10 -9
  6. overfitting-0.4.2/overfitting/data.py +89 -0
  7. overfitting-0.4.2/overfitting/indicators.py +210 -0
  8. {overfitting-0.4.0 → overfitting-0.4.2}/overfitting/order.py +16 -10
  9. overfitting-0.4.2/overfitting/position.py +113 -0
  10. {overfitting-0.4.0 → overfitting-0.4.2}/overfitting/strategy.py +63 -17
  11. {overfitting-0.4.0 → overfitting-0.4.2}/overfitting.egg-info/PKG-INFO +7 -13
  12. {overfitting-0.4.0 → overfitting-0.4.2}/overfitting.egg-info/SOURCES.txt +1 -2
  13. {overfitting-0.4.0 → overfitting-0.4.2}/overfitting.egg-info/requires.txt +0 -1
  14. {overfitting-0.4.0 → overfitting-0.4.2}/pyproject.toml +1 -2
  15. overfitting-0.4.0/overfitting/analysis/viewer.py +0 -900
  16. overfitting-0.4.0/overfitting/data.py +0 -120
  17. overfitting-0.4.0/overfitting/indicators.py +0 -207
  18. overfitting-0.4.0/overfitting/position.py +0 -118
  19. {overfitting-0.4.0 → overfitting-0.4.2}/LICENSE +0 -0
  20. {overfitting-0.4.0 → overfitting-0.4.2}/overfitting/analysis/__init__.py +0 -0
  21. {overfitting-0.4.0 → overfitting-0.4.2}/overfitting/analysis/graph.py +0 -0
  22. {overfitting-0.4.0 → overfitting-0.4.2}/overfitting/errors.py +0 -0
  23. {overfitting-0.4.0 → overfitting-0.4.2}/overfitting/slippage.py +0 -0
  24. {overfitting-0.4.0 → overfitting-0.4.2}/overfitting/types.py +0 -0
  25. {overfitting-0.4.0 → overfitting-0.4.2}/overfitting.egg-info/dependency_links.txt +0 -0
  26. {overfitting-0.4.0 → overfitting-0.4.2}/overfitting.egg-info/top_level.txt +0 -0
  27. {overfitting-0.4.0 → 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.0
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
- ![Backtest Viewer](https://raw.githubusercontent.com/dohyunkjuly/overfitting/main/documents/viewer.gif)
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, BacktestViewer
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(self, self.asset, source="close", window=20)
72
- self.sma_long = SMA(self, self.asset, source="close", window=50)
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:
@@ -98,9 +95,9 @@ class MyStrategy(Strategy):
98
95
  if previous_sma_short >= previous_sma_long and sma_short < sma_long and position.qty > 0:
99
96
  self.market_order(self.asset, -position.qty)
100
97
 
101
- backtest_data, benchmark_data = load_data()
98
+ price_df, benchmark_data = load_data()
102
99
  strategy = MyStrategy(
103
- data=backtest_data,
100
+ data={"BTC": price_df},
104
101
  benchmark=benchmark_data, # Default = None Optional
105
102
  initial_capital=100_000, # Default Optional
106
103
  commission_rate=0.0002, # Default Optional
@@ -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
- ![Backtest Viewer](https://raw.githubusercontent.com/dohyunkjuly/overfitting/main/documents/viewer.gif)
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, BacktestViewer
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(self, self.asset, source="close", window=20)
37
- self.sma_long = SMA(self, self.asset, source="close", window=50)
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:
@@ -63,9 +61,9 @@ class MyStrategy(Strategy):
63
61
  if previous_sma_short >= previous_sma_long and sma_short < sma_long and position.qty > 0:
64
62
  self.market_order(self.asset, -position.qty)
65
63
 
66
- backtest_data, benchmark_data = load_data()
64
+ price_df, benchmark_data = load_data()
67
65
  strategy = MyStrategy(
68
- data=backtest_data,
66
+ data={"BTC": price_df},
69
67
  benchmark=benchmark_data, # Default = None Optional
70
68
  initial_capital=100_000, # Default Optional
71
69
  commission_rate=0.0002, # Default Optional
@@ -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
@@ -1,3 +1,2 @@
1
1
  from .strategy import Strategy
2
2
  from .slippage import Slippage
3
- from .analysis.viewer import BacktestViewer
@@ -41,6 +41,7 @@ class Report:
41
41
  self.summary_df, self.drawdown_series, self.drawdown_table = self._compute_summary()
42
42
 
43
43
  def show(self):
44
+ self._print_summary(self.summary_df, self.drawdown_table)
44
45
  self.plot_cumulative() # Plot cumulative returns vs benchmark
45
46
  self.plot_cumulative_log() # Plot cumulative returns on a log scale vs benchmark
46
47
  self.plot_daily_returns() # Plot daily returns over time
@@ -225,24 +226,29 @@ class Report:
225
226
  return gross_returns, return_percents
226
227
 
227
228
  def _compute_summary(self):
228
- peak = self.cum.expanding(min_periods=1).max()
229
- drawdown = (self.cum / peak) - 1
230
- dvt = graph.value_at_risk(self.daily_returns, sigma=2, period=None)
229
+ drawdown = self._compute_drawdown()
230
+ return_stats = self._compute_return_stats(drawdown)
231
+ trade_stats = self._compute_trade_stats()
231
232
 
232
- # monthly stats for skew/kurt
233
- monthly = (1 + self.daily_returns).resample("ME").prod().sub(1)
234
- monthly.index = monthly.index.strftime("%Y-%m")
235
- skew_val = skew(monthly) if len(monthly) > 2 else np.nan
236
- kurt_val = kurtosis(monthly, fisher=False) if len(monthly) > 2 else np.nan
233
+ summary_df = self._format_summary({**return_stats, **trade_stats})
234
+ dd_table = graph.show_worst_drawdown_periods(self.daily_returns)
235
+ return summary_df, drawdown, dd_table
236
+
237
+ def _compute_drawdown(self):
238
+ peak = self.cum.expanding(min_periods=1).max()
239
+ return (self.cum / peak) - 1
237
240
 
241
+ def _compute_return_stats(self, drawdown):
238
242
  years = max(1e-9, (pd.to_datetime(self.end) - pd.to_datetime(self.start)).days / 365)
239
243
  cum_return = float(self.cum.iloc[-1])
240
244
  cagr = (cum_return ** (1 / years)) - 1 if cum_return > 0 else np.nan
241
245
 
242
- sharpe = graph.sharpe_ratio(self.daily_returns, risk_free=0, period="daily")
243
- sortino = graph.sortino_ratio(self.daily_returns, required_return=0, period="daily")
246
+ monthly = (1 + self.daily_returns).resample("ME").prod().sub(1)
247
+ has_monthly = len(monthly) > 2
248
+ skew_val = float(skew(monthly)) if has_monthly else np.nan
249
+ kurt_val = float(kurtosis(monthly, fisher=False)) if has_monthly else np.nan
244
250
 
245
- summary = {
251
+ return {
246
252
  "Number of Years": round(years, 2),
247
253
  "Start Date": self.start,
248
254
  "End Date": self.end,
@@ -250,26 +256,24 @@ class Report:
250
256
  "Final Balance": self.initial_capital * cum_return,
251
257
  "CAGR": cagr,
252
258
  "Cumulative Return": cum_return,
253
- "Sharpe Ratio": sharpe,
254
- "Sortino Ratio": sortino,
259
+ "Sharpe Ratio": graph.sharpe_ratio(self.daily_returns, risk_free=0, period="daily"),
260
+ "Sortino Ratio": graph.sortino_ratio(self.daily_returns, required_return=0, period="daily"),
255
261
  "Max Drawdown": float(drawdown.min()),
256
- "Daily Value At Risk": float(dvt),
257
- "Skew": float(skew_val) if pd.notna(skew_val) else np.nan,
258
- "Kurtosis": float(kurt_val) if pd.notna(kurt_val) else np.nan,
262
+ "Daily Value At Risk": float(graph.value_at_risk(self.daily_returns, sigma=2, period=None)),
263
+ "Skew": skew_val,
264
+ "Kurtosis": kurt_val,
259
265
  }
260
266
 
261
- # trade stats
262
- stats = graph.trade_summary(self.gross_returns, self.return_percents)
263
- summary.update(stats.to_dict())
267
+ def _compute_trade_stats(self):
268
+ return graph.trade_summary(self.gross_returns, self.return_percents).to_dict()
264
269
 
270
+ def _format_summary(self, summary: dict):
265
271
  df = pd.DataFrame.from_dict(summary, orient="index", columns=[""])
266
272
  df[""] = df[""].apply(lambda x: f"{x:,.8f}" if isinstance(x, float) else x)
273
+ return df
267
274
 
275
+ def _print_summary(self, summary_df, dd_table):
268
276
  print("Performance Summary")
269
277
  with pd.option_context("display.colheader_justify", "left", "display.width", None):
270
- print(df.to_string(header=False))
271
-
272
- dd_table = graph.show_worst_drawdown_periods(self.daily_returns)
273
- print(dd_table)
274
-
275
- return df, drawdown, dd_table
278
+ print(summary_df.to_string(header=False))
279
+ print(dd_table)
@@ -1,6 +1,7 @@
1
1
  import pandas as pd
2
- from typing import List, Dict, Optional, Union, Tuple
3
- from overfitting.data import Data, MultiCurrency
2
+ from decimal import Decimal
3
+ from typing import List, Dict, Optional, Tuple
4
+ from overfitting.data import Data
4
5
  from overfitting.order import Order
5
6
  from overfitting.position import Position
6
7
  from overfitting.slippage import SlippageModel
@@ -9,8 +10,8 @@ from overfitting.errors import EmptyOrderParameters, InvalidOrderParameters, Liq
9
10
 
10
11
  class Broker:
11
12
  def __init__(self,
12
- data: Union[Data, MultiCurrency],
13
- cash: float,
13
+ data: Data,
14
+ cash: float,
14
15
  commission_rate: float,
15
16
  maint_margin_rate: float,
16
17
  maint_amount:float,
@@ -45,8 +46,8 @@ class Broker:
45
46
  f"positions={list(self.position.keys())}, "
46
47
  f"trades={len(self.trades)})")
47
48
 
48
- def _d(self, symbol: str) -> Data:
49
- return self.data[symbol] if isinstance(self.data, MultiCurrency) else self.data
49
+ def _d(self, symbol: str):
50
+ return self.data[symbol]
50
51
 
51
52
  def _bars(self, symbol: str, i: int) -> Tuple:
52
53
  d = self._d(symbol)
@@ -82,8 +83,8 @@ class Broker:
82
83
  if not symbol or not isinstance(symbol, str):
83
84
  raise InvalidOrderParameters(f"symbol must be a non-empty string. - {symbol}")
84
85
 
85
- if not qty or not isinstance(qty, (int, float)):
86
- raise InvalidOrderParameters(f"qty must be a non-empty float. - {qty}")
86
+ if not qty or not isinstance(qty, (int, float, Decimal)):
87
+ raise InvalidOrderParameters(f"qty must be a non-empty number. - {qty}")
87
88
 
88
89
  if symbol not in self.position:
89
90
  self.position[symbol] = Position(symbol, self.maint_margin_rate, self.maint_amount)
@@ -182,7 +183,7 @@ class Broker:
182
183
 
183
184
  position = self.position[symbol]
184
185
 
185
- notional = abs(order.qty) * order.executed_price
186
+ notional = float(abs(order.qty)) * order.executed_price
186
187
  commission = notional * self.commission_rate
187
188
  pnl = position.process_trade(order, liquidation)
188
189
  executed_time = pd.to_datetime(self.data.index[self._i])
@@ -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,23 +1,25 @@
1
1
  import uuid
2
+ from decimal import Decimal
2
3
  import pandas as pd
3
4
  from overfitting.types import OrderType
4
5
 
5
6
  class Order:
6
- def __init__(self,
7
- time: pd.Timestamp,
8
- symbol: str,
9
- qty: float,
10
- price:float,
11
- type: OrderType,
7
+ def __init__(self,
8
+ time: pd.Timestamp,
9
+ symbol: str,
10
+ qty: float,
11
+ price:float,
12
+ type: OrderType,
12
13
  stop_price: float = None,
13
14
  label: str= None):
14
-
15
+
15
16
  self.id = uuid.uuid4().hex[:16]
16
17
  self.created_at = time
17
18
  self.executed_at = None
18
19
  self.symbol = symbol
19
- self.side = "LONG" if qty > 0 else "SHORT"
20
- self.qty = qty
20
+ # Decimal qty so Position bookkeeping is exact
21
+ self.qty = Decimal(str(qty))
22
+ self.side = "LONG" if self.qty > 0 else "SHORT"
21
23
  self.price = price
22
24
  self.type = type
23
25
  self.stop_price = stop_price
@@ -50,7 +52,11 @@ class Order:
50
52
 
51
53
  def to_dict(self):
52
54
  return {
53
- k: (v.name if isinstance(v, OrderType) else v)
55
+ k: (
56
+ v.name if isinstance(v, OrderType)
57
+ else float(v) if isinstance(v, Decimal)
58
+ else v
59
+ )
54
60
  for k, v in self.__dict__.items()
55
61
  }
56
62