overfitting 0.2.2__tar.gz → 0.3.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.
Potentially problematic release.
This version of overfitting might be problematic. Click here for more details.
- {overfitting-0.2.2 → overfitting-0.3.0}/PKG-INFO +10 -3
- {overfitting-0.2.2 → overfitting-0.3.0}/README.md +7 -2
- {overfitting-0.2.2 → overfitting-0.3.0}/overfitting/__init__.py +1 -1
- {overfitting-0.2.2 → overfitting-0.3.0}/overfitting/broker.py +24 -4
- overfitting-0.3.0/overfitting/viewer.py +902 -0
- {overfitting-0.2.2 → overfitting-0.3.0}/overfitting.egg-info/PKG-INFO +10 -3
- {overfitting-0.2.2 → overfitting-0.3.0}/overfitting.egg-info/SOURCES.txt +1 -0
- {overfitting-0.2.2 → overfitting-0.3.0}/overfitting.egg-info/requires.txt +2 -0
- {overfitting-0.2.2 → overfitting-0.3.0}/pyproject.toml +3 -1
- {overfitting-0.2.2 → overfitting-0.3.0}/LICENSE +0 -0
- {overfitting-0.2.2 → overfitting-0.3.0}/overfitting/data.py +0 -0
- {overfitting-0.2.2 → overfitting-0.3.0}/overfitting/entities/__init__.py +0 -0
- {overfitting-0.2.2 → overfitting-0.3.0}/overfitting/entities/order.py +0 -0
- {overfitting-0.2.2 → overfitting-0.3.0}/overfitting/execution/__init__.py +0 -0
- {overfitting-0.2.2 → overfitting-0.3.0}/overfitting/execution/slippage.py +0 -0
- {overfitting-0.2.2 → overfitting-0.3.0}/overfitting/order.py +0 -0
- {overfitting-0.2.2 → overfitting-0.3.0}/overfitting/plot/__init__.py +0 -0
- {overfitting-0.2.2 → overfitting-0.3.0}/overfitting/plot/graph.py +0 -0
- {overfitting-0.2.2 → overfitting-0.3.0}/overfitting/plot/performance.py +0 -0
- {overfitting-0.2.2 → overfitting-0.3.0}/overfitting/position.py +0 -0
- {overfitting-0.2.2 → overfitting-0.3.0}/overfitting/strategy.py +0 -0
- {overfitting-0.2.2 → overfitting-0.3.0}/overfitting/utils/__init__.py +0 -0
- {overfitting-0.2.2 → overfitting-0.3.0}/overfitting/utils/error.py +0 -0
- {overfitting-0.2.2 → overfitting-0.3.0}/overfitting.egg-info/dependency_links.txt +0 -0
- {overfitting-0.2.2 → overfitting-0.3.0}/overfitting.egg-info/top_level.txt +0 -0
- {overfitting-0.2.2 → overfitting-0.3.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.3.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
|
|
@@ -23,6 +23,8 @@ Requires-Dist: pandas>=0.25.0
|
|
|
23
23
|
Requires-Dist: seaborn
|
|
24
24
|
Requires-Dist: matplotlib
|
|
25
25
|
Requires-Dist: scipy
|
|
26
|
+
Requires-Dist: plotly
|
|
27
|
+
Requires-Dist: PySide6
|
|
26
28
|
Provides-Extra: examples
|
|
27
29
|
Requires-Dist: notebook; extra == "examples"
|
|
28
30
|
Requires-Dist: ipykernel; extra == "examples"
|
|
@@ -39,13 +41,15 @@ Overfitting simulates a realistic crypto futures trading environment including
|
|
|
39
41
|
- Four Different Order Types: LIMIT, MARKET, STOP_LIMIT, STOP_MARKET
|
|
40
42
|
- Slippage/Commission Setting
|
|
41
43
|
|
|
44
|
+

|
|
45
|
+
|
|
42
46
|
## Installation
|
|
43
47
|
$ pip install overfitting
|
|
44
48
|
|
|
45
49
|
## Usage
|
|
46
50
|
```python
|
|
47
51
|
import pandas as pd
|
|
48
|
-
from overfitting import Strategy
|
|
52
|
+
from overfitting import Strategy, BacktestViewer
|
|
49
53
|
|
|
50
54
|
def load_data():
|
|
51
55
|
df = pd.read_csv('./data/BTCUSDT.csv')
|
|
@@ -102,11 +106,14 @@ strategy = MyStrategy(
|
|
|
102
106
|
benchmark=benchmark_data, # Default = None Optional
|
|
103
107
|
initial_capital=100_000, # Default Optional
|
|
104
108
|
commission_rate=0.0002, # Default Optional
|
|
105
|
-
|
|
109
|
+
maint_margin_rate=0.005, # Default Optional
|
|
106
110
|
maint_amount=50 # Default Optional
|
|
107
111
|
)
|
|
108
112
|
returns = strategy.run()
|
|
109
113
|
strategy.plot(returns)
|
|
114
|
+
|
|
115
|
+
# Show Backtest Viewer UI
|
|
116
|
+
# BacktestViewer(strategy).show()
|
|
110
117
|
```
|
|
111
118
|
|
|
112
119
|
Results
|
|
@@ -6,13 +6,15 @@ 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
|
+

|
|
10
|
+
|
|
9
11
|
## Installation
|
|
10
12
|
$ pip install overfitting
|
|
11
13
|
|
|
12
14
|
## Usage
|
|
13
15
|
```python
|
|
14
16
|
import pandas as pd
|
|
15
|
-
from overfitting import Strategy
|
|
17
|
+
from overfitting import Strategy, BacktestViewer
|
|
16
18
|
|
|
17
19
|
def load_data():
|
|
18
20
|
df = pd.read_csv('./data/BTCUSDT.csv')
|
|
@@ -69,11 +71,14 @@ strategy = MyStrategy(
|
|
|
69
71
|
benchmark=benchmark_data, # Default = None Optional
|
|
70
72
|
initial_capital=100_000, # Default Optional
|
|
71
73
|
commission_rate=0.0002, # Default Optional
|
|
72
|
-
|
|
74
|
+
maint_margin_rate=0.005, # Default Optional
|
|
73
75
|
maint_amount=50 # Default Optional
|
|
74
76
|
)
|
|
75
77
|
returns = strategy.run()
|
|
76
78
|
strategy.plot(returns)
|
|
79
|
+
|
|
80
|
+
# Show Backtest Viewer UI
|
|
81
|
+
# BacktestViewer(strategy).show()
|
|
77
82
|
```
|
|
78
83
|
|
|
79
84
|
Results
|
|
@@ -225,6 +225,16 @@ class Broker:
|
|
|
225
225
|
elif order.type == OrderType.LIMIT:
|
|
226
226
|
if ((order.qty > 0 and low < order.price) or
|
|
227
227
|
(order.qty < 0 and high > order.price)):
|
|
228
|
+
# If the order just has been created
|
|
229
|
+
if order.created_at == pd.to_datetime(self.data.index[self._i]):
|
|
230
|
+
# For example)
|
|
231
|
+
# If open price is 100 and places an limit buy order 110
|
|
232
|
+
# The order should be executed at 100 not 110
|
|
233
|
+
if ((order.qty > 0 and order.price > open) or
|
|
234
|
+
(order.qty < 0 and order.price < open)):
|
|
235
|
+
self._execute_trade(symbol, order, open)
|
|
236
|
+
continue
|
|
237
|
+
|
|
228
238
|
self._execute_trade(symbol, order)
|
|
229
239
|
else:
|
|
230
240
|
# STOP LIMIT, STOP MARKET Trigger Condition:
|
|
@@ -240,8 +250,18 @@ class Broker:
|
|
|
240
250
|
if order.price is None: # STOP MARKET ORDER
|
|
241
251
|
self._execute_trade(symbol, order, order.stop_price)
|
|
242
252
|
else: # STOP LIMIT ORDER
|
|
243
|
-
if ((order.qty > 0 and
|
|
244
|
-
(order.qty < 0 and
|
|
245
|
-
|
|
246
|
-
|
|
253
|
+
if ((order.qty > 0 and low < order.price) or
|
|
254
|
+
(order.qty < 0 and high > order.price)):
|
|
255
|
+
# If the order just has been created
|
|
256
|
+
if order.created_at == pd.to_datetime(self.data.index[self._i]):
|
|
257
|
+
# For example)
|
|
258
|
+
# If open price is 100 and places an limit buy order 110
|
|
259
|
+
# The order should be executed at 100 not 110
|
|
260
|
+
if ((order.qty > 0 and order.price > open) or
|
|
261
|
+
(order.qty < 0 and order.price < open)):
|
|
262
|
+
self._execute_trade(symbol, order, open)
|
|
263
|
+
continue
|
|
264
|
+
|
|
265
|
+
self._execute_trade(symbol, order)
|
|
266
|
+
|
|
247
267
|
self._i += 1
|
|
@@ -0,0 +1,902 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import os, sys, tempfile
|
|
4
|
+
import pandas as pd
|
|
5
|
+
import numpy as np
|
|
6
|
+
import plotly.graph_objects as go
|
|
7
|
+
|
|
8
|
+
from overfitting import Strategy
|
|
9
|
+
from overfitting.data import MultiCurrency
|
|
10
|
+
|
|
11
|
+
from PySide6.QtWidgets import (
|
|
12
|
+
QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
|
|
13
|
+
QSplitter, QLabel, QComboBox, QTableWidget, QTableWidgetItem,
|
|
14
|
+
QHeaderView, QFrame, QAbstractItemView, QPushButton, QButtonGroup,
|
|
15
|
+
)
|
|
16
|
+
from PySide6.QtWebEngineWidgets import QWebEngineView
|
|
17
|
+
from PySide6.QtCore import Qt, Signal, QUrl
|
|
18
|
+
from PySide6.QtGui import QColor
|
|
19
|
+
|
|
20
|
+
_BG = "#0a0a0a"
|
|
21
|
+
_BG2 = "#0d0d0d"
|
|
22
|
+
_BG3 = "#161616"
|
|
23
|
+
_BORDER = "#222222"
|
|
24
|
+
_AMBER = "#ff9900"
|
|
25
|
+
_AMBER_DIM = "#995c00"
|
|
26
|
+
_AMBER_BG = "#1a1000"
|
|
27
|
+
_WHITE = "#d8d8d8"
|
|
28
|
+
_DIM = "#555555"
|
|
29
|
+
_GREEN = "#00cc66"
|
|
30
|
+
_RED = "#ff3333"
|
|
31
|
+
_CYAN = "#00bcd4"
|
|
32
|
+
_FONT = "Courier New, Courier, monospace"
|
|
33
|
+
|
|
34
|
+
_TIMEFRAMES = ["1m", "5m", "15m", "1h", "4h", "1d"]
|
|
35
|
+
_TF_MINUTES = {"1m": 1, "5m": 5, "15m": 15, "1h": 60, "4h": 240, "1d": 1440}
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class StrategyAdapter:
|
|
39
|
+
"""Extracts symbol metadata from a Strategy instance."""
|
|
40
|
+
|
|
41
|
+
def __init__(self, strategy):
|
|
42
|
+
self._strategy = strategy
|
|
43
|
+
|
|
44
|
+
def get_symbols(self) -> list[str]:
|
|
45
|
+
if isinstance(self._strategy.data, MultiCurrency):
|
|
46
|
+
return list(self._strategy.data.symbols)
|
|
47
|
+
return ["DEFAULT"]
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class OHLCBuilder:
|
|
51
|
+
"""Builds and resamples OHLC DataFrames from strategy data."""
|
|
52
|
+
|
|
53
|
+
@staticmethod
|
|
54
|
+
def detect_base_tf_minutes(price_df: pd.DataFrame) -> int:
|
|
55
|
+
"""Infer the bar interval of the DataFrame in minutes."""
|
|
56
|
+
if len(price_df) < 2:
|
|
57
|
+
return 60
|
|
58
|
+
diffs = price_df["timestamp"].diff().dropna()
|
|
59
|
+
median_sec = diffs.median().total_seconds()
|
|
60
|
+
return max(1, int(round(median_sec / 60)))
|
|
61
|
+
|
|
62
|
+
@staticmethod
|
|
63
|
+
def resample(price_df: pd.DataFrame, target_minutes: int, base_minutes: int) -> pd.DataFrame:
|
|
64
|
+
"""Resample a tidy OHLC DataFrame to a coarser timeframe."""
|
|
65
|
+
if price_df is None or price_df.empty:
|
|
66
|
+
return pd.DataFrame(columns=["timestamp", "open", "high", "low", "close"])
|
|
67
|
+
|
|
68
|
+
if target_minutes <= base_minutes:
|
|
69
|
+
return price_df.copy().reset_index(drop=True)
|
|
70
|
+
|
|
71
|
+
df = price_df.set_index("timestamp")
|
|
72
|
+
rs = df.resample(f"{target_minutes}min", label="left", closed="left").agg(
|
|
73
|
+
open=("open", "first"),
|
|
74
|
+
high=("high", "max"),
|
|
75
|
+
low=("low", "min"),
|
|
76
|
+
close=("close", "last"),
|
|
77
|
+
).dropna(subset=["open"])
|
|
78
|
+
return rs.reset_index()
|
|
79
|
+
|
|
80
|
+
@classmethod
|
|
81
|
+
def from_strategy(cls, strategy, symbol: str) -> pd.DataFrame:
|
|
82
|
+
"""Extract a tidy OHLC DataFrame for *symbol* from a strategy instance."""
|
|
83
|
+
try:
|
|
84
|
+
d = strategy.data[symbol] if isinstance(strategy.data, MultiCurrency) else strategy.data
|
|
85
|
+
except KeyError:
|
|
86
|
+
d = strategy.data
|
|
87
|
+
|
|
88
|
+
return pd.DataFrame({
|
|
89
|
+
"timestamp": pd.to_datetime(d.timestamp),
|
|
90
|
+
"open": d.open,
|
|
91
|
+
"high": d.high,
|
|
92
|
+
"low": d.low,
|
|
93
|
+
"close": d.close,
|
|
94
|
+
}).sort_values("timestamp").reset_index(drop=True)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
class TradeBuilder:
|
|
98
|
+
"""Builds trade and marker DataFrames from a strategy's broker trade log."""
|
|
99
|
+
|
|
100
|
+
COLUMNS = [
|
|
101
|
+
"id", "created_at", "executed_at", "symbol", "side",
|
|
102
|
+
"qty", "price", "theoretical_price", "executed_price", "type",
|
|
103
|
+
"status", "stop_price", "is_triggered", "commission",
|
|
104
|
+
"pnl", "realized_pnl", "label", "reason",
|
|
105
|
+
]
|
|
106
|
+
|
|
107
|
+
@classmethod
|
|
108
|
+
def from_strategy(cls, strategy, symbol: str | None = None) -> pd.DataFrame:
|
|
109
|
+
"""Return the full trade log as a normalised DataFrame."""
|
|
110
|
+
raw = strategy.broker.trades
|
|
111
|
+
if not raw:
|
|
112
|
+
return pd.DataFrame(columns=cls.COLUMNS)
|
|
113
|
+
|
|
114
|
+
df = pd.DataFrame(raw)
|
|
115
|
+
for col in ("created_at", "executed_at"):
|
|
116
|
+
if col in df.columns:
|
|
117
|
+
df[col] = pd.to_datetime(df[col], errors="coerce")
|
|
118
|
+
|
|
119
|
+
if isinstance(strategy.data, MultiCurrency) and symbol and "symbol" in df.columns:
|
|
120
|
+
df = df[df["symbol"] == symbol]
|
|
121
|
+
|
|
122
|
+
for c in cls.COLUMNS:
|
|
123
|
+
if c not in df.columns:
|
|
124
|
+
df[c] = None
|
|
125
|
+
|
|
126
|
+
return (
|
|
127
|
+
df.sort_values(["executed_at", "created_at"], ascending=True, na_position="last")
|
|
128
|
+
.reset_index(drop=True)
|
|
129
|
+
)
|
|
130
|
+
|
|
131
|
+
@staticmethod
|
|
132
|
+
def to_markers(trades_df: pd.DataFrame) -> pd.DataFrame:
|
|
133
|
+
"""Convert a filled-trades DataFrame into chart marker rows."""
|
|
134
|
+
empty = pd.DataFrame(columns=["x", "y", "side", "text"])
|
|
135
|
+
if trades_df.empty:
|
|
136
|
+
return empty
|
|
137
|
+
|
|
138
|
+
filled = trades_df[
|
|
139
|
+
(trades_df["status"] == "FILLED") &
|
|
140
|
+
trades_df["executed_at"].notna() &
|
|
141
|
+
trades_df["executed_price"].notna()
|
|
142
|
+
].copy()
|
|
143
|
+
|
|
144
|
+
if filled.empty:
|
|
145
|
+
return empty
|
|
146
|
+
|
|
147
|
+
def _fmt(row) -> str:
|
|
148
|
+
color = "#00e5ff" if row.get("side") == "LONG" else "#ff00cc"
|
|
149
|
+
pnl = row.get("realized_pnl", "")
|
|
150
|
+
pnl_s = f"{float(pnl):+.4f}" if pnl not in ("", None) else "—"
|
|
151
|
+
ts = pd.to_datetime(row.get("executed_at", ""), errors="coerce")
|
|
152
|
+
ts_s = ts.strftime("%Y-%m-%d %H:%M") if not pd.isna(ts) else "—"
|
|
153
|
+
return (
|
|
154
|
+
f"<span style='color:{color};font-weight:bold'>{row.get('side','')}</span>"
|
|
155
|
+
f" {row.get('type','')} "
|
|
156
|
+
f"<span style='color:#888'>{ts_s}</span><br>"
|
|
157
|
+
f"qty: {row.get('qty','')}<br>"
|
|
158
|
+
f"price: {row.get('executed_price','')}<br>"
|
|
159
|
+
f"pnl: {pnl_s}<br>"
|
|
160
|
+
f"label: {row.get('label','') or '—'}"
|
|
161
|
+
)
|
|
162
|
+
|
|
163
|
+
return pd.DataFrame({
|
|
164
|
+
"x": filled["executed_at"].values,
|
|
165
|
+
"y": filled["executed_price"].values,
|
|
166
|
+
"side": filled["side"].values,
|
|
167
|
+
"executed_at": filled["executed_at"].values,
|
|
168
|
+
"text": filled.apply(_fmt, axis=1).values,
|
|
169
|
+
})
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
class CandleChartWidget(QWidget):
|
|
173
|
+
# Fixed chart window size
|
|
174
|
+
_MAX_CANDLES = 20_000
|
|
175
|
+
_HALF_WINDOW = _MAX_CANDLES // 2
|
|
176
|
+
|
|
177
|
+
def __init__(self, parent=None):
|
|
178
|
+
super().__init__(parent)
|
|
179
|
+
self._price_df = None # base (finest) OHLC
|
|
180
|
+
self._markers_df = None # all filled trade markers
|
|
181
|
+
self._title = ""
|
|
182
|
+
self._tmp_file = None
|
|
183
|
+
self._base_tf_min = 60
|
|
184
|
+
self._current_tf = "1h"
|
|
185
|
+
|
|
186
|
+
self._view = QWebEngineView(self)
|
|
187
|
+
self._view.setStyleSheet(
|
|
188
|
+
f"QWebEngineView {{ background:{_BG}; border:none; margin:0; padding:0; }}"
|
|
189
|
+
)
|
|
190
|
+
self._view.page().setBackgroundColor(QColor(_BG))
|
|
191
|
+
|
|
192
|
+
lay = QVBoxLayout(self)
|
|
193
|
+
lay.setContentsMargins(0, 0, 0, 0)
|
|
194
|
+
lay.setSpacing(0)
|
|
195
|
+
lay.addWidget(self._view)
|
|
196
|
+
|
|
197
|
+
def set_data(self, price_df, markers_df=None, title="", base_tf_min: int | None = None):
|
|
198
|
+
self._price_df = price_df.copy() if price_df is not None else None
|
|
199
|
+
self._markers_df = markers_df.copy() if markers_df is not None else None
|
|
200
|
+
self._title = title
|
|
201
|
+
if self._price_df is not None:
|
|
202
|
+
self._base_tf_min = base_tf_min or OHLCBuilder.detect_base_tf_minutes(self._price_df)
|
|
203
|
+
self._render()
|
|
204
|
+
|
|
205
|
+
def set_timeframe(self, tf: str):
|
|
206
|
+
self._current_tf = tf
|
|
207
|
+
self._render()
|
|
208
|
+
|
|
209
|
+
def zoom_to_trade(self, executed_at):
|
|
210
|
+
if self._price_df is None or self._price_df.empty:
|
|
211
|
+
return
|
|
212
|
+
ts = pd.to_datetime(executed_at, errors="coerce")
|
|
213
|
+
if pd.isna(ts):
|
|
214
|
+
return
|
|
215
|
+
self._render(center_time=ts, selected_time=ts)
|
|
216
|
+
|
|
217
|
+
def _get_display_df(self, center_time=None) -> pd.DataFrame:
|
|
218
|
+
"""
|
|
219
|
+
Return chart OHLC for the current timeframe.
|
|
220
|
+
|
|
221
|
+
- Initial render: first 2000 base rows
|
|
222
|
+
- Trade click: base rows around selected trade timestamp, approx n-1000:n+1000
|
|
223
|
+
"""
|
|
224
|
+
if self._price_df is None or self._price_df.empty:
|
|
225
|
+
return pd.DataFrame(columns=["timestamp", "open", "high", "low", "close"])
|
|
226
|
+
|
|
227
|
+
base_df = self._price_df.reset_index(drop=True)
|
|
228
|
+
|
|
229
|
+
if center_time is None:
|
|
230
|
+
src = base_df.iloc[:self._MAX_CANDLES].copy()
|
|
231
|
+
else:
|
|
232
|
+
ts = pd.to_datetime(center_time, errors="coerce")
|
|
233
|
+
if pd.isna(ts):
|
|
234
|
+
src = base_df.iloc[:self._MAX_CANDLES].copy()
|
|
235
|
+
else:
|
|
236
|
+
idx = (base_df["timestamp"] - ts).abs().idxmin()
|
|
237
|
+
left = max(0, idx - self._HALF_WINDOW)
|
|
238
|
+
right = min(len(base_df), idx + self._HALF_WINDOW)
|
|
239
|
+
src = base_df.iloc[left:right].copy()
|
|
240
|
+
|
|
241
|
+
tf_min = _TF_MINUTES.get(self._current_tf, self._base_tf_min)
|
|
242
|
+
df = OHLCBuilder.resample(src, tf_min, self._base_tf_min).reset_index(drop=True)
|
|
243
|
+
|
|
244
|
+
return df
|
|
245
|
+
|
|
246
|
+
def _y_range_for_window(self, df: pd.DataFrame):
|
|
247
|
+
if df is None or df.empty:
|
|
248
|
+
return None
|
|
249
|
+
lo = float(df["low"].min())
|
|
250
|
+
hi = float(df["high"].max())
|
|
251
|
+
pad = (hi - lo) * 0.07 if hi > lo else max(abs(hi) * 0.01, 1.0)
|
|
252
|
+
return [lo - pad, hi + pad]
|
|
253
|
+
|
|
254
|
+
def _render(self, center_time=None, selected_time=None):
|
|
255
|
+
if self._price_df is None or self._price_df.empty:
|
|
256
|
+
return
|
|
257
|
+
|
|
258
|
+
display_df = self._get_display_df(center_time=center_time)
|
|
259
|
+
if display_df.empty:
|
|
260
|
+
return
|
|
261
|
+
|
|
262
|
+
display_x_start = display_df["timestamp"].min()
|
|
263
|
+
display_x_end = display_df["timestamp"].max()
|
|
264
|
+
|
|
265
|
+
fig = go.Figure()
|
|
266
|
+
|
|
267
|
+
# ── candlesticks ──────────────────────────────────────────────────────
|
|
268
|
+
fig.add_trace(go.Candlestick(
|
|
269
|
+
x=display_df["timestamp"],
|
|
270
|
+
open=display_df["open"], high=display_df["high"],
|
|
271
|
+
low=display_df["low"], close=display_df["close"],
|
|
272
|
+
name="OHLC",
|
|
273
|
+
increasing=dict(line=dict(color=_GREEN, width=1), fillcolor=_GREEN),
|
|
274
|
+
decreasing=dict(line=dict(color=_RED, width=1), fillcolor=_RED),
|
|
275
|
+
hoverlabel=dict(bgcolor=_BG3),
|
|
276
|
+
hovertemplate=(
|
|
277
|
+
"<span style='color:#888'>%{x|%Y-%m-%d %H:%M}</span><br>"
|
|
278
|
+
"O: %{open:.2f} H: %{high:.2f}<br>"
|
|
279
|
+
"L: %{low:.2f} C: %{close:.2f}"
|
|
280
|
+
"<extra></extra>"
|
|
281
|
+
),
|
|
282
|
+
))
|
|
283
|
+
|
|
284
|
+
# ── markers only inside visible candle window ────────────────────────
|
|
285
|
+
mdf = pd.DataFrame()
|
|
286
|
+
if self._markers_df is not None and not self._markers_df.empty:
|
|
287
|
+
mdf = self._markers_df.copy()
|
|
288
|
+
mdf["x"] = pd.to_datetime(mdf["x"], errors="coerce")
|
|
289
|
+
mdf = mdf.dropna(subset=["x"]).sort_values("x").reset_index(drop=True)
|
|
290
|
+
|
|
291
|
+
mdf = mdf[
|
|
292
|
+
(mdf["x"] >= display_x_start) &
|
|
293
|
+
(mdf["x"] <= display_x_end)
|
|
294
|
+
].reset_index(drop=True)
|
|
295
|
+
|
|
296
|
+
for _, row in mdf.iterrows():
|
|
297
|
+
side = row["side"]
|
|
298
|
+
color = "#00e5ff" if side == "LONG" else "#ff00cc"
|
|
299
|
+
sym = "triangle-up" if side == "LONG" else "triangle-down"
|
|
300
|
+
|
|
301
|
+
y_val = pd.to_numeric(pd.Series([row["y"]]), errors="coerce").iloc[0]
|
|
302
|
+
if pd.isna(y_val):
|
|
303
|
+
continue
|
|
304
|
+
|
|
305
|
+
nudge = y_val * (0.0012 if side == "LONG" else -0.0012)
|
|
306
|
+
|
|
307
|
+
fig.add_trace(go.Scatter(
|
|
308
|
+
x=[row["x"]],
|
|
309
|
+
y=[y_val - nudge],
|
|
310
|
+
mode="markers",
|
|
311
|
+
name=side,
|
|
312
|
+
text=[row["text"]],
|
|
313
|
+
hovertemplate="%{text}<extra></extra>",
|
|
314
|
+
marker=dict(
|
|
315
|
+
symbol=sym,
|
|
316
|
+
size=10,
|
|
317
|
+
color=color,
|
|
318
|
+
line=dict(width=1, color="rgba(255,255,255,0.12)"),
|
|
319
|
+
),
|
|
320
|
+
showlegend=False,
|
|
321
|
+
))
|
|
322
|
+
|
|
323
|
+
# ── highlight selected trade if visible ──────────────────────────────
|
|
324
|
+
if selected_time is not None and not mdf.empty:
|
|
325
|
+
ts_series = pd.to_datetime(mdf["x"], errors="coerce")
|
|
326
|
+
if ts_series.notna().any():
|
|
327
|
+
nearest = (ts_series - pd.to_datetime(selected_time)).abs().idxmin()
|
|
328
|
+
row = mdf.loc[[nearest]]
|
|
329
|
+
|
|
330
|
+
highlight_y = pd.to_numeric(row["y"], errors="coerce")
|
|
331
|
+
if not highlight_y.empty and pd.notna(highlight_y.iloc[0]):
|
|
332
|
+
fig.add_trace(go.Scatter(
|
|
333
|
+
x=row["x"],
|
|
334
|
+
y=highlight_y,
|
|
335
|
+
mode="markers",
|
|
336
|
+
hoverinfo="skip",
|
|
337
|
+
marker=dict(
|
|
338
|
+
symbol="circle-open",
|
|
339
|
+
size=22,
|
|
340
|
+
color=_AMBER,
|
|
341
|
+
line=dict(width=2, color=_AMBER),
|
|
342
|
+
),
|
|
343
|
+
showlegend=False,
|
|
344
|
+
name="selected-trade",
|
|
345
|
+
))
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
y_axis_cfg: dict = dict(
|
|
349
|
+
title="",
|
|
350
|
+
gridcolor=_BORDER,
|
|
351
|
+
linecolor=_BORDER,
|
|
352
|
+
tickfont=dict(color=_AMBER_DIM, size=10, family=_FONT),
|
|
353
|
+
tickformat=",.0f",
|
|
354
|
+
side="right",
|
|
355
|
+
zeroline=False,
|
|
356
|
+
fixedrange=False,
|
|
357
|
+
autorange=True,
|
|
358
|
+
)
|
|
359
|
+
|
|
360
|
+
x_axis_cfg: dict = dict(
|
|
361
|
+
title="",
|
|
362
|
+
rangeslider_visible=False,
|
|
363
|
+
gridcolor=_BORDER,
|
|
364
|
+
linecolor=_BORDER,
|
|
365
|
+
tickfont=dict(color=_AMBER_DIM, size=10, family=_FONT),
|
|
366
|
+
zeroline=False,
|
|
367
|
+
fixedrange=False,
|
|
368
|
+
range=[str(display_x_start), str(display_x_end)],
|
|
369
|
+
)
|
|
370
|
+
|
|
371
|
+
y_rng = self._y_range_for_window(display_df)
|
|
372
|
+
if y_rng:
|
|
373
|
+
y_axis_cfg["range"] = y_rng
|
|
374
|
+
y_axis_cfg["autorange"] = False
|
|
375
|
+
|
|
376
|
+
fig.update_layout(
|
|
377
|
+
title=dict(
|
|
378
|
+
text=f"<b>{self._title}</b> "
|
|
379
|
+
f"<span style='color:{_AMBER_DIM};font-size:11px'>{self._current_tf.upper()}</span>",
|
|
380
|
+
font=dict(color=_AMBER, size=13, family=_FONT),
|
|
381
|
+
x=0.005, xanchor="left", y=0.98, yanchor="top",
|
|
382
|
+
),
|
|
383
|
+
paper_bgcolor=_BG,
|
|
384
|
+
plot_bgcolor=_BG2,
|
|
385
|
+
font=dict(color=_AMBER_DIM, family=_FONT, size=11),
|
|
386
|
+
xaxis=x_axis_cfg,
|
|
387
|
+
yaxis=y_axis_cfg,
|
|
388
|
+
legend=dict(
|
|
389
|
+
orientation="h",
|
|
390
|
+
bgcolor="rgba(0,0,0,0)",
|
|
391
|
+
font=dict(color=_DIM, size=10, family=_FONT),
|
|
392
|
+
x=0, y=1.0,
|
|
393
|
+
),
|
|
394
|
+
margin=dict(l=0, r=56, t=32, b=0),
|
|
395
|
+
hovermode="x unified",
|
|
396
|
+
hoverlabel=dict(
|
|
397
|
+
bgcolor=_BG3,
|
|
398
|
+
bordercolor=_AMBER_DIM,
|
|
399
|
+
font=dict(color=_AMBER, family=_FONT, size=11),
|
|
400
|
+
),
|
|
401
|
+
dragmode="pan",
|
|
402
|
+
uirevision="constant",
|
|
403
|
+
)
|
|
404
|
+
|
|
405
|
+
extra_head = (
|
|
406
|
+
"<style>"
|
|
407
|
+
"html,body{margin:0;padding:0;background:" + _BG + ";overflow:hidden}"
|
|
408
|
+
".js-plotly-plot,.plot-container{width:100%!important;height:100vh!important}"
|
|
409
|
+
"body{user-select:none;}"
|
|
410
|
+
"</style>"
|
|
411
|
+
)
|
|
412
|
+
|
|
413
|
+
html = fig.to_html(
|
|
414
|
+
include_plotlyjs=True,
|
|
415
|
+
full_html=True,
|
|
416
|
+
config={
|
|
417
|
+
"scrollZoom": True,
|
|
418
|
+
"displayModeBar": False,
|
|
419
|
+
"doubleClick": "reset",
|
|
420
|
+
},
|
|
421
|
+
)
|
|
422
|
+
|
|
423
|
+
custom_js = r"""
|
|
424
|
+
<script>
|
|
425
|
+
document.addEventListener("DOMContentLoaded", function () {
|
|
426
|
+
const gd = document.querySelector('.js-plotly-plot');
|
|
427
|
+
if (!gd) return;
|
|
428
|
+
|
|
429
|
+
let isDraggingYAxis = false;
|
|
430
|
+
let startY = 0;
|
|
431
|
+
let startRange = null;
|
|
432
|
+
|
|
433
|
+
function getYAxisRange() {
|
|
434
|
+
const layout = gd._fullLayout;
|
|
435
|
+
if (!layout || !layout.yaxis) return null;
|
|
436
|
+
const r = layout.yaxis.range;
|
|
437
|
+
if (!r || r.length !== 2) return null;
|
|
438
|
+
return [Number(r[0]), Number(r[1])];
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
function isNearRightAxis(ev) {
|
|
442
|
+
const rect = gd.getBoundingClientRect();
|
|
443
|
+
const fullLayout = gd._fullLayout;
|
|
444
|
+
if (!fullLayout || !fullLayout.yaxis) return false;
|
|
445
|
+
|
|
446
|
+
// Plotly's plotting area ends before the right margin.
|
|
447
|
+
// We use the right side of the graph div as the y-axis interaction zone.
|
|
448
|
+
const zoneWidth = 60; // pixels near the right edge
|
|
449
|
+
const x = ev.clientX - rect.left;
|
|
450
|
+
|
|
451
|
+
return x >= (rect.width - zoneWidth) && x <= rect.width;
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
function scaleRangeFromDrag(startRange, dy, plotHeight) {
|
|
455
|
+
const y0 = startRange[0];
|
|
456
|
+
const y1 = startRange[1];
|
|
457
|
+
const center = (y0 + y1) / 2;
|
|
458
|
+
const span = Math.abs(y1 - y0);
|
|
459
|
+
|
|
460
|
+
if (!isFinite(span) || span === 0 || !isFinite(plotHeight) || plotHeight <= 0) {
|
|
461
|
+
return startRange;
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
// Drag up => compress range, drag down => expand range
|
|
465
|
+
const sensitivity = 1.25;
|
|
466
|
+
const factor = Math.exp((dy / plotHeight) * sensitivity);
|
|
467
|
+
|
|
468
|
+
const newSpan = span * factor;
|
|
469
|
+
return [center - newSpan / 2, center + newSpan / 2];
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
gd.addEventListener('mousedown', function (ev) {
|
|
473
|
+
if (ev.button !== 0) return;
|
|
474
|
+
if (!isNearRightAxis(ev)) return;
|
|
475
|
+
|
|
476
|
+
const range = getYAxisRange();
|
|
477
|
+
if (!range) return;
|
|
478
|
+
|
|
479
|
+
isDraggingYAxis = true;
|
|
480
|
+
startY = ev.clientY;
|
|
481
|
+
startRange = range;
|
|
482
|
+
|
|
483
|
+
ev.preventDefault();
|
|
484
|
+
ev.stopPropagation();
|
|
485
|
+
}, true);
|
|
486
|
+
|
|
487
|
+
window.addEventListener('mousemove', function (ev) {
|
|
488
|
+
if (!isDraggingYAxis || !startRange) return;
|
|
489
|
+
|
|
490
|
+
const fullLayout = gd._fullLayout;
|
|
491
|
+
const plotHeight = fullLayout && fullLayout._size ? fullLayout._size.h : gd.clientHeight;
|
|
492
|
+
const dy = ev.clientY - startY;
|
|
493
|
+
|
|
494
|
+
const newRange = scaleRangeFromDrag(startRange, dy, plotHeight);
|
|
495
|
+
|
|
496
|
+
Plotly.relayout(gd, {
|
|
497
|
+
'yaxis.autorange': false,
|
|
498
|
+
'yaxis.range': newRange
|
|
499
|
+
});
|
|
500
|
+
|
|
501
|
+
ev.preventDefault();
|
|
502
|
+
}, true);
|
|
503
|
+
|
|
504
|
+
window.addEventListener('mouseup', function () {
|
|
505
|
+
isDraggingYAxis = false;
|
|
506
|
+
startRange = null;
|
|
507
|
+
}, true);
|
|
508
|
+
|
|
509
|
+
// Cursor feedback when hovering near right axis
|
|
510
|
+
gd.addEventListener('mousemove', function (ev) {
|
|
511
|
+
if (isDraggingYAxis) {
|
|
512
|
+
gd.style.cursor = 'ns-resize';
|
|
513
|
+
return;
|
|
514
|
+
}
|
|
515
|
+
gd.style.cursor = isNearRightAxis(ev) ? 'ns-resize' : '';
|
|
516
|
+
});
|
|
517
|
+
|
|
518
|
+
gd.addEventListener('mouseleave', function () {
|
|
519
|
+
if (!isDraggingYAxis) {
|
|
520
|
+
gd.style.cursor = '';
|
|
521
|
+
}
|
|
522
|
+
});
|
|
523
|
+
});
|
|
524
|
+
</script>
|
|
525
|
+
"""
|
|
526
|
+
|
|
527
|
+
html = html.replace("<head>", "<head>" + extra_head, 1)
|
|
528
|
+
html = html.replace("</body>", custom_js + "</body>", 1)
|
|
529
|
+
|
|
530
|
+
if not self._tmp_file:
|
|
531
|
+
fd, path = tempfile.mkstemp(suffix=".html")
|
|
532
|
+
os.close(fd)
|
|
533
|
+
self._tmp_file = path
|
|
534
|
+
|
|
535
|
+
with open(self._tmp_file, "w", encoding="utf-8") as f:
|
|
536
|
+
f.write(html)
|
|
537
|
+
|
|
538
|
+
self._view.load(QUrl.fromLocalFile(self._tmp_file))
|
|
539
|
+
|
|
540
|
+
|
|
541
|
+
class TimeframeBar(QFrame):
|
|
542
|
+
"""Row of TF buttons; disables those finer than the base data interval."""
|
|
543
|
+
|
|
544
|
+
tf_changed = Signal(str)
|
|
545
|
+
|
|
546
|
+
_BTN_STYLE = """
|
|
547
|
+
QPushButton {{
|
|
548
|
+
background: {bg};
|
|
549
|
+
color: {fg};
|
|
550
|
+
border: 1px solid {border};
|
|
551
|
+
border-radius: 2px;
|
|
552
|
+
padding: 2px 10px;
|
|
553
|
+
font-family: {font};
|
|
554
|
+
font-size: 11px;
|
|
555
|
+
font-weight: bold;
|
|
556
|
+
min-width: 32px;
|
|
557
|
+
}}
|
|
558
|
+
QPushButton:hover {{ background: {hover}; color: {amber}; border-color: {amber}; }}
|
|
559
|
+
QPushButton:checked {{ background: {amber_bg}; color: {amber}; border-color: {amber}; }}
|
|
560
|
+
QPushButton:disabled {{ color: {dim}; border-color: {border}; }}
|
|
561
|
+
""".format(
|
|
562
|
+
bg=_BG3, fg=_DIM, border=_BORDER,
|
|
563
|
+
hover=_BG3, amber=_AMBER, amber_bg=_AMBER_BG,
|
|
564
|
+
dim=_DIM, font=_FONT,
|
|
565
|
+
)
|
|
566
|
+
|
|
567
|
+
def __init__(self, parent=None):
|
|
568
|
+
super().__init__(parent)
|
|
569
|
+
self.setFixedHeight(28)
|
|
570
|
+
self.setStyleSheet(f"QFrame {{ background:{_BG}; border:none; }}")
|
|
571
|
+
|
|
572
|
+
lay = QHBoxLayout(self)
|
|
573
|
+
lay.setContentsMargins(8, 0, 8, 0)
|
|
574
|
+
lay.setSpacing(4)
|
|
575
|
+
|
|
576
|
+
tf_lbl = QLabel("TF:")
|
|
577
|
+
tf_lbl.setStyleSheet(
|
|
578
|
+
f"color:{_DIM}; font-family:{_FONT}; font-size:10px; background:transparent;"
|
|
579
|
+
)
|
|
580
|
+
lay.addWidget(tf_lbl)
|
|
581
|
+
|
|
582
|
+
self._group = QButtonGroup(self)
|
|
583
|
+
self._group.setExclusive(True)
|
|
584
|
+
self._buttons: dict[str, QPushButton] = {}
|
|
585
|
+
|
|
586
|
+
for tf in _TIMEFRAMES:
|
|
587
|
+
btn = QPushButton(tf.upper())
|
|
588
|
+
btn.setCheckable(True)
|
|
589
|
+
btn.setStyleSheet(self._BTN_STYLE)
|
|
590
|
+
btn.setFocusPolicy(Qt.NoFocus)
|
|
591
|
+
lay.addWidget(btn)
|
|
592
|
+
self._group.addButton(btn)
|
|
593
|
+
self._buttons[tf] = btn
|
|
594
|
+
|
|
595
|
+
lay.addStretch()
|
|
596
|
+
self._group.buttonClicked.connect(self._on_click)
|
|
597
|
+
|
|
598
|
+
def set_base_tf(self, base_minutes: int, active_tf: str):
|
|
599
|
+
"""Enable only TFs that are >= the base data interval."""
|
|
600
|
+
for tf, btn in self._buttons.items():
|
|
601
|
+
tf_min = _TF_MINUTES[tf]
|
|
602
|
+
enabled = tf_min >= base_minutes
|
|
603
|
+
btn.setEnabled(enabled)
|
|
604
|
+
if tf == active_tf and enabled:
|
|
605
|
+
btn.setChecked(True)
|
|
606
|
+
elif not enabled:
|
|
607
|
+
btn.setChecked(False)
|
|
608
|
+
|
|
609
|
+
def _on_click(self, btn: QPushButton):
|
|
610
|
+
for tf, b in self._buttons.items():
|
|
611
|
+
if b is btn:
|
|
612
|
+
self.tf_changed.emit(tf)
|
|
613
|
+
return
|
|
614
|
+
|
|
615
|
+
|
|
616
|
+
class TradeTableWidget(QWidget):
|
|
617
|
+
trade_selected = Signal(dict)
|
|
618
|
+
|
|
619
|
+
COLUMNS = [
|
|
620
|
+
("executed_at", "EXECUTED AT"),
|
|
621
|
+
("created_at", "CREATED AT"),
|
|
622
|
+
("symbol", "SYMBOL"),
|
|
623
|
+
("side", "SIDE"),
|
|
624
|
+
("qty", "QTY"),
|
|
625
|
+
("price", "ORDER PRICE"),
|
|
626
|
+
("theoretical_price", "THEOR. PRICE"),
|
|
627
|
+
("executed_price", "EXEC PRICE"),
|
|
628
|
+
("type", "TYPE"),
|
|
629
|
+
("status", "STATUS"),
|
|
630
|
+
("stop_price", "STOP PRICE"),
|
|
631
|
+
("is_triggered", "TRIGGERED"),
|
|
632
|
+
("commission", "COMMISSION"),
|
|
633
|
+
("pnl", "PNL"),
|
|
634
|
+
("realized_pnl", "REAL. PNL"),
|
|
635
|
+
("label", "LABEL"),
|
|
636
|
+
("reason", "REASON"),
|
|
637
|
+
("id", "ORDER ID"),
|
|
638
|
+
]
|
|
639
|
+
|
|
640
|
+
def __init__(self, parent=None):
|
|
641
|
+
super().__init__(parent)
|
|
642
|
+
self._df = pd.DataFrame()
|
|
643
|
+
self._keys = [k for k, _ in self.COLUMNS]
|
|
644
|
+
|
|
645
|
+
self._table = QTableWidget(0, len(self._keys), self)
|
|
646
|
+
self._table.setHorizontalHeaderLabels([l for _, l in self.COLUMNS])
|
|
647
|
+
self._table.setSelectionBehavior(QAbstractItemView.SelectRows)
|
|
648
|
+
self._table.setSelectionMode(QAbstractItemView.SingleSelection)
|
|
649
|
+
self._table.setEditTriggers(QAbstractItemView.NoEditTriggers)
|
|
650
|
+
self._table.setSortingEnabled(False)
|
|
651
|
+
self._table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)
|
|
652
|
+
self._table.horizontalHeader().setStretchLastSection(False)
|
|
653
|
+
self._table.verticalHeader().setVisible(False)
|
|
654
|
+
self._table.setAlternatingRowColors(True)
|
|
655
|
+
self._table.cellClicked.connect(self._on_click)
|
|
656
|
+
self._apply_style()
|
|
657
|
+
|
|
658
|
+
lay = QVBoxLayout(self)
|
|
659
|
+
lay.setContentsMargins(0, 0, 0, 0)
|
|
660
|
+
lay.addWidget(self._table)
|
|
661
|
+
|
|
662
|
+
def set_data(self, df: pd.DataFrame):
|
|
663
|
+
self._df = df.reset_index(drop=True) if df is not None and not df.empty else pd.DataFrame()
|
|
664
|
+
self._table.setSortingEnabled(False)
|
|
665
|
+
self._table.setRowCount(0)
|
|
666
|
+
|
|
667
|
+
if self._df.empty:
|
|
668
|
+
return
|
|
669
|
+
|
|
670
|
+
self._table.setRowCount(len(self._df))
|
|
671
|
+
for r, (_, row) in enumerate(self._df.iterrows()):
|
|
672
|
+
for c, key in enumerate(self._keys):
|
|
673
|
+
raw = row.get(key, "")
|
|
674
|
+
if raw is None or (isinstance(raw, float) and np.isnan(raw)):
|
|
675
|
+
val = ""
|
|
676
|
+
elif isinstance(raw, float):
|
|
677
|
+
val = f"{raw:.6f}".rstrip("0").rstrip(".")
|
|
678
|
+
else:
|
|
679
|
+
val = str(raw)
|
|
680
|
+
|
|
681
|
+
item = QTableWidgetItem(val)
|
|
682
|
+
item.setFlags(item.flags() & ~Qt.ItemIsEditable)
|
|
683
|
+
item.setData(Qt.UserRole, r)
|
|
684
|
+
|
|
685
|
+
if key in ("realized_pnl", "pnl") and val:
|
|
686
|
+
try:
|
|
687
|
+
item.setForeground(QColor(_GREEN if float(val) >= 0 else _RED))
|
|
688
|
+
except ValueError:
|
|
689
|
+
pass
|
|
690
|
+
elif key == "side":
|
|
691
|
+
item.setForeground(QColor("#00e5ff" if val == "LONG" else "#ff00cc"))
|
|
692
|
+
elif key == "status":
|
|
693
|
+
item.setForeground(QColor({
|
|
694
|
+
"FILLED": _GREEN,
|
|
695
|
+
"CANCELLED": _DIM,
|
|
696
|
+
"REJECTED": _RED
|
|
697
|
+
}.get(val, _WHITE)))
|
|
698
|
+
elif key == "type":
|
|
699
|
+
item.setForeground(QColor(_CYAN))
|
|
700
|
+
elif key == "id":
|
|
701
|
+
item.setForeground(QColor(_DIM))
|
|
702
|
+
|
|
703
|
+
self._table.setItem(r, c, item)
|
|
704
|
+
|
|
705
|
+
self._table.setSortingEnabled(True)
|
|
706
|
+
self._table.sortByColumn(0, Qt.AscendingOrder)
|
|
707
|
+
|
|
708
|
+
def _on_click(self, row: int, _col: int):
|
|
709
|
+
if self._df.empty:
|
|
710
|
+
return
|
|
711
|
+
|
|
712
|
+
item = self._table.item(row, 0)
|
|
713
|
+
if item is None:
|
|
714
|
+
return
|
|
715
|
+
|
|
716
|
+
original_idx = item.data(Qt.UserRole)
|
|
717
|
+
self.trade_selected.emit(self._df.iloc[original_idx].to_dict())
|
|
718
|
+
|
|
719
|
+
def _apply_style(self):
|
|
720
|
+
self._table.setStyleSheet(f"""
|
|
721
|
+
QTableWidget {{
|
|
722
|
+
background-color: {_BG2};
|
|
723
|
+
alternate-background-color: {_BG3};
|
|
724
|
+
color: {_WHITE};
|
|
725
|
+
gridline-color: {_BORDER};
|
|
726
|
+
border: none;
|
|
727
|
+
font-family: {_FONT};
|
|
728
|
+
font-size: 11px;
|
|
729
|
+
}}
|
|
730
|
+
QHeaderView::section {{
|
|
731
|
+
background-color: {_BG};
|
|
732
|
+
color: {_AMBER};
|
|
733
|
+
border: none;
|
|
734
|
+
border-right: 1px solid {_BORDER};
|
|
735
|
+
border-bottom: 2px solid {_AMBER_DIM};
|
|
736
|
+
padding: 3px 6px;
|
|
737
|
+
font-family: {_FONT};
|
|
738
|
+
font-size: 10px;
|
|
739
|
+
font-weight: bold;
|
|
740
|
+
}}
|
|
741
|
+
QTableWidget::item {{ padding: 2px 6px; }}
|
|
742
|
+
QTableWidget::item:selected {{ background-color:{_AMBER_BG}; color:{_AMBER}; }}
|
|
743
|
+
QScrollBar:horizontal, QScrollBar:vertical {{
|
|
744
|
+
background:{_BG}; height:5px; width:5px;
|
|
745
|
+
}}
|
|
746
|
+
QScrollBar::handle:horizontal, QScrollBar::handle:vertical {{
|
|
747
|
+
background:{_AMBER_DIM}; border-radius:2px;
|
|
748
|
+
}}
|
|
749
|
+
QScrollBar::add-line, QScrollBar::sub-line {{ background:none; border:none; }}
|
|
750
|
+
""")
|
|
751
|
+
|
|
752
|
+
|
|
753
|
+
class HeaderBar(QFrame):
|
|
754
|
+
def __init__(self, symbols: list[str], parent=None):
|
|
755
|
+
super().__init__(parent)
|
|
756
|
+
self.setFixedHeight(36)
|
|
757
|
+
self.setStyleSheet(
|
|
758
|
+
f"QFrame {{ background:{_BG}; border-bottom:2px solid {_AMBER}; }}"
|
|
759
|
+
)
|
|
760
|
+
|
|
761
|
+
lay = QHBoxLayout(self)
|
|
762
|
+
lay.setContentsMargins(12, 0, 12, 0)
|
|
763
|
+
|
|
764
|
+
title = QLabel("OVERFITTING // BACKTEST VIEWER")
|
|
765
|
+
title.setStyleSheet(
|
|
766
|
+
f"color:{_AMBER}; font-family:{_FONT}; font-size:12px; "
|
|
767
|
+
f"font-weight:bold; background:transparent;"
|
|
768
|
+
)
|
|
769
|
+
lay.addWidget(title)
|
|
770
|
+
lay.addStretch()
|
|
771
|
+
|
|
772
|
+
sym_lbl = QLabel("SYMBOL:")
|
|
773
|
+
sym_lbl.setStyleSheet(
|
|
774
|
+
f"color:{_DIM}; font-family:{_FONT}; font-size:10px; background:transparent;"
|
|
775
|
+
)
|
|
776
|
+
lay.addWidget(sym_lbl)
|
|
777
|
+
|
|
778
|
+
self.combo = QComboBox()
|
|
779
|
+
self.combo.addItems(symbols)
|
|
780
|
+
self.combo.setFixedWidth(150)
|
|
781
|
+
self.combo.setStyleSheet(f"""
|
|
782
|
+
QComboBox {{
|
|
783
|
+
background:{_BG3}; color:{_AMBER};
|
|
784
|
+
border:1px solid {_AMBER_DIM}; border-radius:2px;
|
|
785
|
+
padding:2px 24px 2px 8px;
|
|
786
|
+
font-family:{_FONT}; font-size:11px;
|
|
787
|
+
}}
|
|
788
|
+
QComboBox::drop-down {{ border:none; width:20px; }}
|
|
789
|
+
QComboBox QAbstractItemView {{
|
|
790
|
+
background:{_BG3}; color:{_AMBER};
|
|
791
|
+
selection-background-color:{_BG};
|
|
792
|
+
border:1px solid {_AMBER_DIM};
|
|
793
|
+
font-family:{_FONT};
|
|
794
|
+
}}
|
|
795
|
+
""")
|
|
796
|
+
lay.addWidget(self.combo)
|
|
797
|
+
|
|
798
|
+
|
|
799
|
+
class BacktestViewerWindow(QMainWindow):
|
|
800
|
+
def __init__(self, strategy):
|
|
801
|
+
super().__init__()
|
|
802
|
+
self.strategy = strategy
|
|
803
|
+
self.symbols = StrategyAdapter(strategy).get_symbols()
|
|
804
|
+
self.current_symbol = self.symbols[0]
|
|
805
|
+
|
|
806
|
+
self.setWindowTitle("OVERFITTING — BACKTEST VIEWER")
|
|
807
|
+
self.resize(1600, 960)
|
|
808
|
+
self.setStyleSheet(
|
|
809
|
+
f"QMainWindow, QWidget {{ background:{_BG}; color:{_WHITE}; }}"
|
|
810
|
+
)
|
|
811
|
+
|
|
812
|
+
self.header = HeaderBar(self.symbols, self)
|
|
813
|
+
self.tf_bar = TimeframeBar(self)
|
|
814
|
+
self.chart = CandleChartWidget(self)
|
|
815
|
+
self.trade_table = TradeTableWidget(self)
|
|
816
|
+
|
|
817
|
+
self.header.combo.setCurrentText(self.current_symbol)
|
|
818
|
+
self.header.combo.currentTextChanged.connect(self._on_symbol_changed)
|
|
819
|
+
self.trade_table.trade_selected.connect(self._on_trade_selected)
|
|
820
|
+
self.tf_bar.tf_changed.connect(self._on_tf_changed)
|
|
821
|
+
|
|
822
|
+
self._build_ui()
|
|
823
|
+
self._refresh()
|
|
824
|
+
|
|
825
|
+
def _build_ui(self):
|
|
826
|
+
central = QWidget(self)
|
|
827
|
+
self.setCentralWidget(central)
|
|
828
|
+
|
|
829
|
+
root = QVBoxLayout(central)
|
|
830
|
+
root.setContentsMargins(0, 0, 0, 0)
|
|
831
|
+
root.setSpacing(0)
|
|
832
|
+
|
|
833
|
+
root.addWidget(self.header)
|
|
834
|
+
root.addWidget(self.tf_bar)
|
|
835
|
+
|
|
836
|
+
splitter = QSplitter(Qt.Vertical)
|
|
837
|
+
splitter.addWidget(self.chart)
|
|
838
|
+
splitter.addWidget(self.trade_table)
|
|
839
|
+
splitter.setStretchFactor(0, 3)
|
|
840
|
+
splitter.setStretchFactor(1, 1)
|
|
841
|
+
splitter.setHandleWidth(3)
|
|
842
|
+
splitter.setStyleSheet(
|
|
843
|
+
f"QSplitter::handle:vertical {{ background:{_AMBER_DIM}; }}"
|
|
844
|
+
)
|
|
845
|
+
root.addWidget(splitter, 1)
|
|
846
|
+
|
|
847
|
+
def _on_symbol_changed(self, symbol: str):
|
|
848
|
+
self.current_symbol = symbol
|
|
849
|
+
self._refresh()
|
|
850
|
+
|
|
851
|
+
def _on_trade_selected(self, trade: dict):
|
|
852
|
+
at = trade.get("executed_at")
|
|
853
|
+
if at and str(at) not in ("", "None", "NaT"):
|
|
854
|
+
self.chart.zoom_to_trade(at)
|
|
855
|
+
|
|
856
|
+
def _on_tf_changed(self, tf: str):
|
|
857
|
+
self.chart.set_timeframe(tf)
|
|
858
|
+
|
|
859
|
+
def _refresh(self):
|
|
860
|
+
price_df = OHLCBuilder.from_strategy(self.strategy, self.current_symbol)
|
|
861
|
+
trades_df = TradeBuilder.from_strategy(self.strategy, self.current_symbol)
|
|
862
|
+
markers = TradeBuilder.to_markers(trades_df)
|
|
863
|
+
|
|
864
|
+
base_tf_min = OHLCBuilder.detect_base_tf_minutes(price_df) if not price_df.empty else 60
|
|
865
|
+
|
|
866
|
+
default_tf = "1h"
|
|
867
|
+
for tf in _TIMEFRAMES:
|
|
868
|
+
if _TF_MINUTES[tf] >= base_tf_min:
|
|
869
|
+
default_tf = tf
|
|
870
|
+
break
|
|
871
|
+
|
|
872
|
+
self.chart._current_tf = default_tf
|
|
873
|
+
self.tf_bar.set_base_tf(base_tf_min, default_tf)
|
|
874
|
+
self.chart.set_data(price_df, markers, title=self.current_symbol, base_tf_min=base_tf_min)
|
|
875
|
+
|
|
876
|
+
# Trade table stays full
|
|
877
|
+
self.trade_table.set_data(trades_df)
|
|
878
|
+
|
|
879
|
+
|
|
880
|
+
class BacktestViewer:
|
|
881
|
+
"""
|
|
882
|
+
BacktestViewer(strategy).show()
|
|
883
|
+
"""
|
|
884
|
+
def __init__(self, strategy):
|
|
885
|
+
if not hasattr(strategy, "broker"):
|
|
886
|
+
raise ValueError("strategy must have a .broker attribute")
|
|
887
|
+
if not hasattr(strategy, "data"):
|
|
888
|
+
raise ValueError("strategy must have a .data attribute")
|
|
889
|
+
self._strategy = strategy
|
|
890
|
+
self._window = None
|
|
891
|
+
|
|
892
|
+
def show(self):
|
|
893
|
+
app = QApplication.instance()
|
|
894
|
+
owns_app = app is None
|
|
895
|
+
if owns_app:
|
|
896
|
+
app = QApplication(sys.argv)
|
|
897
|
+
|
|
898
|
+
self._window = BacktestViewerWindow(self._strategy)
|
|
899
|
+
self._window.show()
|
|
900
|
+
|
|
901
|
+
if owns_app:
|
|
902
|
+
sys.exit(app.exec())
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: overfitting
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.3.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
|
|
@@ -23,6 +23,8 @@ Requires-Dist: pandas>=0.25.0
|
|
|
23
23
|
Requires-Dist: seaborn
|
|
24
24
|
Requires-Dist: matplotlib
|
|
25
25
|
Requires-Dist: scipy
|
|
26
|
+
Requires-Dist: plotly
|
|
27
|
+
Requires-Dist: PySide6
|
|
26
28
|
Provides-Extra: examples
|
|
27
29
|
Requires-Dist: notebook; extra == "examples"
|
|
28
30
|
Requires-Dist: ipykernel; extra == "examples"
|
|
@@ -39,13 +41,15 @@ Overfitting simulates a realistic crypto futures trading environment including
|
|
|
39
41
|
- Four Different Order Types: LIMIT, MARKET, STOP_LIMIT, STOP_MARKET
|
|
40
42
|
- Slippage/Commission Setting
|
|
41
43
|
|
|
44
|
+

|
|
45
|
+
|
|
42
46
|
## Installation
|
|
43
47
|
$ pip install overfitting
|
|
44
48
|
|
|
45
49
|
## Usage
|
|
46
50
|
```python
|
|
47
51
|
import pandas as pd
|
|
48
|
-
from overfitting import Strategy
|
|
52
|
+
from overfitting import Strategy, BacktestViewer
|
|
49
53
|
|
|
50
54
|
def load_data():
|
|
51
55
|
df = pd.read_csv('./data/BTCUSDT.csv')
|
|
@@ -102,11 +106,14 @@ strategy = MyStrategy(
|
|
|
102
106
|
benchmark=benchmark_data, # Default = None Optional
|
|
103
107
|
initial_capital=100_000, # Default Optional
|
|
104
108
|
commission_rate=0.0002, # Default Optional
|
|
105
|
-
|
|
109
|
+
maint_margin_rate=0.005, # Default Optional
|
|
106
110
|
maint_amount=50 # Default Optional
|
|
107
111
|
)
|
|
108
112
|
returns = strategy.run()
|
|
109
113
|
strategy.plot(returns)
|
|
114
|
+
|
|
115
|
+
# Show Backtest Viewer UI
|
|
116
|
+
# BacktestViewer(strategy).show()
|
|
110
117
|
```
|
|
111
118
|
|
|
112
119
|
Results
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "overfitting"
|
|
7
|
-
version = "0.
|
|
7
|
+
version = "0.3.0"
|
|
8
8
|
description = "A Robust Futures CryptoCurrency Backtesting Library."
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.8"
|
|
@@ -36,6 +36,8 @@ dependencies = [
|
|
|
36
36
|
"seaborn",
|
|
37
37
|
"matplotlib",
|
|
38
38
|
"scipy",
|
|
39
|
+
"plotly",
|
|
40
|
+
"PySide6",
|
|
39
41
|
]
|
|
40
42
|
|
|
41
43
|
[project.optional-dependencies]
|
|
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
|
|
File without changes
|
|
File without changes
|
|
File without changes
|