overfitting 0.3.2__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 (24) hide show
  1. {overfitting-0.3.2 → overfitting-0.4.0}/PKG-INFO +2 -1
  2. {overfitting-0.3.2 → overfitting-0.4.0}/README.md +2 -1
  3. {overfitting-0.3.2 → overfitting-0.4.0}/overfitting/analysis/graph.py +8 -0
  4. {overfitting-0.3.2 → overfitting-0.4.0}/overfitting/broker.py +17 -16
  5. {overfitting-0.3.2 → overfitting-0.4.0}/overfitting/errors.py +3 -0
  6. {overfitting-0.3.2 → overfitting-0.4.0}/overfitting/order.py +8 -48
  7. {overfitting-0.3.2 → overfitting-0.4.0}/overfitting/position.py +38 -65
  8. {overfitting-0.3.2 → overfitting-0.4.0}/overfitting/types.py +2 -3
  9. {overfitting-0.3.2 → overfitting-0.4.0}/overfitting.egg-info/PKG-INFO +2 -1
  10. {overfitting-0.3.2 → overfitting-0.4.0}/pyproject.toml +1 -1
  11. {overfitting-0.3.2 → overfitting-0.4.0}/LICENSE +0 -0
  12. {overfitting-0.3.2 → overfitting-0.4.0}/overfitting/__init__.py +0 -0
  13. {overfitting-0.3.2 → overfitting-0.4.0}/overfitting/analysis/__init__.py +0 -0
  14. {overfitting-0.3.2 → overfitting-0.4.0}/overfitting/analysis/report.py +0 -0
  15. {overfitting-0.3.2 → overfitting-0.4.0}/overfitting/analysis/viewer.py +0 -0
  16. {overfitting-0.3.2 → overfitting-0.4.0}/overfitting/data.py +0 -0
  17. {overfitting-0.3.2 → overfitting-0.4.0}/overfitting/indicators.py +0 -0
  18. {overfitting-0.3.2 → overfitting-0.4.0}/overfitting/slippage.py +0 -0
  19. {overfitting-0.3.2 → overfitting-0.4.0}/overfitting/strategy.py +0 -0
  20. {overfitting-0.3.2 → overfitting-0.4.0}/overfitting.egg-info/SOURCES.txt +0 -0
  21. {overfitting-0.3.2 → overfitting-0.4.0}/overfitting.egg-info/dependency_links.txt +0 -0
  22. {overfitting-0.3.2 → overfitting-0.4.0}/overfitting.egg-info/requires.txt +0 -0
  23. {overfitting-0.3.2 → overfitting-0.4.0}/overfitting.egg-info/top_level.txt +0 -0
  24. {overfitting-0.3.2 → 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.2
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')
@@ -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')
@@ -162,4 +163,4 @@ You can simply test multiple currencies by passing data as dict[str, pd.DataFram
162
163
  - **Parameter Optimizer**
163
164
  A simple optimizer to help find the best-performing strategy parameters (like SMA windows, thresholds, etc.) based on backtest results.
164
165
 
165
- > 💡 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.
@@ -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
@@ -5,7 +5,7 @@ from overfitting.order import Order
5
5
  from overfitting.position import Position
6
6
  from overfitting.slippage import SlippageModel
7
7
  from overfitting.types import OrderType
8
- from overfitting.errors import EmptyOrderParameters, InvalidOrderParameters, LiquidationError
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
@@ -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,6 +1,6 @@
1
1
  import uuid
2
2
  import pandas as pd
3
- from overfitting.types import OrderType, Status
3
+ from overfitting.types import OrderType
4
4
 
5
5
  class Order:
6
6
  def __init__(self,
@@ -12,7 +12,7 @@ class Order:
12
12
  stop_price: float = None,
13
13
  label: str= None):
14
14
 
15
- self.id = self.make_id()
15
+ self.id = uuid.uuid4().hex[:16]
16
16
  self.created_at = time
17
17
  self.executed_at = None
18
18
  self.symbol = symbol
@@ -20,10 +20,9 @@ class Order:
20
20
  self.qty = qty
21
21
  self.price = price
22
22
  self.type = type
23
- self._status = Status.OPEN
24
23
  self.stop_price = stop_price
25
24
  self.is_triggered = False
26
- self.reason = None
25
+ self.is_liquidation_order = False
27
26
  self.theoretical_price = 0
28
27
  self.executed_price = 0
29
28
  self.commission = 0
@@ -32,7 +31,7 @@ class Order:
32
31
  self.label = label
33
32
 
34
33
  def __repr__(self):
35
- return (f"Order(id={self.id}, "
34
+ return (f"Order(id={self.id}"
36
35
  f"created_at={self.created_at}, "
37
36
  f"exeucted_at={self.executed_at}, "
38
37
  f"symbol={self.symbol}, "
@@ -40,10 +39,8 @@ class Order:
40
39
  f"qty={self.qty}, "
41
40
  f"price={self.price}, "
42
41
  f"type={self.type}, "
43
- f"status={self._status}, "
44
42
  f"stop_price={self.stop_price}, "
45
43
  f"is_triggered={self.is_triggered}, "
46
- f"reason={self.reason}, "
47
44
  f"theoretical_price={self.theoretical_price}, "
48
45
  f"executed_price={self.executed_price}, "
49
46
  f"commission={self.commission}, "
@@ -52,46 +49,9 @@ class Order:
52
49
  f"label={self.label})")
53
50
 
54
51
  def to_dict(self):
55
- out = {}
56
- for k, v in self.__dict__.items():
57
- if k == "_status":
58
- out["status"] = v.name
59
- elif k == "type":
60
- out["type"] = v.name
61
- else:
62
- out[k] = v
63
- return out
64
-
65
- @staticmethod
66
- def make_id():
67
- 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
+ }
68
56
 
69
- @property
70
- def status(self):
71
- return self._status
72
-
73
- @status.setter
74
- def status(self, status):
75
- self._status = status
76
-
77
- def trigger(self):
78
- self.is_triggered = True
79
-
80
- def cancel(self, reason=None):
81
- self.status = Status.CANCELLED
82
- self.reason = reason
83
-
84
- def reject(self, reason=None):
85
- self.status = Status.REJECTED
86
- self.reason = reason
87
-
88
- def fill(self, commission, pnl, executed_price, time, reason=None):
89
- self.status = Status.FILLED
90
- self.executed_at = time
91
- self.commission = commission
92
- self.pnl = pnl
93
- realized = pnl - commission
94
- self.realized_pnl = realized
95
- self.executed_price = executed_price
96
- self.reason = reason
97
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,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.2
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')
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "overfitting"
7
- version = "0.3.2"
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"
File without changes
File without changes