overfitting 0.3.1__tar.gz → 0.4.0__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 (30) hide show
  1. {overfitting-0.3.1 → overfitting-0.4.0}/PKG-INFO +14 -16
  2. {overfitting-0.3.1 → overfitting-0.4.0}/README.md +14 -16
  3. overfitting-0.4.0/overfitting/__init__.py +3 -0
  4. {overfitting-0.3.1/overfitting/visualization → overfitting-0.4.0/overfitting/analysis}/graph.py +8 -0
  5. {overfitting-0.3.1/overfitting/visualization → overfitting-0.4.0/overfitting/analysis}/report.py +1 -1
  6. {overfitting-0.3.1 → overfitting-0.4.0}/overfitting/broker.py +19 -18
  7. {overfitting-0.3.1/overfitting/data → overfitting-0.4.0/overfitting}/data.py +35 -2
  8. overfitting-0.3.1/overfitting/error.py → overfitting-0.4.0/overfitting/errors.py +3 -0
  9. {overfitting-0.3.1 → overfitting-0.4.0}/overfitting/order.py +8 -49
  10. {overfitting-0.3.1 → overfitting-0.4.0}/overfitting/position.py +38 -65
  11. {overfitting-0.3.1 → overfitting-0.4.0}/overfitting/strategy.py +2 -2
  12. overfitting-0.3.1/overfitting/entities/order.py → overfitting-0.4.0/overfitting/types.py +2 -3
  13. {overfitting-0.3.1 → overfitting-0.4.0}/overfitting.egg-info/PKG-INFO +14 -16
  14. overfitting-0.4.0/overfitting.egg-info/SOURCES.txt +22 -0
  15. {overfitting-0.3.1 → overfitting-0.4.0}/pyproject.toml +1 -1
  16. overfitting-0.3.1/overfitting/__init__.py +0 -3
  17. overfitting-0.3.1/overfitting/data/__init__.py +0 -4
  18. overfitting-0.3.1/overfitting/data/multi_currency.py +0 -38
  19. overfitting-0.3.1/overfitting/execution/__init__.py +0 -0
  20. overfitting-0.3.1/overfitting/visualization/__init__.py +0 -0
  21. overfitting-0.3.1/overfitting.egg-info/SOURCES.txt +0 -26
  22. {overfitting-0.3.1 → overfitting-0.4.0}/LICENSE +0 -0
  23. {overfitting-0.3.1/overfitting/entities → overfitting-0.4.0/overfitting/analysis}/__init__.py +0 -0
  24. {overfitting-0.3.1/overfitting/visualization → overfitting-0.4.0/overfitting/analysis}/viewer.py +0 -0
  25. /overfitting-0.3.1/overfitting/indicator.py → /overfitting-0.4.0/overfitting/indicators.py +0 -0
  26. {overfitting-0.3.1/overfitting/execution → overfitting-0.4.0/overfitting}/slippage.py +0 -0
  27. {overfitting-0.3.1 → overfitting-0.4.0}/overfitting.egg-info/dependency_links.txt +0 -0
  28. {overfitting-0.3.1 → overfitting-0.4.0}/overfitting.egg-info/requires.txt +0 -0
  29. {overfitting-0.3.1 → overfitting-0.4.0}/overfitting.egg-info/top_level.txt +0 -0
  30. {overfitting-0.3.1 → overfitting-0.4.0}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: overfitting
3
- Version: 0.3.1
3
+ Version: 0.4.0
4
4
  Summary: A Robust Futures CryptoCurrency Backtesting Library.
5
5
  Author-email: Dohyun Kim <dohyun.k.july@gmail.com>
6
6
  License: MIT
@@ -50,6 +50,7 @@ Overfitting simulates a realistic crypto futures trading environment including
50
50
  ```python
51
51
  import pandas as pd
52
52
  from overfitting import Strategy, BacktestViewer
53
+ from overfitting.indicators import SMA
53
54
 
54
55
  def load_data():
55
56
  df = pd.read_csv('./data/BTCUSDT.csv')
@@ -59,41 +60,38 @@ def load_data():
59
60
 
60
61
  start_time = pd.to_datetime('2023-01-01 00:00:00')
61
62
  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
63
 
66
64
  return df, benchamrk_df
67
-
65
+
68
66
  class MyStrategy(Strategy):
69
67
  def init(self):
70
68
  self.asset = 'BTC'
71
69
  self.set_leverage(self.asset, 1)
72
70
 
71
+ self.sma_short = SMA(self, self.asset, source="close", window=20)
72
+ self.sma_long = SMA(self, self.asset, source="close", window=50)
73
+
73
74
  def next(self, i):
74
75
  if i == 0:
75
76
  return
76
77
 
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")
78
+ sma_short = self.sma_short[i]
79
+ sma_long = self.sma_long[i]
80
+ previous_sma_short = self.sma_short[i - 1]
81
+ previous_sma_long = self.sma_long[i - 1]
81
82
 
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)):
83
+ if (
84
+ pd.isna(sma_short) or pd.isna(sma_long) or
85
+ pd.isna(previous_sma_short) or pd.isna(previous_sma_long)
86
+ ):
85
87
  return
86
88
 
87
- # Fetch the current position
88
89
  position = self.get_position(self.asset)
89
90
 
90
91
  # Golden cross (entry)
91
92
  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
93
  open_price = self.open(self.asset, i)
94
- # Determine Lot Size
95
94
  lot_size = self.get_balance() // open_price
96
- # Create LIMIT ORDER
97
95
  self.limit_order(self.asset, lot_size, open_price)
98
96
 
99
97
  # Death cross (exit)
@@ -15,6 +15,7 @@ Overfitting simulates a realistic crypto futures trading environment including
15
15
  ```python
16
16
  import pandas as pd
17
17
  from overfitting import Strategy, BacktestViewer
18
+ from overfitting.indicators import SMA
18
19
 
19
20
  def load_data():
20
21
  df = pd.read_csv('./data/BTCUSDT.csv')
@@ -24,41 +25,38 @@ def load_data():
24
25
 
25
26
  start_time = pd.to_datetime('2023-01-01 00:00:00')
26
27
  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
28
 
31
29
  return df, benchamrk_df
32
-
30
+
33
31
  class MyStrategy(Strategy):
34
32
  def init(self):
35
33
  self.asset = 'BTC'
36
34
  self.set_leverage(self.asset, 1)
37
35
 
36
+ self.sma_short = SMA(self, self.asset, source="close", window=20)
37
+ self.sma_long = SMA(self, self.asset, source="close", window=50)
38
+
38
39
  def next(self, i):
39
40
  if i == 0:
40
41
  return
41
42
 
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")
43
+ sma_short = self.sma_short[i]
44
+ sma_long = self.sma_long[i]
45
+ previous_sma_short = self.sma_short[i - 1]
46
+ previous_sma_long = self.sma_long[i - 1]
46
47
 
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)):
48
+ if (
49
+ pd.isna(sma_short) or pd.isna(sma_long) or
50
+ pd.isna(previous_sma_short) or pd.isna(previous_sma_long)
51
+ ):
50
52
  return
51
53
 
52
- # Fetch the current position
53
54
  position = self.get_position(self.asset)
54
55
 
55
56
  # Golden cross (entry)
56
57
  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
58
  open_price = self.open(self.asset, i)
59
- # Determine Lot Size
60
59
  lot_size = self.get_balance() // open_price
61
- # Create LIMIT ORDER
62
60
  self.limit_order(self.asset, lot_size, open_price)
63
61
 
64
62
  # Death cross (exit)
@@ -165,4 +163,4 @@ You can simply test multiple currencies by passing data as dict[str, pd.DataFram
165
163
  - **Parameter Optimizer**
166
164
  A simple optimizer to help find the best-performing strategy parameters (like SMA windows, thresholds, etc.) based on backtest results.
167
165
 
168
- > 💡 Got feedback or suggestions? Feel free to open an issue or contribute via pull request.
166
+ > 💡 Got feedback or suggestions? Feel free to open an issue or contribute via pull request.
@@ -0,0 +1,3 @@
1
+ from .strategy import Strategy
2
+ from .slippage import Slippage
3
+ from .analysis.viewer import BacktestViewer
@@ -1,3 +1,11 @@
1
+ # This file includes code derived from Pyfolio
2
+ # https://github.com/quantopian/pyfolio
3
+ #
4
+ # Original Copyright 2018 Quantopian, Inc.
5
+ # Licensed under Apache License 2.0
6
+ #
7
+ # Modifications made by Dohyun, 2025
8
+
1
9
  import pandas as pd
2
10
  import numpy as np
3
11
  from numpy.lib.stride_tricks import as_strided
@@ -2,7 +2,7 @@ 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.visualization.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
@@ -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.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, StopOrderRejected
9
9
 
10
10
  class Broker:
11
11
  def __init__(self,
@@ -113,16 +113,15 @@ class Broker:
113
113
  open = self._open(symbol, self._i)
114
114
  if ((order.qty > 0 and order.stop_price < open) or
115
115
  (order.qty < 0 and order.stop_price > open)):
116
- # Check if order would be triggered immedately. If True, reject.
117
- order.reject("STOP order would Immedately Trigger")
118
- self.trades.append(order.to_dict())
119
- return order
116
+ raise StopOrderRejected(
117
+ f"STOP order rejected: stop price {order.stop_price} would trigger immediately at current price {open}."
118
+ )
120
119
 
121
120
  # Put new order in the open_orders list if not rejected
122
121
  self.open_orders[symbol][order.id] = order
123
122
  return order
124
123
 
125
- def cancel_order(self, symbol, order_id: str, reason: str = None) -> Optional[Order]:
124
+ def cancel_order(self, symbol, order_id: str) -> Optional[Order]:
126
125
  if symbol not in self.open_orders:
127
126
  return None
128
127
 
@@ -130,19 +129,16 @@ class Broker:
130
129
  return None
131
130
 
132
131
  order = self.open_orders[symbol][order_id]
133
- order.cancel(reason)
134
132
  del self.open_orders[symbol][order_id]
135
133
 
136
134
  return order
137
135
 
138
- def cancel_all_orders(self, symbol: str, reason: str = None):
136
+ def cancel_all_orders(self, symbol: str):
139
137
  if symbol not in self.open_orders:
140
138
  return None
141
139
 
142
140
  orders = self.open_orders[symbol]
143
141
  for order_id in list(orders.keys()):
144
- order = orders[order_id]
145
- order.cancel(reason)
146
142
  del orders[order_id]
147
143
 
148
144
  def get_position(self, symbol: str) -> Position:
@@ -184,14 +180,19 @@ class Broker:
184
180
  if not order.theoretical_price:
185
181
  raise EmptyOrderParameters("Cannot Exeucte Orders without Price. Please check the order")
186
182
 
183
+ position = self.position[symbol]
184
+
187
185
  notional = abs(order.qty) * order.executed_price
188
186
  commission = notional * self.commission_rate
189
- position = self.position[symbol]
190
- pnl = position.update(order, liquidation)
187
+ pnl = position.process_trade(order, liquidation)
188
+ executed_time = pd.to_datetime(self.data.index[self._i])
191
189
 
192
- timestamp = pd.to_datetime(self.data.index[self._i])
193
- reason = 'liquidation' if liquidation else None
194
- order.fill(commission, pnl, order.executed_price, timestamp, reason)
190
+ # Update Order fields as it has been filled
191
+ order.pnl = pnl
192
+ order.executed_at = executed_time
193
+ order.commission = commission
194
+ order.realized_pnl = pnl - commission
195
+ self.is_liquidation_order = True if liquidation else False
195
196
 
196
197
  # Update trades and balance
197
198
  self.trades.append(order.to_dict())
@@ -244,7 +245,7 @@ class Broker:
244
245
  # Check for the STOP order Trigger Condition
245
246
  if ((order.qty > 0 and high >= order.stop_price) or
246
247
  (order.qty < 0 and low <= order.stop_price)):
247
- order.trigger() # Trigger the Order
248
+ order.is_triggered = True # Trigger the Order
248
249
 
249
250
  if order.is_triggered == True:
250
251
  if order.price is None: # STOP MARKET ORDER
@@ -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.error import InitializationError
4
+ from overfitting.errors import InitializationError
5
5
 
6
6
  REQUIRED_OHLC = ("open", "high", "low", "close")
7
7
 
@@ -84,4 +84,37 @@ class Data(dict):
84
84
  if key in {"index", "columns", "n"}:
85
85
  object.__setattr__(self, key, value)
86
86
  else:
87
- raise AttributeError("Data is read-only; modify the source DataFrame before wrapping.")
87
+ raise AttributeError("Data is read-only; modify the source DataFrame before wrapping.")
88
+
89
+ class MultiCurrency(dict):
90
+
91
+ symbols: tuple[str, ...] # List of symbols in this container
92
+ index: np.ndarray # datetime64[ns] index
93
+ n: int # Number of rows per symbol
94
+
95
+ def __init__(self, frames: dict[str, pd.DataFrame]):
96
+ if not isinstance(frames, dict) or not frames:
97
+ raise InitializationError("Data must be non-empty dict Type - dict[str, pd.DataFrame]")
98
+
99
+ payload = {}
100
+ first_ts = None
101
+ for symbol, df in frames.items():
102
+ d = Data(df)
103
+ if first_ts is None:
104
+ first_ts = d.index
105
+ else:
106
+ # Requires identical timestamps for NOW
107
+ # TODO IMNPLEMENT AUTO FILL for uniform timestamps
108
+ if len(d.index) != len(first_ts) or not np.array_equal(d.index, first_ts):
109
+ raise InitializationError(
110
+ f"Len Timestamps for {symbol} are not equal with the other symbols.")
111
+
112
+ payload[symbol] = d
113
+
114
+ super().__init__(payload)
115
+ object.__setattr__(self, "symbols", tuple(payload.keys()))
116
+ object.__setattr__(self, "index", first_ts)
117
+ object.__setattr__(self, "n", len(first_ts))
118
+
119
+ def __len__(self) -> int:
120
+ return self.n
@@ -21,4 +21,7 @@ class InvalidOrderType(CustomError):
21
21
  pass
22
22
 
23
23
  class LiquidationError(CustomError):
24
+ pass
25
+
26
+ class StopOrderRejected(CustomError):
24
27
  pass
@@ -1,7 +1,6 @@
1
1
  import uuid
2
2
  import pandas as pd
3
- from overfitting.entities.order import OrderType, Status
4
- from enum import Enum
3
+ from overfitting.types import OrderType
5
4
 
6
5
  class Order:
7
6
  def __init__(self,
@@ -13,7 +12,7 @@ class Order:
13
12
  stop_price: float = None,
14
13
  label: str= None):
15
14
 
16
- self.id = self.make_id()
15
+ self.id = uuid.uuid4().hex[:16]
17
16
  self.created_at = time
18
17
  self.executed_at = None
19
18
  self.symbol = symbol
@@ -21,10 +20,9 @@ class Order:
21
20
  self.qty = qty
22
21
  self.price = price
23
22
  self.type = type
24
- self._status = Status.OPEN
25
23
  self.stop_price = stop_price
26
24
  self.is_triggered = False
27
- self.reason = None
25
+ self.is_liquidation_order = False
28
26
  self.theoretical_price = 0
29
27
  self.executed_price = 0
30
28
  self.commission = 0
@@ -33,7 +31,7 @@ class Order:
33
31
  self.label = label
34
32
 
35
33
  def __repr__(self):
36
- return (f"Order(id={self.id}, "
34
+ return (f"Order(id={self.id}"
37
35
  f"created_at={self.created_at}, "
38
36
  f"exeucted_at={self.executed_at}, "
39
37
  f"symbol={self.symbol}, "
@@ -41,10 +39,8 @@ class Order:
41
39
  f"qty={self.qty}, "
42
40
  f"price={self.price}, "
43
41
  f"type={self.type}, "
44
- f"status={self._status}, "
45
42
  f"stop_price={self.stop_price}, "
46
43
  f"is_triggered={self.is_triggered}, "
47
- f"reason={self.reason}, "
48
44
  f"theoretical_price={self.theoretical_price}, "
49
45
  f"executed_price={self.executed_price}, "
50
46
  f"commission={self.commission}, "
@@ -53,46 +49,9 @@ class Order:
53
49
  f"label={self.label})")
54
50
 
55
51
  def to_dict(self):
56
- out = {}
57
- for k, v in self.__dict__.items():
58
- if k == "_status":
59
- out["status"] = v.name
60
- elif k == "type":
61
- out["type"] = v.name
62
- else:
63
- out[k] = v
64
- return out
65
-
66
- @staticmethod
67
- def make_id():
68
- return uuid.uuid4().hex[:16]
52
+ return {
53
+ k: (v.name if isinstance(v, OrderType) else v)
54
+ for k, v in self.__dict__.items()
55
+ }
69
56
 
70
- @property
71
- def status(self):
72
- return self._status
73
-
74
- @status.setter
75
- def status(self, status):
76
- self._status = status
77
-
78
- def trigger(self):
79
- self.is_triggered = True
80
-
81
- def cancel(self, reason=None):
82
- self.status = Status.CANCELLED
83
- self.reason = reason
84
-
85
- def reject(self, reason=None):
86
- self.status = Status.REJECTED
87
- self.reason = reason
88
-
89
- def fill(self, commission, pnl, executed_price, time, reason=None):
90
- self.status = Status.FILLED
91
- self.executed_at = time
92
- self.commission = commission
93
- self.pnl = pnl
94
- realized = pnl - commission
95
- self.realized_pnl = realized
96
- self.executed_price = executed_price
97
- self.reason = reason
98
57
 
@@ -27,12 +27,6 @@ class Position:
27
27
  f"maint_margin_rate={self.maint_margin_rate}, "
28
28
  f"maint_amount={self.maint_amount})")
29
29
 
30
- def __getattr__(self, attr):
31
- return object.__getattribute__(self, attr)
32
-
33
- def __setattr__(self, attr, value):
34
- object.__setattr__(self, attr, value)
35
-
36
30
  def _update_liquid_price(self):
37
31
  """
38
32
  NOTE: liquidation price is calculated based on ISOLATED mode.
@@ -62,13 +56,16 @@ class Position:
62
56
  self.liquid_price = self.price + delta_p
63
57
 
64
58
  def _liquidate(self):
65
- """Returns PNL which is position Margin * -1"""
66
- l = self.margin
59
+ """Returns PNL which is position margin * -1"""
60
+ pnl = -self.margin
61
+ self._reset()
62
+ return pnl
63
+
64
+ def _reset(self):
67
65
  self.qty = 0.0
68
66
  self.price = 0.0
69
67
  self.liquid_price = 0.0
70
68
  self.margin = 0.0
71
- return -l
72
69
 
73
70
  def set_leverage(self, leverage):
74
71
  if leverage <= 0 or leverage > 100:
@@ -77,69 +74,45 @@ class Position:
77
74
  self.leverage = leverage
78
75
  self._update_liquid_price()
79
76
 
80
- def _calculate_pnl(self, txn: Order):
81
- """Assumes this is only called during reducing/closing trades"""
82
- closing_qty = txn.qty
83
- trade_size = abs(closing_qty)
84
-
85
- # Closing long position (selling)
86
- if closing_qty < 0:
87
- pnl_per_unit = txn.executed_price - self.price
88
- # Closing short position (buying to cover)
89
- else:
90
- pnl_per_unit = self.price - txn.executed_price
91
-
92
- return pnl_per_unit * trade_size
93
-
94
- def update(self, txn: Order, liquidation = False):
95
- if self.symbol != txn.symbol:
96
- raise ValueError("Cannot update with a different symbol.")
97
-
98
- if txn.qty == 0:
77
+ def _calculate_realized_pnl(self, entry_price: float, exit_price: float, qty: float, side: float):
78
+ """
79
+ side > 0 : position is long
80
+ side < 0 : position is short
81
+ """
82
+ if side > 0:
83
+ return (exit_price - entry_price) * qty
84
+ return (entry_price - exit_price) * qty
85
+
86
+ def process_trade(self, order: Order, liquidation: bool = False) -> float:
87
+ if self.symbol != order.symbol:
88
+ raise ValueError("Cannot process trade with a different symbol.")
89
+ if order.qty == 0:
99
90
  raise ValueError("Transaction quantity cannot be zero.")
100
-
91
+
101
92
  if liquidation:
102
93
  return self._liquidate()
103
94
 
104
- pnl = 0.0
105
- total_qty = self.qty + txn.qty
106
-
107
- # Case 1: Position fully closed
108
- if total_qty == 0:
109
- pnl = self._calculate_pnl(txn)
110
- self.qty = 0
111
- self.price = 0.0
112
- self.margin = 0.0
113
- self.liquid_price = 0.0
114
-
115
- else:
116
- txn_side = copysign(1, txn.qty)
117
- current_side = copysign(1, self.qty) if self.qty != 0 else txn_side
95
+ same_side = self.qty == 0 or (self.qty * order.qty > 0)
118
96
 
119
- # Case 2: Partially closing or flipping position
120
- if txn_side != current_side:
121
- pnl = self._calculate_pnl(txn)
97
+ if same_side:
98
+ total = self.qty + order.qty
99
+ self.price = (self.price * self.qty + order.executed_price * order.qty) / total
100
+ self.qty = total
101
+ self._update_liquid_price()
102
+ return 0.0
122
103
 
123
- # If position flips (e.g., long → short or vice versa)
124
- if abs(txn.qty) > abs(self.qty):
125
- self.price = txn.executed_price # new position starts at txn price
104
+ # Opposite side — reduce, close, or flip
105
+ close_qty = min(abs(self.qty), abs(order.qty))
106
+ side = 1 if self.qty > 0 else -1
107
+ pnl = self._calculate_realized_pnl(self.price, order.executed_price, close_qty, side)
126
108
 
127
- else:
128
- # Case 3: Adding to an existing position
129
- weighted_cost = (self.price * self.qty) + (txn.executed_price * txn.qty)
130
- self.price = weighted_cost / total_qty
109
+ self.qty += order.qty
131
110
 
132
- self.qty = total_qty
111
+ if self.qty == 0:
112
+ self._reset()
113
+ else: # flip or reduce
114
+ if self.qty * order.qty > 0: # flipped
115
+ self.price = order.executed_price
133
116
  self._update_liquid_price()
134
117
 
135
- return pnl
136
-
137
- def to_dict(self):
138
- return{
139
- 'symbol': self.symbol,
140
- 'qty': self.qty,
141
- 'price': self.price,
142
- 'liquid_price': self.liquid_price,
143
- 'margin': self.margin,
144
- 'leverage': self.leverage
145
- }
118
+ return pnl
@@ -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.visualization.report import Report
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,
@@ -7,6 +7,5 @@ class OrderType(Enum):
7
7
 
8
8
  class Status(Enum):
9
9
  OPEN = 0
10
- CANCELLED = 1
11
- FILLED = 2
12
- REJECTED = 3
10
+ FILLED = 1
11
+ REJECTED = 2
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: overfitting
3
- Version: 0.3.1
3
+ Version: 0.4.0
4
4
  Summary: A Robust Futures CryptoCurrency Backtesting Library.
5
5
  Author-email: Dohyun Kim <dohyun.k.july@gmail.com>
6
6
  License: MIT
@@ -50,6 +50,7 @@ Overfitting simulates a realistic crypto futures trading environment including
50
50
  ```python
51
51
  import pandas as pd
52
52
  from overfitting import Strategy, BacktestViewer
53
+ from overfitting.indicators import SMA
53
54
 
54
55
  def load_data():
55
56
  df = pd.read_csv('./data/BTCUSDT.csv')
@@ -59,41 +60,38 @@ def load_data():
59
60
 
60
61
  start_time = pd.to_datetime('2023-01-01 00:00:00')
61
62
  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
63
 
66
64
  return df, benchamrk_df
67
-
65
+
68
66
  class MyStrategy(Strategy):
69
67
  def init(self):
70
68
  self.asset = 'BTC'
71
69
  self.set_leverage(self.asset, 1)
72
70
 
71
+ self.sma_short = SMA(self, self.asset, source="close", window=20)
72
+ self.sma_long = SMA(self, self.asset, source="close", window=50)
73
+
73
74
  def next(self, i):
74
75
  if i == 0:
75
76
  return
76
77
 
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")
78
+ sma_short = self.sma_short[i]
79
+ sma_long = self.sma_long[i]
80
+ previous_sma_short = self.sma_short[i - 1]
81
+ previous_sma_long = self.sma_long[i - 1]
81
82
 
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)):
83
+ if (
84
+ pd.isna(sma_short) or pd.isna(sma_long) or
85
+ pd.isna(previous_sma_short) or pd.isna(previous_sma_long)
86
+ ):
85
87
  return
86
88
 
87
- # Fetch the current position
88
89
  position = self.get_position(self.asset)
89
90
 
90
91
  # Golden cross (entry)
91
92
  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
93
  open_price = self.open(self.asset, i)
94
- # Determine Lot Size
95
94
  lot_size = self.get_balance() // open_price
96
- # Create LIMIT ORDER
97
95
  self.limit_order(self.asset, lot_size, open_price)
98
96
 
99
97
  # Death cross (exit)
@@ -0,0 +1,22 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ overfitting/__init__.py
5
+ overfitting/broker.py
6
+ overfitting/data.py
7
+ overfitting/errors.py
8
+ overfitting/indicators.py
9
+ overfitting/order.py
10
+ overfitting/position.py
11
+ overfitting/slippage.py
12
+ overfitting/strategy.py
13
+ overfitting/types.py
14
+ overfitting.egg-info/PKG-INFO
15
+ overfitting.egg-info/SOURCES.txt
16
+ overfitting.egg-info/dependency_links.txt
17
+ overfitting.egg-info/requires.txt
18
+ overfitting.egg-info/top_level.txt
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.1"
7
+ version = "0.4.0"
8
8
  description = "A Robust Futures CryptoCurrency Backtesting Library."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.8"
@@ -1,3 +0,0 @@
1
- from .strategy import Strategy
2
- from .execution.slippage import Slippage
3
- from .visualization.viewer import BacktestViewer
@@ -1,4 +0,0 @@
1
- from .data import Data
2
- from .multi_currency import MultiCurrency
3
-
4
- __all__ = ["Data", "MultiCurrency"]
@@ -1,38 +0,0 @@
1
- import pandas as pd
2
- import numpy as np
3
- from pandas.api.types import is_datetime64_any_dtype, is_integer_dtype, is_float_dtype
4
- from overfitting.error import InitializationError
5
- from overfitting.data import Data
6
-
7
- class MultiCurrency(dict):
8
-
9
- symbols: tuple[str, ...] # List of symbols in this container
10
- index: np.ndarray # datetime64[ns] index
11
- n: int # Number of rows per symbol
12
-
13
- def __init__(self, frames: dict[str, pd.DataFrame]):
14
- if not isinstance(frames, dict) or not frames:
15
- raise InitializationError("Data must be non-empty dict Type - dict[str, pd.DataFrame]")
16
-
17
- payload = {}
18
- first_ts = None
19
- for symbol, df in frames.items():
20
- d = Data(df)
21
- if first_ts is None:
22
- first_ts = d.index
23
- else:
24
- # Requires identical timestamps for NOW
25
- # TODO IMNPLEMENT AUTO FILL for uniform timestamps
26
- if len(d.index) != len(first_ts) or not np.array_equal(d.index, first_ts):
27
- raise InitializationError(
28
- f"Len Timestamps for {symbol} are not equal with the other symbols.")
29
-
30
- payload[symbol] = d
31
-
32
- super().__init__(payload)
33
- object.__setattr__(self, "symbols", tuple(payload.keys()))
34
- object.__setattr__(self, "index", first_ts)
35
- object.__setattr__(self, "n", len(first_ts))
36
-
37
- def __len__(self) -> int:
38
- return self.n
File without changes
File without changes
@@ -1,26 +0,0 @@
1
- LICENSE
2
- README.md
3
- pyproject.toml
4
- overfitting/__init__.py
5
- overfitting/broker.py
6
- overfitting/error.py
7
- overfitting/indicator.py
8
- overfitting/order.py
9
- overfitting/position.py
10
- overfitting/strategy.py
11
- overfitting.egg-info/PKG-INFO
12
- overfitting.egg-info/SOURCES.txt
13
- overfitting.egg-info/dependency_links.txt
14
- overfitting.egg-info/requires.txt
15
- overfitting.egg-info/top_level.txt
16
- overfitting/data/__init__.py
17
- overfitting/data/data.py
18
- overfitting/data/multi_currency.py
19
- overfitting/entities/__init__.py
20
- overfitting/entities/order.py
21
- overfitting/execution/__init__.py
22
- overfitting/execution/slippage.py
23
- overfitting/visualization/__init__.py
24
- overfitting/visualization/graph.py
25
- overfitting/visualization/report.py
26
- overfitting/visualization/viewer.py
File without changes
File without changes