cyberkyne commited on
Commit
9481f45
Β·
verified Β·
1 Parent(s): 8028a17

Delete src

Browse files
src/BacktestEngine.jl DELETED
@@ -1,326 +0,0 @@
1
- """
2
- BacktestEngine.jl
3
- ─────────────────────────────────────────────────────
4
- Vectorized event-driven backtest engine.
5
-
6
- Inputs:
7
- close, high, low, volume :: Vector{Float64}
8
- signals :: Vector{Int8} (1=long, -1=short, 0=flat)
9
- params :: NamedTuple
10
-
11
- Returns BacktestResult with all performance metrics.
12
-
13
- Complexity: O(n) simulation, O(n) metrics.
14
- All arithmetic is Float64. No allocations inside the hot loop.
15
- """
16
- module BacktestEngine
17
-
18
- using Statistics
19
-
20
- export run_backtest, BacktestResult, BacktestConfig
21
-
22
- include("Indicators.jl")
23
- using .Indicators: atr
24
-
25
- # ── Config ────────────────────────────────────────────
26
-
27
- Base.@kwdef struct BacktestConfig
28
- initial_equity :: Float64 = 10_000.0
29
- commission_pct :: Float64 = 0.0002 # 0.02% per side
30
- slippage_pct :: Float64 = 0.0001
31
- risk_per_trade :: Float64 = 0.01 # 1% per trade
32
- atr_mult :: Float64 = 2.0 # stop at 2Γ—ATR
33
- max_pos_pct :: Float64 = 0.20
34
- atr_period :: Int = 14
35
- end
36
-
37
- # ── Result struct ─────────────────────────────────────
38
-
39
- mutable struct BacktestResult
40
- # Returns
41
- total_return :: Float64
42
- cagr :: Float64
43
- sharpe :: Float64
44
- sortino :: Float64
45
- calmar :: Float64
46
- max_dd :: Float64
47
- max_dd_bars :: Int
48
- # Trades
49
- n_trades :: Int
50
- n_wins :: Int
51
- win_rate :: Float64
52
- profit_factor :: Float64
53
- avg_win_pct :: Float64
54
- avg_loss_pct :: Float64
55
- expectancy :: Float64
56
- avg_bars_held :: Float64
57
- max_consec_wins :: Int
58
- max_consec_loss :: Int
59
- # Capital
60
- final_equity :: Float64
61
- total_comm :: Float64
62
- # Data
63
- equity_curve :: Vector{Float64}
64
- n_bars :: Int
65
- is_valid :: Bool
66
- error_msg :: String
67
- end
68
-
69
- function BacktestResult(; n_bars=0, is_valid=false, error_msg="")
70
- BacktestResult(
71
- 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0,
72
- 0, 0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0, 0,
73
- 10_000.0, 0.0,
74
- Float64[],
75
- n_bars, is_valid, error_msg
76
- )
77
- end
78
-
79
- # ── Bars per year lookup ───────────────────────────────
80
-
81
- const BARS_PER_YEAR = Dict(
82
- "1m" => 525_600, "3m" => 175_200, "5m" => 105_120,
83
- "15m" => 35_040, "30m" => 17_520,
84
- "1h" => 8_760, "2h" => 4_380, "4h" => 2_190,
85
- "6h" => 1_460, "12h" => 730,
86
- "1d" => 252, "1w" => 52,
87
- )
88
-
89
- # ── Main engine ───────────────────────────────────────
90
-
91
- """
92
- run_backtest(open, high, low, close, volume, signals, timeframe, cfg)
93
-
94
- Core vectorized backtest. Hot loop is pure Julia β€” no allocations per bar.
95
- """
96
- function run_backtest(
97
- open_p :: Vector{Float64},
98
- high :: Vector{Float64},
99
- low :: Vector{Float64},
100
- close :: Vector{Float64},
101
- volume :: Vector{Float64},
102
- signals :: Vector{Int},
103
- timeframe :: String = "1h",
104
- cfg :: BacktestConfig = BacktestConfig(),
105
- ) :: BacktestResult
106
-
107
- n = length(close)
108
- n < 50 && return BacktestResult(; n_bars=n, error_msg="Need β‰₯50 bars, got $n")
109
-
110
- # Pre-compute ATR for position sizing
111
- atr_v = atr(high, low, close, cfg.atr_period)
112
-
113
- # ── Simulation ────────────────────────────────────
114
- equity = cfg.initial_equity
115
- eq_curve = fill(cfg.initial_equity, n)
116
-
117
- # Trade tracking (pre-allocate max possible)
118
- trade_pnls = Vector{Float64}(undef, n Γ· 2 + 1)
119
- trade_sizes = Vector{Float64}(undef, n Γ· 2 + 1)
120
- trade_entries = Vector{Float64}(undef, n Γ· 2 + 1)
121
- trade_bars = Vector{Int}(undef, n Γ· 2 + 1)
122
- trade_wins = Vector{Bool}(undef, n Γ· 2 + 1)
123
- n_trades = 0
124
- total_comm = 0.0
125
-
126
- # State
127
- pos = 0 # 1=long, -1=short, 0=flat
128
- entry_px = 0.0
129
- pos_sz = 0.0
130
- stop_px = 0.0
131
- entry_bar = 1
132
- last_trade = 0
133
-
134
- @inbounds for i in 2:n
135
- px = close[i]
136
- sig = signals[i]
137
-
138
- # ── Stop loss check ────────────────────────
139
- if pos != 0
140
- hit = (pos == 1 && low[i] <= stop_px) ||
141
- (pos == -1 && high[i] >= stop_px)
142
- if hit
143
- ep = stop_px * (1.0 + cfg.slippage_pct * pos)
144
- pnl, comm = _close(pos, entry_px, ep, pos_sz, cfg)
145
- n_trades += 1
146
- trade_pnls[n_trades] = pnl - comm
147
- trade_sizes[n_trades] = pos_sz
148
- trade_entries[n_trades] = entry_px
149
- trade_bars[n_trades] = i - entry_bar
150
- trade_wins[n_trades] = pnl > comm
151
- total_comm += comm
152
- equity += pnl - comm
153
- pos = 0
154
- last_trade = i
155
- end
156
- end
157
-
158
- # ── Exit on signal change ──────────────────
159
- if pos != 0 && (sig == 0 || sig == -pos)
160
- ep = px * (1.0 + cfg.slippage_pct * pos)
161
- pnl, comm = _close(pos, entry_px, ep, pos_sz, cfg)
162
- n_trades += 1
163
- trade_pnls[n_trades] = pnl - comm
164
- trade_sizes[n_trades] = pos_sz
165
- trade_entries[n_trades] = entry_px
166
- trade_bars[n_trades] = i - entry_bar
167
- trade_wins[n_trades] = pnl > comm
168
- total_comm += comm
169
- equity += pnl - comm
170
- pos = 0
171
- last_trade = i
172
- end
173
-
174
- # ── Entry ──────────────────────────────────
175
- if pos == 0 && sig != 0 && (i - last_trade) >= 1
176
- ep = px * (1.0 + cfg.slippage_pct * sig)
177
- a_val = isnan(atr_v[i]) ? px * 0.01 : atr_v[i]
178
- dist = cfg.atr_mult * a_val
179
- risk_a = equity * cfg.risk_per_trade
180
- sz = min(
181
- risk_a / max(dist, 1e-8),
182
- equity * cfg.max_pos_pct / ep,
183
- )
184
- sz = max(sz, 1e-8)
185
- pos = sig
186
- entry_px = ep
187
- pos_sz = sz
188
- stop_px = ep - sig * dist
189
- entry_bar = i
190
- end
191
-
192
- # ── Mark-to-market equity ──────────────────
193
- mtm = pos != 0 ? pos * (px - entry_px) * pos_sz : 0.0
194
- eq_curve[i] = equity + mtm
195
- end
196
-
197
- # Close any open position at end
198
- if pos != 0
199
- ep = close[n]
200
- pnl, comm = _close(pos, entry_px, ep, pos_sz, cfg)
201
- n_trades += 1
202
- trade_pnls[n_trades] = pnl - comm
203
- trade_sizes[n_trades] = pos_sz
204
- trade_entries[n_trades] = entry_px
205
- trade_bars[n_trades] = n - entry_bar
206
- trade_wins[n_trades] = pnl > comm
207
- total_comm += comm
208
- equity += pnl - comm
209
- eq_curve[n] = equity
210
- end
211
-
212
- # Trim to actual trade count
213
- pnls = trade_pnls[1:n_trades]
214
- wins = trade_wins[1:n_trades]
215
- bars = trade_bars[1:n_trades]
216
- ents = trade_entries[1:n_trades]
217
- szs = trade_sizes[1:n_trades]
218
-
219
- # ── Compute metrics ────────────────────────────
220
- return _metrics(
221
- eq_curve, pnls, wins, bars, ents, szs,
222
- total_comm, n, timeframe, cfg
223
- )
224
- end
225
-
226
- # ── Helper: close trade ───────────────────────────────
227
-
228
- @inline function _close(pos, entry, exit_px, sz, cfg)
229
- gross = pos * (exit_px - entry) * sz
230
- comm = (entry + exit_px) * sz * cfg.commission_pct
231
- return gross, comm
232
- end
233
-
234
- # ── Metrics computation ───────────────────────────────
235
-
236
- function _metrics(
237
- eq :: Vector{Float64},
238
- pnls :: Vector{Float64},
239
- wins :: Vector{Bool},
240
- bars :: Vector{Int},
241
- entries :: Vector{Float64},
242
- sizes :: Vector{Float64},
243
- total_comm :: Float64,
244
- n_bars :: Int,
245
- tf :: String,
246
- cfg :: BacktestConfig,
247
- ) :: BacktestResult
248
-
249
- init = cfg.initial_equity
250
- final = eq[end]
251
- bpy = get(BARS_PER_YEAR, tf, 252)
252
-
253
- r = BacktestResult(; n_bars=n_bars, is_valid=true)
254
- r.equity_curve = eq
255
- r.final_equity = final
256
- r.total_comm = total_comm
257
- r.total_return = (final - init) / init * 100.0
258
-
259
- # CAGR
260
- years = n_bars / bpy
261
- r.cagr = years > 0 && final > 0 ?
262
- ((final / init)^(1.0/years) - 1.0) * 100.0 : 0.0
263
-
264
- # Drawdown
265
- peak = eq[1]
266
- max_dd = 0.0
267
- dd_run = 0; max_dd_bars = 0
268
- for v in eq
269
- peak = max(peak, v)
270
- dd = (peak - v) / peak
271
- max_dd = max(max_dd, dd)
272
- if v < peak; dd_run += 1; max_dd_bars = max(max_dd_bars, dd_run)
273
- else; dd_run = 0; end
274
- end
275
- r.max_dd = max_dd * 100.0
276
- r.max_dd_bars = max_dd_bars
277
-
278
- # Sharpe / Sortino
279
- rets = diff(eq) ./ eq[1:end-1]
280
- filter!(!isnan, rets)
281
- if length(rets) > 1
282
- mu = mean(rets)
283
- sig = std(rets)
284
- ds = std(filter(x -> x < 0, rets))
285
- af = sqrt(Float64(bpy))
286
- r.sharpe = sig > 0 ? mu/sig * af : 0.0
287
- r.sortino = ds > 0 ? mu/ds * af : 0.0
288
- r.calmar = r.max_dd > 0 ? r.cagr / r.max_dd : 0.0
289
- end
290
-
291
- # Trade stats
292
- n_tr = length(pnls)
293
- r.n_trades = n_tr
294
- n_tr == 0 && return r
295
-
296
- n_win = count(wins)
297
- r.n_wins = n_win
298
- r.win_rate = n_win / n_tr * 100.0
299
-
300
- gw = sum(pnls[wins]); gl = abs(sum(pnls[.!wins]))
301
- r.profit_factor = gl > 0 ? gw / gl : (gw > 0 ? Inf : 0.0)
302
-
303
- # Pct returns per trade
304
- pct = pnls ./ (entries .* sizes .+ 1e-10) .* 100.0
305
- r.avg_win_pct = n_win > 0 ? mean(pct[wins]) : 0.0
306
- r.avg_loss_pct = (n_tr-n_win) > 0 ? mean(pct[.!wins]) : 0.0
307
- r.expectancy = r.win_rate/100.0 * r.avg_win_pct +
308
- (1 - r.win_rate/100.0) * r.avg_loss_pct
309
- r.avg_bars_held = mean(Float64.(bars))
310
-
311
- # Consecutive wins/losses
312
- r.max_consec_wins = _max_run(wins)
313
- r.max_consec_loss = _max_run(.!wins)
314
-
315
- return r
316
- end
317
-
318
- function _max_run(bools::Vector{Bool})::Int
319
- mx = run = 0
320
- for b in bools
321
- b ? (run += 1; mx = max(mx, run)) : (run = 0)
322
- end
323
- return mx
324
- end
325
-
326
- end # module BacktestEngine
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/Indicators.jl DELETED
@@ -1,418 +0,0 @@
1
- """
2
- Indicators.jl
3
- ─────────────────────────────────────────────────────
4
- Vectorized technical indicator library.
5
- All functions operate on Float64 vectors.
6
- Returns Vector{Float64} of same length, NaN for warmup bars.
7
-
8
- Performance: all O(n), fully vectorized, allocation-minimal.
9
- """
10
- module Indicators
11
-
12
- using Statistics
13
-
14
- export sma, ema, wma, tema, dema,
15
- rsi, macd, stoch, cci, williams_r,
16
- atr, bbands, keltner, donchian, adx,
17
- vwap, obv, cmf, zscore, std_dev,
18
- momentum, roc, highest, lowest,
19
- crossover, crossunder
20
-
21
- # ── Utilities ─────────────────────────────────────────
22
-
23
- """Fill NaN for first `n` elements."""
24
- function _warmup(v::Vector{Float64}, n::Int)
25
- result = copy(v)
26
- result[1:min(n, end)] .= NaN
27
- return result
28
- end
29
-
30
- function _nanfill(n::Int)::Vector{Float64}
31
- fill(NaN, n)
32
- end
33
-
34
- # ── Trend ─────────────────────────────────────────────
35
-
36
- """Simple Moving Average β€” O(n)"""
37
- function sma(x::Vector{Float64}, n::Int)::Vector{Float64}
38
- len = length(x)
39
- out = fill(NaN, len)
40
- running = 0.0
41
- for i in 1:len
42
- running += x[i]
43
- if i >= n
44
- if i > n
45
- running -= x[i - n]
46
- end
47
- out[i] = running / n
48
- end
49
- end
50
- return out
51
- end
52
-
53
- """Exponential Moving Average β€” Wilder-style adjusting=false"""
54
- function ema(x::Vector{Float64}, n::Int)::Vector{Float64}
55
- len = length(x)
56
- out = fill(NaN, len)
57
- k = 2.0 / (n + 1.0)
58
- # seed with first non-NaN
59
- seed_i = findfirst(!isnan, x)
60
- seed_i === nothing && return out
61
- val = x[seed_i]
62
- for i in seed_i:len
63
- if isnan(x[i]); continue; end
64
- if i == seed_i
65
- # Build SMA seed over first n valid values
66
- count = 0; s = 0.0
67
- for j in seed_i:len
68
- if !isnan(x[j])
69
- s += x[j]; count += 1
70
- if count == n
71
- val = s / n
72
- out[j] = val
73
- for m in (j+1):len
74
- if !isnan(x[m])
75
- val = x[m] * k + val * (1.0 - k)
76
- out[m] = val
77
- end
78
- end
79
- return out
80
- end
81
- end
82
- end
83
- break
84
- end
85
- end
86
- return out
87
- end
88
-
89
- """Weighted Moving Average"""
90
- function wma(x::Vector{Float64}, n::Int)::Vector{Float64}
91
- len = length(x)
92
- out = fill(NaN, len)
93
- w_sum = n * (n + 1) / 2.0
94
- for i in n:len
95
- s = 0.0
96
- for j in 1:n
97
- s += x[i - n + j] * j
98
- end
99
- out[i] = s / w_sum
100
- end
101
- return out
102
- end
103
-
104
- """Triple EMA: 3e1 - 3e2 + e3"""
105
- function tema(x::Vector{Float64}, n::Int)::Vector{Float64}
106
- e1 = ema(x, n); e2 = ema(e1, n); e3 = ema(e2, n)
107
- return 3.0 .* e1 .- 3.0 .* e2 .+ e3
108
- end
109
-
110
- """Double EMA: 2e1 - e2"""
111
- function dema(x::Vector{Float64}, n::Int)::Vector{Float64}
112
- e1 = ema(x, n); e2 = ema(e1, n)
113
- return 2.0 .* e1 .- e2
114
- end
115
-
116
- # ── Oscillators ───────────────────────────────────────
117
-
118
- """RSI using Wilder's smoothing"""
119
- function rsi(close::Vector{Float64}, n::Int=14)::Vector{Float64}
120
- len = length(close)
121
- out = fill(NaN, len)
122
- n < 1 && return out
123
- avg_gain = 0.0; avg_loss = 0.0
124
- # Seed with first n differences
125
- for i in 2:(n+1)
126
- i > len && break
127
- d = close[i] - close[i-1]
128
- if d > 0; avg_gain += d; else avg_loss += abs(d); end
129
- end
130
- avg_gain /= n; avg_loss /= n
131
- if n + 1 <= len
132
- rs = avg_loss == 0 ? 100.0 : avg_gain / avg_loss
133
- out[n+1] = 100.0 - 100.0 / (1.0 + rs)
134
- end
135
- for i in (n+2):len
136
- d = close[i] - close[i-1]
137
- g = d > 0 ? d : 0.0; l = d < 0 ? abs(d) : 0.0
138
- avg_gain = (avg_gain * (n-1) + g) / n
139
- avg_loss = (avg_loss * (n-1) + l) / n
140
- rs = avg_loss == 0 ? 100.0 : avg_gain / avg_loss
141
- out[i] = 100.0 - 100.0 / (1.0 + rs)
142
- end
143
- return out
144
- end
145
-
146
- """MACD β€” returns (macd_line, signal_line, histogram)"""
147
- function macd(close::Vector{Float64};
148
- fast::Int=12, slow::Int=26, sig::Int=9
149
- )::Tuple{Vector{Float64},Vector{Float64},Vector{Float64}}
150
- ml = ema(close, fast) .- ema(close, slow)
151
- sl = ema(ml, sig)
152
- hist = ml .- sl
153
- return ml, sl, hist
154
- end
155
-
156
- """Stochastic %K and %D"""
157
- function stoch(high::Vector{Float64}, low::Vector{Float64},
158
- close::Vector{Float64};
159
- k::Int=14, d::Int=3
160
- )::Tuple{Vector{Float64},Vector{Float64}}
161
- len = length(close)
162
- K = fill(NaN, len)
163
- for i in k:len
164
- hh = maximum(high[i-k+1:i])
165
- ll = minimum(low[i-k+1:i])
166
- denom = hh - ll
167
- K[i] = denom == 0 ? 50.0 : 100.0 * (close[i] - ll) / denom
168
- end
169
- D = sma(K, d)
170
- return K, D
171
- end
172
-
173
- """Commodity Channel Index"""
174
- function cci(high::Vector{Float64}, low::Vector{Float64},
175
- close::Vector{Float64}, n::Int=20)::Vector{Float64}
176
- len = length(close)
177
- tp = (high .+ low .+ close) ./ 3.0
178
- out = fill(NaN, len)
179
- for i in n:len
180
- window = tp[i-n+1:i]
181
- m = mean(window)
182
- md = mean(abs.(window .- m))
183
- out[i] = md == 0 ? 0.0 : (tp[i] - m) / (0.015 * md)
184
- end
185
- return out
186
- end
187
-
188
- """Williams %R"""
189
- function williams_r(high::Vector{Float64}, low::Vector{Float64},
190
- close::Vector{Float64}, n::Int=14)::Vector{Float64}
191
- len = length(close)
192
- out = fill(NaN, len)
193
- for i in n:len
194
- hh = maximum(high[i-n+1:i])
195
- ll = minimum(low[i-n+1:i])
196
- denom = hh - ll
197
- out[i] = denom == 0 ? -50.0 : -100.0 * (hh - close[i]) / denom
198
- end
199
- return out
200
- end
201
-
202
- """Rate of Change (%)"""
203
- function roc(x::Vector{Float64}, n::Int=10)::Vector{Float64}
204
- len = length(x)
205
- out = fill(NaN, len)
206
- for i in (n+1):len
207
- out[i] = x[i-n] == 0 ? 0.0 : 100.0 * (x[i] - x[i-n]) / x[i-n]
208
- end
209
- return out
210
- end
211
-
212
- """Momentum"""
213
- function momentum(x::Vector{Float64}, n::Int=10)::Vector{Float64}
214
- len = length(x)
215
- out = fill(NaN, len)
216
- for i in (n+1):len
217
- out[i] = x[i] - x[i-n]
218
- end
219
- return out
220
- end
221
-
222
- # ── Volatility ────────────────────────────────────────
223
-
224
- """True Range"""
225
- function _tr(high::Vector{Float64}, low::Vector{Float64},
226
- close::Vector{Float64})::Vector{Float64}
227
- len = length(close)
228
- tr = fill(NaN, len)
229
- tr[1] = high[1] - low[1]
230
- for i in 2:len
231
- tr[i] = max(high[i] - low[i],
232
- abs(high[i] - close[i-1]),
233
- abs(low[i] - close[i-1]))
234
- end
235
- return tr
236
- end
237
-
238
- """Average True Range β€” Wilder's smoothing"""
239
- function atr(high::Vector{Float64}, low::Vector{Float64},
240
- close::Vector{Float64}, n::Int=14)::Vector{Float64}
241
- tr = _tr(high, low, close)
242
- return ema(tr, n)
243
- end
244
-
245
- """Bollinger Bands β€” returns (upper, middle, lower)"""
246
- function bbands(close::Vector{Float64}, n::Int=20,
247
- k::Float64=2.0
248
- )::Tuple{Vector{Float64},Vector{Float64},Vector{Float64}}
249
- len = length(close)
250
- mid = sma(close, n)
251
- sd = fill(NaN, len)
252
- for i in n:len
253
- sd[i] = std(close[i-n+1:i]; corrected=false)
254
- end
255
- upper = mid .+ k .* sd
256
- lower = mid .- k .* sd
257
- return upper, mid, lower
258
- end
259
-
260
- """Keltner Channels β€” returns (upper, middle, lower)"""
261
- function keltner(high::Vector{Float64}, low::Vector{Float64},
262
- close::Vector{Float64}, n::Int=20,
263
- k::Float64=2.0
264
- )::Tuple{Vector{Float64},Vector{Float64},Vector{Float64}}
265
- mid = ema(close, n)
266
- a = atr(high, low, close, n)
267
- upper = mid .+ k .* a
268
- lower = mid .- k .* a
269
- return upper, mid, lower
270
- end
271
-
272
- """Donchian Channels β€” returns (upper, middle, lower)"""
273
- function donchian(high::Vector{Float64}, low::Vector{Float64},
274
- n::Int=20
275
- )::Tuple{Vector{Float64},Vector{Float64},Vector{Float64}}
276
- len = length(high)
277
- upper = fill(NaN, len)
278
- lower = fill(NaN, len)
279
- for i in n:len
280
- upper[i] = maximum(high[i-n+1:i])
281
- lower[i] = minimum(low[i-n+1:i])
282
- end
283
- mid = (upper .+ lower) ./ 2.0
284
- return upper, mid, lower
285
- end
286
-
287
- """Rolling standard deviation"""
288
- function std_dev(x::Vector{Float64}, n::Int=20)::Vector{Float64}
289
- len = length(x)
290
- out = fill(NaN, len)
291
- for i in n:len
292
- out[i] = std(x[i-n+1:i]; corrected=false)
293
- end
294
- return out
295
- end
296
-
297
- """Rolling Z-score"""
298
- function zscore(x::Vector{Float64}, n::Int=20)::Vector{Float64}
299
- mu = sma(x, n)
300
- sd = std_dev(x, n)
301
- out = fill(NaN, length(x))
302
- for i in eachindex(x)
303
- if !isnan(mu[i]) && !isnan(sd[i]) && sd[i] > 0
304
- out[i] = (x[i] - mu[i]) / sd[i]
305
- end
306
- end
307
- return out
308
- end
309
-
310
- # ── Trend Strength ────────────────────────────────────
311
-
312
- """ADX, +DI, -DI"""
313
- function adx(high::Vector{Float64}, low::Vector{Float64},
314
- close::Vector{Float64}, n::Int=14
315
- )::Tuple{Vector{Float64},Vector{Float64},Vector{Float64}}
316
- len = length(close)
317
- tr = _tr(high, low, close)
318
- up_mv = diff(vcat(high[1], high))
319
- dn_mv = diff(vcat(low[1], low))
320
-
321
- pdm = map((u,d) -> (u > d && u > 0) ? u : 0.0, up_mv, dn_mv)
322
- ndm = map((u,d) -> (d > u && d > 0) ? d : 0.0, up_mv, dn_mv)
323
-
324
- sm_tr = ema(tr, n)
325
- sm_pdm = ema(pdm, n)
326
- sm_ndm = ema(ndm, n)
327
-
328
- pdi = 100.0 .* sm_pdm ./ (sm_tr .+ 1e-10)
329
- ndi = 100.0 .* sm_ndm ./ (sm_tr .+ 1e-10)
330
- dx = 100.0 .* abs.(pdi .- ndi) ./ (pdi .+ ndi .+ 1e-10)
331
- adx_v = ema(dx, n)
332
-
333
- return adx_v, pdi, ndi
334
- end
335
-
336
- # ── Volume ────────────────────────────────────────────
337
-
338
- """VWAP (session-based, cumulative)"""
339
- function vwap(high::Vector{Float64}, low::Vector{Float64},
340
- close::Vector{Float64}, volume::Vector{Float64})::Vector{Float64}
341
- tp = (high .+ low .+ close) ./ 3.0
342
- cum_pv = cumsum(tp .* volume)
343
- cum_vol = cumsum(volume)
344
- return cum_pv ./ (cum_vol .+ 1e-10)
345
- end
346
-
347
- """On-Balance Volume"""
348
- function obv(close::Vector{Float64}, volume::Vector{Float64})::Vector{Float64}
349
- len = length(close)
350
- out = zeros(Float64, len)
351
- out[1] = volume[1]
352
- for i in 2:len
353
- d = close[i] - close[i-1]
354
- out[i] = out[i-1] + (d > 0 ? volume[i] : d < 0 ? -volume[i] : 0.0)
355
- end
356
- return out
357
- end
358
-
359
- """Chaikin Money Flow"""
360
- function cmf(high::Vector{Float64}, low::Vector{Float64},
361
- close::Vector{Float64}, volume::Vector{Float64},
362
- n::Int=20)::Vector{Float64}
363
- len = length(close)
364
- out = fill(NaN, len)
365
- hl = high .- low
366
- mf_mult = map((c,l,h,hl) -> hl == 0 ? 0.0 : (2c - l - h) / hl,
367
- close, low, high, hl)
368
- mf_vol = mf_mult .* volume
369
- for i in n:len
370
- sv = sum(volume[i-n+1:i])
371
- out[i] = sv == 0 ? 0.0 : sum(mf_vol[i-n+1:i]) / sv
372
- end
373
- return out
374
- end
375
-
376
- # ── Rolling utilities ─────────────────────────────────
377
-
378
- """Rolling maximum"""
379
- function highest(x::Vector{Float64}, n::Int)::Vector{Float64}
380
- len = length(x)
381
- out = fill(NaN, len)
382
- for i in n:len
383
- out[i] = maximum(x[i-n+1:i])
384
- end
385
- return out
386
- end
387
-
388
- """Rolling minimum"""
389
- function lowest(x::Vector{Float64}, n::Int)::Vector{Float64}
390
- len = length(x)
391
- out = fill(NaN, len)
392
- for i in n:len
393
- out[i] = minimum(x[i-n+1:i])
394
- end
395
- return out
396
- end
397
-
398
- """Crossover: a crosses above b"""
399
- function crossover(a::Vector{Float64}, b::Vector{Float64})::Vector{Bool}
400
- len = length(a)
401
- out = fill(false, len)
402
- for i in 2:len
403
- out[i] = a[i] > b[i] && a[i-1] <= b[i-1]
404
- end
405
- return out
406
- end
407
-
408
- """Crossunder: a crosses below b"""
409
- function crossunder(a::Vector{Float64}, b::Vector{Float64})::Vector{Bool}
410
- len = length(a)
411
- out = fill(false, len)
412
- for i in 2:len
413
- out[i] = a[i] < b[i] && a[i-1] >= b[i-1]
414
- end
415
- return out
416
- end
417
-
418
- end # module Indicators
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/Manifest.toml DELETED
@@ -1,19 +0,0 @@
1
- # This file is machine-generated - editing it directly is not recommended
2
- julia_version = "1.10.7"
3
- manifest_format = "2.0"
4
- project_hash = "abc123"
5
-
6
- [[deps.JSON3]]
7
- deps = ["Dates", "Mmap", "Parsers", "PrecompileTools", "StructTypes", "UUIDs"]
8
- git-tree-sha1 = "eb3edce0ed4fa32f75a0a11217433c31d56bd48b"
9
- uuid = "0f8b85d8-7e73-4b43-9b43-f8e4f07d6bcd"
10
- version = "1.14.0"
11
-
12
- [[deps.Random]]
13
- deps = ["SHA"]
14
- uuid = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c"
15
-
16
- [[deps.Statistics]]
17
- deps = ["LinearAlgebra", "SparseArrays"]
18
- uuid = "10745b16-79ce-11e8-11f9-7d13ad32a3b2"
19
- version = "1.10.0"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/Optimizer.jl DELETED
@@ -1,307 +0,0 @@
1
- """
2
- Optimizer.jl
3
- ─────────────────────────────────────────────────────
4
- Walk-forward optimization engine.
5
-
6
- Algorithm:
7
- 1. Split data into N anchored windows
8
- 2. Per window: grid search on IS β†’ pick best Sharpe params
9
- 3. Test best params OOS β†’ record result
10
- 4. Final params: Sharpe-weighted median vote across windows
11
- 5. Compute WF efficiency, robustness score, viability
12
-
13
- All heavy computation runs in Julia.
14
- Python receives a Dict with the final results.
15
- """
16
- module Optimizer
17
-
18
- using Statistics
19
- using Random
20
-
21
- export walk_forward_optimize, OptimResult
22
-
23
- include("BacktestEngine.jl")
24
- using .BacktestEngine: run_backtest, BacktestConfig, BacktestResult
25
-
26
- # ── Result struct ─────────────────────────────────────
27
-
28
- mutable struct OptimResult
29
- strategy_name :: String
30
- symbol :: String
31
- timeframe :: String
32
- optimal_params :: Dict{String, Float64}
33
- oos_sharpe_mean:: Float64
34
- oos_sharpe_std :: Float64
35
- oos_win_rate :: Float64
36
- oos_max_dd :: Float64
37
- oos_pf_mean :: Float64
38
- oos_trades :: Int
39
- wf_efficiency :: Float64
40
- robustness :: Float64
41
- is_viable :: Bool
42
- reasons :: Vector{String}
43
- oos_sharpes :: Vector{Float64} # per-window OOS Sharpes
44
- end
45
-
46
- function OptimResult(name, symbol, tf)
47
- OptimResult(
48
- name, symbol, tf,
49
- Dict{String,Float64}(),
50
- 0.0, 0.0, 0.0, 0.0, 0.0, 0, 0.0, 0.0, false,
51
- String[], Float64[]
52
- )
53
- end
54
-
55
- # ── Main optimizer ────────────────────────────────────
56
-
57
- """
58
- walk_forward_optimize(signal_fn, param_grid, open_p, high, low, close, volume,
59
- timeframe, strategy_name, symbol;
60
- n_windows, is_ratio, min_trades, min_sharpe,
61
- max_combinations, cfg)
62
-
63
- signal_fn :: (open, high, low, close, volume, params) -> Vector{Int}
64
- param_grid :: Dict{String, Vector{Float64}}
65
- """
66
- function walk_forward_optimize(
67
- signal_fn :: Function,
68
- param_grid :: Dict{String, Vector{Float64}},
69
- open_p :: Vector{Float64},
70
- high :: Vector{Float64},
71
- low :: Vector{Float64},
72
- close :: Vector{Float64},
73
- volume :: Vector{Float64},
74
- timeframe :: String,
75
- strategy_name :: String,
76
- symbol :: String;
77
- n_windows :: Int = 5,
78
- is_ratio :: Float64 = 0.70,
79
- min_trades :: Int = 30,
80
- min_sharpe :: Float64 = 0.5,
81
- max_combos :: Int = 300,
82
- cfg :: BacktestConfig = BacktestConfig(),
83
- ) :: OptimResult
84
-
85
- result = OptimResult(strategy_name, symbol, timeframe)
86
- n = length(close)
87
-
88
- n < 200 && (push!(result.reasons, "Need β‰₯200 bars, got $n"); return result)
89
- isempty(param_grid) && (param_grid = Dict{String,Float64}())
90
-
91
- combos = _build_combos(param_grid, max_combos)
92
- windows = _build_windows(n, n_windows)
93
- isempty(windows) && (push!(result.reasons, "Could not build WF windows"); return result)
94
-
95
- win_params = Vector{Dict{String,Float64}}()
96
- is_sharpes = Float64[]
97
- oos_sharpes = Float64[]
98
- oos_results = Vector{BacktestResult}()
99
-
100
- for (is_s, is_e, oos_s, oos_e) in windows
101
- is_o = open_p[is_s:is_e]; is_h = high[is_s:is_e]
102
- is_l = low[is_s:is_e]; is_c = close[is_s:is_e]
103
- is_v = volume[is_s:is_e]
104
-
105
- best_p = nothing; best_sh = -Inf
106
-
107
- for params in combos
108
- r = _run_one(signal_fn, is_o, is_h, is_l, is_c, is_v,
109
- params, timeframe, strategy_name, symbol, cfg)
110
- if r.is_valid && r.n_trades >= min_trades && r.sharpe > best_sh
111
- best_sh = r.sharpe; best_p = params
112
- end
113
- end
114
-
115
- best_p === nothing && continue
116
-
117
- push!(win_params, best_p)
118
- push!(is_sharpes, best_sh)
119
-
120
- oos_o = open_p[oos_s:oos_e]; oos_h = high[oos_s:oos_e]
121
- oos_l = low[oos_s:oos_e]; oos_c = close[oos_s:oos_e]
122
- oos_v = volume[oos_s:oos_e]
123
-
124
- oos_r = _run_one(signal_fn, oos_o, oos_h, oos_l, oos_c, oos_v,
125
- best_p, timeframe, strategy_name, symbol, cfg)
126
- push!(oos_results, oos_r)
127
- push!(oos_sharpes, oos_r.sharpe)
128
- end
129
-
130
- isempty(oos_results) && (push!(result.reasons, "No valid WF windows"); return result)
131
-
132
- # ── Aggregate OOS metrics ─────────────────────────
133
- valid_oos = filter(r -> r.is_valid && r.n_trades >= min_trades, oos_results)
134
- result.oos_sharpes = oos_sharpes
135
-
136
- if !isempty(valid_oos)
137
- sh = [r.sharpe for r in valid_oos]
138
- result.oos_sharpe_mean = mean(sh)
139
- result.oos_sharpe_std = std(sh)
140
- result.oos_win_rate = mean([r.win_rate for r in valid_oos])
141
- result.oos_max_dd = mean([r.max_dd for r in valid_oos])
142
- result.oos_pf_mean = mean(filter(x->x<100, [r.profit_factor for r in valid_oos]))
143
- result.oos_trades = sum(r.n_trades for r in valid_oos)
144
- end
145
-
146
- # WF efficiency
147
- if !isempty(is_sharpes) && !isempty(oos_sharpes)
148
- mean_is = mean(is_sharpes)
149
- mean_oos = mean(oos_sharpes)
150
- result.wf_efficiency = mean_is > 0 ? mean_oos / mean_is : 0.0
151
- end
152
-
153
- # Optimal params via Sharpe-weighted median vote
154
- result.optimal_params = _vote_params(win_params, oos_sharpes)
155
-
156
- # Robustness & viability
157
- result.robustness = _robustness(result, min_trades)
158
- result.is_viable, result.reasons =
159
- _viability(result, min_trades, min_sharpe)
160
-
161
- return result
162
- end
163
-
164
- # ── Single backtest run ───────────────────────────────
165
-
166
- function _run_one(signal_fn, o, h, l, c, v, params, tf, name, sym, cfg)
167
- try
168
- sigs = signal_fn(o, h, l, c, v, params)
169
- return run_backtest(o, h, l, c, v, sigs, tf, cfg)
170
- catch e
171
- return BacktestResult(; error_msg=string(e))
172
- end
173
- end
174
-
175
- # ── Build parameter combinations ─────────────────────
176
-
177
- function _build_combos(
178
- grid :: Dict{String, Vector{Float64}},
179
- max_c :: Int,
180
- ) :: Vector{Dict{String, Float64}}
181
-
182
- isempty(grid) && return [Dict{String,Float64}()]
183
-
184
- keys_ = collect(keys(grid))
185
- vals_ = [grid[k] for k in keys_]
186
- n_all = prod(length(v) for v in vals_)
187
-
188
- # Cartesian product
189
- all_c = Vector{Dict{String,Float64}}()
190
- sizehint!(all_c, min(n_all, max_c))
191
-
192
- indices = ones(Int, length(keys_))
193
- for _ in 1:n_all
194
- d = Dict(keys_[j] => vals_[j][indices[j]] for j in eachindex(keys_))
195
- push!(all_c, d)
196
- # Increment indices
197
- for j in length(indices):-1:1
198
- indices[j] += 1
199
- if indices[j] <= length(vals_[j]); break
200
- else; indices[j] = 1; end
201
- end
202
- end
203
-
204
- # Random sample if too many
205
- if length(all_c) > max_c
206
- idx = randperm(length(all_c))[1:max_c]
207
- all_c = all_c[idx]
208
- end
209
-
210
- return all_c
211
- end
212
-
213
- # ── Build anchored walk-forward windows ───────────────
214
-
215
- function _build_windows(n::Int, n_win::Int
216
- )::Vector{Tuple{Int,Int,Int,Int}}
217
- oos_sz = max(50, n Γ· (n_win * 2))
218
- windows = Tuple{Int,Int,Int,Int}[]
219
- for i in 0:(n_win-1)
220
- oos_e = n - i * oos_sz
221
- oos_s = oos_e - oos_sz + 1
222
- is_e = oos_s - 1
223
- is_s = 1
224
- is_e - is_s < 100 && continue
225
- oos_e - oos_s < 50 && continue
226
- push!(windows, (is_s, is_e, oos_s, oos_e))
227
- end
228
- return reverse(windows) # chronological order
229
- end
230
-
231
- # ── Sharpe-weighted median vote ───────────────────────
232
-
233
- function _vote_params(
234
- param_list :: Vector{Dict{String,Float64}},
235
- oos_sharpes :: Vector{Float64},
236
- ) :: Dict{String, Float64}
237
-
238
- isempty(param_list) && return Dict{String,Float64}()
239
- length(param_list) == 1 && return param_list[1]
240
-
241
- weights = max.(0.0, oos_sharpes[1:length(param_list)])
242
- total_w = sum(weights)
243
- weights = total_w > 0 ? weights ./ total_w :
244
- fill(1.0/length(param_list), length(param_list))
245
-
246
- keys_ = collect(keys(param_list[1]))
247
- result = Dict{String,Float64}()
248
-
249
- for k in keys_
250
- vals = [p[k] for p in param_list if haskey(p, k)]
251
- w = weights[1:length(vals)]
252
- # Weighted median
253
- si = sortperm(vals)
254
- cv = cumsum(w[si])
255
- mi = findfirst(x -> x >= 0.5, cv)
256
- result[k] = vals[si[mi !== nothing ? mi : end]]
257
- end
258
-
259
- return result
260
- end
261
-
262
- # ── Robustness score (0-100) ──────────────────────────
263
-
264
- function _robustness(r::OptimResult, min_trades::Int) :: Float64
265
- s = 0.0
266
- s += clamp(r.wf_efficiency, 0.0, 1.0) * 40.0
267
- if r.oos_sharpe_mean > 0
268
- cv = r.oos_sharpe_std / (r.oos_sharpe_mean + 1e-9)
269
- s += clamp(1.0 - cv, 0.0, 1.0) * 30.0
270
- end
271
- s += clamp(r.oos_trades / max(1, min_trades * 10), 0.0, 1.0) * 20.0
272
- r.oos_pf_mean > 1 && (s += clamp((r.oos_pf_mean-1)/2, 0.0, 1.0) * 10.0)
273
- return round(s; digits=1)
274
- end
275
-
276
- # ── Viability assessment ──────────────────────────────
277
-
278
- function _viability(
279
- r :: OptimResult,
280
- min_trades :: Int,
281
- min_sharpe :: Float64,
282
- ) :: Tuple{Bool, Vector{String}}
283
-
284
- reasons = String[]
285
- r.oos_sharpe_mean < min_sharpe &&
286
- push!(reasons, "OOS Sharpe $(round(r.oos_sharpe_mean;digits=2)) < $min_sharpe")
287
- r.oos_trades < min_trades &&
288
- push!(reasons, "Too few OOS trades: $(r.oos_trades) < $min_trades")
289
- r.oos_max_dd > 30.0 &&
290
- push!(reasons, "High avg drawdown: $(round(r.oos_max_dd;digits=1))%")
291
- r.wf_efficiency < 0.3 &&
292
- push!(reasons, "Low WF efficiency: $(round(r.wf_efficiency;digits=2))")
293
- r.oos_pf_mean < 1.1 &&
294
- push!(reasons, "Profit factor $(round(r.oos_pf_mean;digits=2)) < 1.1")
295
-
296
- viable = isempty(reasons)
297
- if viable
298
- push!(reasons,
299
- "βœ… Sharpe=$(round(r.oos_sharpe_mean;digits=2)) " *
300
- "DD=$(round(r.oos_max_dd;digits=1))% " *
301
- "WFE=$(round(r.wf_efficiency;digits=2)) " *
302
- "Score=$(r.robustness)/100")
303
- end
304
- return viable, reasons
305
- end
306
-
307
- end # module Optimizer
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/Project.toml DELETED
@@ -1,7 +0,0 @@
1
- [deps]
2
- JSON3 = "0f8b85d8-7e73-4b43-9b43-f8e4f07d6bcd"
3
- Random = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c"
4
- Statistics = "10745b16-79ce-11e8-11f9-7d13ad32a3b2"
5
-
6
- [compat]
7
- julia = "1.10"
 
 
 
 
 
 
 
 
src/QuantEngine.jl DELETED
@@ -1,124 +0,0 @@
1
- """
2
- QuantEngine.jl
3
- ─────────────────────────────────────────────────────
4
- Top-level module. This is what Python imports via juliacall.
5
-
6
- Exposes a clean, flat API that python can call with simple types
7
- (arrays of Float64, Dicts, Strings) β€” no Julia-specific types
8
- crossing the boundary.
9
- """
10
- module QuantEngine
11
-
12
- using Statistics
13
-
14
- include("Indicators.jl")
15
- include("BacktestEngine.jl")
16
- include("Optimizer.jl")
17
- include("SignalCompiler.jl")
18
-
19
- using .Indicators
20
- using .BacktestEngine
21
- using .Optimizer
22
- using .SignalCompiler
23
-
24
- export
25
- # Indicators (all return Vector{Float64})
26
- sma, ema, wma, tema, dema,
27
- rsi, macd, stoch, cci, williams_r,
28
- atr, bbands, keltner, donchian, adx,
29
- vwap, obv, cmf, zscore, std_dev,
30
- momentum, roc, highest, lowest,
31
- crossover, crossunder,
32
- # Engine
33
- run_backtest, BacktestConfig,
34
- # Optimizer
35
- walk_forward_optimize,
36
- # Compiler
37
- compile_strategy,
38
- # High-level pipeline
39
- full_backtest_pipeline
40
-
41
- # ── High-level pipeline function ─────────────────────
42
- """
43
- full_backtest_pipeline(strategy_code, strategy_name,
44
- open_p, high, low, close, volume,
45
- timeframe, symbol;
46
- kwargs...) -> Dict
47
-
48
- End-to-end: compile β†’ optimize β†’ return result as a plain Dict
49
- that crosses cleanly to Python via juliacall.
50
- """
51
- function full_backtest_pipeline(
52
- strategy_code :: String,
53
- strategy_name :: String,
54
- open_p :: Vector{Float64},
55
- high :: Vector{Float64},
56
- low :: Vector{Float64},
57
- close :: Vector{Float64},
58
- volume :: Vector{Float64},
59
- timeframe :: String,
60
- symbol :: String;
61
- n_windows :: Int = 5,
62
- is_ratio :: Float64 = 0.70,
63
- min_trades :: Int = 30,
64
- min_sharpe :: Float64 = 0.5,
65
- max_combos :: Int = 300,
66
- initial_equity :: Float64 = 10_000.0,
67
- commission_pct :: Float64 = 0.0002,
68
- risk_per_trade :: Float64 = 0.01,
69
- ) :: Dict{String, Any}
70
-
71
- # 1. Compile strategy
72
- compiled = compile_strategy(strategy_name, strategy_code)
73
- if !compiled.is_valid
74
- return Dict{String,Any}(
75
- "is_valid" => false,
76
- "error" => compiled.error,
77
- "strategy" => strategy_name,
78
- "symbol" => symbol,
79
- "timeframe" => timeframe,
80
- )
81
- end
82
-
83
- # 2. Walk-forward optimize
84
- cfg = BacktestConfig(
85
- initial_equity = initial_equity,
86
- commission_pct = commission_pct,
87
- risk_per_trade = risk_per_trade,
88
- )
89
-
90
- opt = walk_forward_optimize(
91
- compiled.generate_fn,
92
- compiled.param_grid_fn(),
93
- open_p, high, low, close, volume,
94
- timeframe, strategy_name, symbol;
95
- n_windows = n_windows,
96
- is_ratio = is_ratio,
97
- min_trades = min_trades,
98
- min_sharpe = min_sharpe,
99
- max_combos = max_combos,
100
- cfg = cfg,
101
- )
102
-
103
- # 3. Return as plain Dict (crosses Python boundary cleanly)
104
- return Dict{String,Any}(
105
- "is_valid" => true,
106
- "strategy" => opt.strategy_name,
107
- "symbol" => opt.symbol,
108
- "timeframe" => opt.timeframe,
109
- "optimal_params" => opt.optimal_params,
110
- "oos_sharpe_mean" => opt.oos_sharpe_mean,
111
- "oos_sharpe_std" => opt.oos_sharpe_std,
112
- "oos_win_rate" => opt.oos_win_rate,
113
- "oos_max_dd" => opt.oos_max_dd,
114
- "oos_pf_mean" => opt.oos_pf_mean,
115
- "oos_trades" => opt.oos_trades,
116
- "wf_efficiency" => opt.wf_efficiency,
117
- "robustness" => opt.robustness,
118
- "is_viable" => opt.is_viable,
119
- "reasons" => opt.reasons,
120
- "oos_sharpes" => opt.oos_sharpes,
121
- )
122
- end
123
-
124
- end # module QuantEngine
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/SignalCompiler.jl DELETED
@@ -1,151 +0,0 @@
1
- """
2
- SignalCompiler.jl
3
- ─────────────────────────────────────────────────────
4
- Compiles AI-generated Julia strategy code into callable functions.
5
-
6
- Sandbox design:
7
- - Creates a fresh anonymous Module per strategy
8
- - Injects all Indicators functions as module-level constants
9
- - Injects safe Base/Statistics functions
10
- - No `using` statements inside sandbox (avoids relative-path issues)
11
- - Validates both required functions exist
12
- - Smoke-tests with synthetic 200-bar OHLCV data
13
- """
14
- module SignalCompiler
15
-
16
- using Statistics, Random
17
-
18
- export compile_strategy, CompiledStrategy
19
-
20
- include("Indicators.jl")
21
- using .Indicators
22
-
23
- # ── Strategy handle ───────────────────────────────────
24
-
25
- struct CompiledStrategy
26
- name :: String
27
- generate_fn :: Function
28
- param_grid_fn :: Function
29
- is_valid :: Bool
30
- error :: String
31
- end
32
-
33
- CompiledStrategy(name::String; error::String="") =
34
- CompiledStrategy(name,
35
- (o,h,l,c,v,p) -> zeros(Int, length(c)),
36
- () -> Dict{String,Vector{Float64}}(),
37
- false, error)
38
-
39
- # ── Compiler ──────────────────────────────────────────
40
-
41
- """
42
- compile_strategy(name, code) -> CompiledStrategy
43
-
44
- Evaluate AI-generated Julia code in a sandboxed Module.
45
- All Indicators functions are pre-injected so the strategy code
46
- can call sma(), rsi() etc. directly without any import statement.
47
- """
48
- function compile_strategy(name::String, code::String) :: CompiledStrategy
49
- safe_name = replace(replace(name, " " => "_"), r"[^\w]" => "x")
50
- sandbox = Module(Symbol("Strat_" * safe_name * "_" * string(rand(UInt16), base=16)))
51
-
52
- # ── Pre-inject Indicators ─────────────────────────
53
- for fn_name in names(Indicators; all=false)
54
- fn_name == :Indicators && continue
55
- if isdefined(Indicators, fn_name)
56
- try
57
- Core.eval(sandbox,
58
- Expr(:const, Expr(:(=), fn_name, getfield(Indicators, fn_name))))
59
- catch; end
60
- end
61
- end
62
-
63
- # ── Pre-inject Statistics ─────────────────────────
64
- for sym in (:mean, :std, :var, :median, :cor, :cov)
65
- isdefined(Statistics, sym) &&
66
- Core.eval(sandbox,
67
- Expr(:const, Expr(:(=), sym, getfield(Statistics, sym))))
68
- end
69
-
70
- # ── Pre-inject safe Base functions ───────────────
71
- for sym in (
72
- :length, :size, :zeros, :ones, :fill, :similar,
73
- :sum, :prod, :diff, :cumsum, :cumprod,
74
- :max, :min, :abs, :sqrt, :log, :exp, :floor, :ceil, :round, :clamp,
75
- :isnan, :isinf, :isfinite, :sign,
76
- :sort, :sortperm, :reverse, :unique, :findall, :findfirst,
77
- :push!, :append!, :pop!, :first, :last, :eachindex,
78
- :map, :filter, :any, :all, :count,
79
- :Int, :Float64, :Bool,
80
- :Dict, :Vector, :Tuple, :Set,
81
- :NaN, :Inf, :pi, :true, :false,
82
- :println, :string, :@inbounds,
83
- )
84
- try
85
- val = sym in (:NaN, :Inf, :pi, :true, :false) ?
86
- getfield(Base, sym) : getfield(Base, sym)
87
- Core.eval(sandbox, Expr(:const, Expr(:(=), sym, val)))
88
- catch; end
89
- end
90
-
91
- # ── Parse and evaluate generated code ────────────
92
- parsed = try
93
- Meta.parseall(code)
94
- catch e
95
- return CompiledStrategy(name; error="Parse error: $(sprint(showerror, e))")
96
- end
97
-
98
- try
99
- Core.eval(sandbox, parsed)
100
- catch e
101
- return CompiledStrategy(name; error="Eval error: $(sprint(showerror, e))")
102
- end
103
-
104
- # ── Validate required functions ───────────────────
105
- isdefined(sandbox, :get_param_grid) ||
106
- return CompiledStrategy(name;
107
- error="Missing: get_param_grid() -> Dict{String,Vector{Float64}}")
108
- isdefined(sandbox, :generate_signals) ||
109
- return CompiledStrategy(name;
110
- error="Missing: generate_signals(o,h,l,c,v,params) -> Vector{Int}")
111
-
112
- gen_fn = getfield(sandbox, :generate_signals)
113
- grid_fn = getfield(sandbox, :get_param_grid)
114
-
115
- # ── Smoke test ────────────────────────────────────
116
- err = _smoke_test(gen_fn, grid_fn)
117
- err != "" && return CompiledStrategy(name; error=err)
118
-
119
- return CompiledStrategy(name, gen_fn, grid_fn, true, "")
120
- end
121
-
122
- # ── Smoke test ────────────────────────────────────────
123
-
124
- function _smoke_test(gen_fn, grid_fn) :: String
125
- try
126
- grid = grid_fn()
127
- grid isa Dict || return "get_param_grid() must return Dict"
128
- params = Dict{String,Float64}(
129
- k => (v isa Vector && !isempty(v) ? Float64(v[1]) : 0.0)
130
- for (k,v) in grid)
131
-
132
- n = 200
133
- c = 100.0 .* exp.(cumsum(randn(n) .* 0.005))
134
- h = c .* (1.0 .+ abs.(randn(n)) .* 0.003)
135
- l = c .* (1.0 .- abs.(randn(n)) .* 0.003)
136
- o = c .* (1.0 .+ randn(n) .* 0.001)
137
- v = abs.(randn(n)) .* 1000.0 .+ 500.0
138
-
139
- sigs = gen_fn(o, h, l, c, v, params)
140
-
141
- sigs isa Vector || return "generate_signals must return Vector, got $(typeof(sigs))"
142
- length(sigs) != n && return "Signal length $(length(sigs)) β‰  $n"
143
- any(s -> !(s in (-1, 0, 1)), sigs) &&
144
- return "Signal values must be in {-1,0,1}, got $(unique(sigs))"
145
- catch e
146
- return "Runtime: $(sprint(showerror, e))"
147
- end
148
- return ""
149
- end
150
-
151
- end # module SignalCompiler
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/strategy_template.jl DELETED
@@ -1,118 +0,0 @@
1
- # ═══════════════════════════════════════════════════════════════════
2
- # JULIA STRATEGY TEMPLATE
3
- # This is the exact format Claude generates for each strategy.
4
- # Two functions required. No module/using declarations needed β€”
5
- # all Indicators functions are pre-injected by SignalCompiler.jl.
6
- # ═══════════════════════════════════════════════════════════════════
7
-
8
- # ── Example: EMA Crossover Strategy ─────────────────────────────────
9
-
10
- """
11
- Return parameter ranges for walk-forward grid search.
12
- Keys must be valid Julia identifiers. Values are Float64 ranges.
13
- """
14
- function get_param_grid() :: Dict{String, Vector{Float64}}
15
- return Dict(
16
- "fast_period" => [10.0, 15.0, 20.0, 25.0],
17
- "slow_period" => [40.0, 50.0, 60.0, 80.0],
18
- "atr_filter" => [14.0], # single value = no optimization
19
- )
20
- end
21
-
22
- """
23
- Generate trading signals from OHLCV arrays.
24
-
25
- Arguments (all same length n):
26
- open_p, high, low, close, volume :: Vector{Float64}
27
- params :: Dict{String,Float64} β€” one value per key from get_param_grid()
28
-
29
- Returns Vector{Int} of length n:
30
- 1 = enter/hold long
31
- -1 = enter/hold short
32
- 0 = flat / no position
33
-
34
- Rules:
35
- - Return 0 for the first ~slow_period bars (warmup / NaN period)
36
- - Always use isnan() checks before comparisons
37
- - Signals are position signals, not entry triggers
38
- (engine manages entries/exits from signal transitions)
39
- """
40
- function generate_signals(
41
- open_p :: Vector{Float64},
42
- high :: Vector{Float64},
43
- low :: Vector{Float64},
44
- close :: Vector{Float64},
45
- volume :: Vector{Float64},
46
- params :: Dict{String, Float64},
47
- ) :: Vector{Int}
48
-
49
- n = length(close)
50
- fast_p = Int(round(get(params, "fast_period", 20.0)))
51
- slow_p = Int(round(get(params, "slow_period", 50.0)))
52
- atr_p = Int(round(get(params, "atr_filter", 14.0)))
53
-
54
- fast_ema = ema(close, fast_p)
55
- slow_ema = ema(close, slow_p)
56
- atr_vals = atr(high, low, close, atr_p)
57
-
58
- signals = zeros(Int, n)
59
-
60
- for i in (slow_p + 1):n
61
- # Skip if any indicator is NaN (still in warmup)
62
- isnan(fast_ema[i]) && continue
63
- isnan(slow_ema[i]) && continue
64
- isnan(atr_vals[i]) && continue
65
-
66
- # Optional: ATR volatility filter β€” only trade when market is moving
67
- atr_threshold = close[i] * 0.001 # 0.1% of price
68
- atr_vals[i] < atr_threshold && continue
69
-
70
- if fast_ema[i] > slow_ema[i]
71
- signals[i] = 1 # bullish: long
72
- elseif fast_ema[i] < slow_ema[i]
73
- signals[i] = -1 # bearish: short
74
- else
75
- signals[i] = 0 # neutral
76
- end
77
- end
78
-
79
- return signals
80
- end
81
-
82
- # ═══════════════════════════════════════════════════════════════════
83
- # Example 2: RSI Mean Reversion
84
- # ═══════════════════════════════════════════════════════════════════
85
-
86
- # function get_param_grid()
87
- # return Dict(
88
- # "rsi_period" => [7.0, 10.0, 14.0, 21.0],
89
- # "oversold" => [25.0, 30.0, 35.0],
90
- # "overbought" => [65.0, 70.0, 75.0],
91
- # "ma_period" => [20.0, 50.0],
92
- # )
93
- # end
94
- #
95
- # function generate_signals(open_p, high, low, close, volume, params)
96
- # n = length(close)
97
- # rsi_p = Int(round(get(params, "rsi_period", 14.0)))
98
- # oversold = get(params, "oversold", 30.0)
99
- # overbought = get(params, "overbought", 70.0)
100
- # ma_p = Int(round(get(params, "ma_period", 50.0)))
101
- #
102
- # rsi_vals = rsi(close, rsi_p)
103
- # trend_ma = sma(close, ma_p)
104
- # signals = zeros(Int, n)
105
- #
106
- # for i in (ma_p + rsi_p + 1):n
107
- # isnan(rsi_vals[i]) && continue
108
- # isnan(trend_ma[i]) && continue
109
- #
110
- # # Mean reversion: buy oversold in uptrend, sell overbought in downtrend
111
- # if rsi_vals[i] < oversold && close[i] > trend_ma[i]
112
- # signals[i] = 1
113
- # elseif rsi_vals[i] > overbought && close[i] < trend_ma[i]
114
- # signals[i] = -1
115
- # end
116
- # end
117
- # return signals
118
- # end
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/warmup.jl DELETED
@@ -1,87 +0,0 @@
1
- """
2
- warmup.jl
3
- ─────────────────────────────────────────────────────
4
- Runs at container startup via Dockerfile.
5
- Forces Julia to JIT-compile all hot paths so the first
6
- real user request doesn't pay compilation overhead.
7
- """
8
-
9
- push!(LOAD_PATH, @__DIR__)
10
- include(joinpath(@__DIR__, "QuantEngine.jl"))
11
- using .QuantEngine
12
- using Statistics, Random
13
-
14
- println("Warming up QuantEngine hot paths...")
15
-
16
- # ── Generate synthetic data ────────────────────────────
17
- n = 500
18
- ret = cumsum(randn(n) .* 0.005)
19
- c = 100.0 .* exp.(ret)
20
- h = c .* (1.0 .+ abs.(randn(n)) .* 0.005)
21
- l = c .* (1.0 .- abs.(randn(n)) .* 0.005)
22
- o = c .* (1.0 .+ randn(n) .* 0.002)
23
- v = abs.(randn(n)) .* 2000.0 .+ 1000.0
24
-
25
- # ── Warm up all indicators ────────────────────────────
26
- _ = sma(c, 20); println(" sma βœ“")
27
- _ = ema(c, 20); println(" ema βœ“")
28
- _ = rsi(c, 14); println(" rsi βœ“")
29
- _ = macd(c); println(" macd βœ“")
30
- _ = atr(h, l, c, 14); println(" atr βœ“")
31
- _ = bbands(c, 20, 2.0); println(" bbands βœ“")
32
- _ = donchian(h, l, 20); println(" donchian βœ“")
33
- _ = adx(h, l, c, 14); println(" adx βœ“")
34
- _ = rsi(c, 14); println(" rsi βœ“")
35
- _ = stoch(h, l, c); println(" stoch βœ“")
36
- _ = zscore(c, 20); println(" zscore βœ“")
37
- _ = obv(c, v); println(" obv βœ“")
38
- println("All indicators warmed βœ“")
39
-
40
- # ── Warm up backtest engine ───────────────────────────
41
- signals = [i > 50 ? (c[i] > sma(c, 20)[i] ? 1 : -1) : 0 for i in 1:n]
42
- signals = [isnan(sma(c,20)[i]) ? 0 : signals[i] for i in 1:n]
43
- sma20 = sma(c, 20)
44
- signals_v = [isnan(sma20[i]) ? 0 : (c[i] > sma20[i] ? 1 : -1) for i in 1:n]
45
-
46
- cfg = BacktestConfig()
47
- result = run_backtest(o, h, l, c, v, signals_v, "1h", cfg)
48
- println("BacktestEngine warmed βœ“ ($(result.n_trades) trades)")
49
-
50
- # ── Warm up SignalCompiler ────────────────────────────
51
- test_code = """
52
- function get_param_grid() :: Dict{String, Vector{Float64}}
53
- return Dict("period" => [10.0, 20.0, 30.0])
54
- end
55
-
56
- function generate_signals(open_p, high, low, close, volume, params)
57
- n = length(close)
58
- p = Int(round(get(params, "period", 20.0)))
59
- ma = sma(close, p)
60
- signals = zeros(Int, n)
61
- for i in (p+1):n
62
- isnan(ma[i]) && continue
63
- signals[i] = close[i] > ma[i] ? 1 : -1
64
- end
65
- return signals
66
- end
67
- """
68
- compiled = compile_strategy("WarmupTest", test_code)
69
- if compiled.is_valid
70
- println("SignalCompiler warmed βœ“")
71
- else
72
- println("SignalCompiler warning: $(compiled.error)")
73
- end
74
-
75
- # ── Warm up optimizer (mini run) ─────────────────────
76
- opt = walk_forward_optimize(
77
- compiled.generate_fn,
78
- compiled.param_grid_fn(),
79
- o, h, l, c, v,
80
- "1h", "WarmupTest", "TEST";
81
- n_windows = 2,
82
- max_combos = 3,
83
- min_trades = 1,
84
- )
85
- println("Optimizer warmed βœ“ (viable=$(opt.is_viable))")
86
-
87
- println("\nβœ… All Julia hot paths precompiled. Ready for production requests.")