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.
- {overfitting-0.3.2 → overfitting-0.4.0}/PKG-INFO +2 -1
- {overfitting-0.3.2 → overfitting-0.4.0}/README.md +2 -1
- {overfitting-0.3.2 → overfitting-0.4.0}/overfitting/analysis/graph.py +8 -0
- {overfitting-0.3.2 → overfitting-0.4.0}/overfitting/broker.py +17 -16
- {overfitting-0.3.2 → overfitting-0.4.0}/overfitting/errors.py +3 -0
- {overfitting-0.3.2 → overfitting-0.4.0}/overfitting/order.py +8 -48
- {overfitting-0.3.2 → overfitting-0.4.0}/overfitting/position.py +38 -65
- {overfitting-0.3.2 → overfitting-0.4.0}/overfitting/types.py +2 -3
- {overfitting-0.3.2 → overfitting-0.4.0}/overfitting.egg-info/PKG-INFO +2 -1
- {overfitting-0.3.2 → overfitting-0.4.0}/pyproject.toml +1 -1
- {overfitting-0.3.2 → overfitting-0.4.0}/LICENSE +0 -0
- {overfitting-0.3.2 → overfitting-0.4.0}/overfitting/__init__.py +0 -0
- {overfitting-0.3.2 → overfitting-0.4.0}/overfitting/analysis/__init__.py +0 -0
- {overfitting-0.3.2 → overfitting-0.4.0}/overfitting/analysis/report.py +0 -0
- {overfitting-0.3.2 → overfitting-0.4.0}/overfitting/analysis/viewer.py +0 -0
- {overfitting-0.3.2 → overfitting-0.4.0}/overfitting/data.py +0 -0
- {overfitting-0.3.2 → overfitting-0.4.0}/overfitting/indicators.py +0 -0
- {overfitting-0.3.2 → overfitting-0.4.0}/overfitting/slippage.py +0 -0
- {overfitting-0.3.2 → overfitting-0.4.0}/overfitting/strategy.py +0 -0
- {overfitting-0.3.2 → overfitting-0.4.0}/overfitting.egg-info/SOURCES.txt +0 -0
- {overfitting-0.3.2 → overfitting-0.4.0}/overfitting.egg-info/dependency_links.txt +0 -0
- {overfitting-0.3.2 → overfitting-0.4.0}/overfitting.egg-info/requires.txt +0 -0
- {overfitting-0.3.2 → overfitting-0.4.0}/overfitting.egg-info/top_level.txt +0 -0
- {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
|
+
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
|
-
|
|
117
|
-
|
|
118
|
-
|
|
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
|
|
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
|
|
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
|
-
|
|
190
|
-
|
|
187
|
+
pnl = position.process_trade(order, liquidation)
|
|
188
|
+
executed_time = pd.to_datetime(self.data.index[self._i])
|
|
191
189
|
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
order.
|
|
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.
|
|
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,6 +1,6 @@
|
|
|
1
1
|
import uuid
|
|
2
2
|
import pandas as pd
|
|
3
|
-
from overfitting.types import OrderType
|
|
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 =
|
|
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.
|
|
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
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
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
|
|
66
|
-
|
|
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
|
|
81
|
-
"""
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
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
|
-
|
|
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
|
-
|
|
120
|
-
|
|
121
|
-
|
|
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
|
-
|
|
124
|
-
|
|
125
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: overfitting
|
|
3
|
-
Version: 0.
|
|
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')
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|