This commit is contained in:
wvr committed 2026-11-20 03:43:46 -06:00
1 parent 15aa6397e8
commit 28bfd7ea81
7 files changed
+4144 -25

No files matched your search

Binary file not shown.
BIN
View File
Binary file not shown.
+3914
View File
File diff suppressed because it is too large. Load diff
+146 -25
View File
@@ -1,5 +1,5 @@
//@version=6 //@version=6
// Bracket Morning Panel: all direction rules plus ATR sizing in one indicator (4 NQ / 3 gold / 2 crude / 1 NG accounts). // Bracket Morning Panel: all direction rules plus ATR sizing in one indicator (evaluations: 3 NQ / 3 gold / 2 crude / 1 NG / 1 euro).
// Gold (entry 8:21): silver % move minus gold % move from the 6:00 pm reopen to 8:19. // Gold (entry 8:21): silver % move minus gold % move from the 6:00 pm reopen to 8:19.
// Gap above the threshold -> LONG, otherwise SHORT. // Gap above the threshold -> LONG, otherwise SHORT.
// Crude (entry 9:01): yesterday's 2:30 pm settlement vs yesterday's 9:00 candle close. // Crude (entry 9:01): yesterday's 2:30 pm settlement vs yesterday's 9:00 candle close.
@@ -7,15 +7,26 @@
// NG (entry 6:01 pm, at the evening reopen, for the NEXT trading day): always the SAME side as crude // NG (entry 6:01 pm, at the evening reopen, for the NEXT trading day): always the SAME side as crude
// (energy group: opposite sides would be hedging). Crude's side for that day is already set by the 2:30 pm // (energy group: opposite sides would be hedging). Crude's side for that day is already set by the 2:30 pm
// settlement, so the panel shows it from 6:00 pm. Hold to the usual 4:40 pm exit next day. // settlement, so the panel shows it from 6:00 pm. Hold to the usual 4:40 pm exit next day.
// NQ (entry 9:31): today's 9:30 candle close vs yesterday's 4:00 pm close (3:59 candle). // NQ News check first (8:31): news day = 8:30 candle volume >= 4.4x the average of the 8:15-8:29 candles.
// Above -> SHORT, below -> LONG. // News day: the 8:30 candle gets the same tests as the 9:30 one (first match wins):
// a. Displacement (8:31): body >= 30% of the 8:30 candle's range, wick against <= 15% -> follow the candle.
// b. Drive (8:33): 8:29 close -> 8:32 close move >= 5% of daily ATR(14), given back <= 25% from the 8:30-8:32
// extreme -> follow the move. c. Three candles (8:33): 8:30, 8:31, 8:32 all close the same way -> follow.
// If none of a-c fires, trade the normal-day rule below.
// Normal day (entry 9:31 or 9:33), first match wins:
// 1. Displacement (9:31): the 9:30 candle has body >= 30% of its range and the wick against it <= 15%
// of the range -> follow the candle (green -> LONG, red -> SHORT).
// 2. Drive (9:33): the move from the 9:29 close to the 9:32 close is >= 5% of daily ATR(14) and price has
// given back <= 25% of the move from the 9:30-9:32 extreme -> follow the move.
// 3. Three candles (9:33): the 9:30, 9:31 and 9:32 candles all close the same way -> follow them.
// 4. Otherwise (9:33): the old rule. 9:30 close vs yesterday's 4:00 pm close: above -> SHORT, below -> LONG.
// Sizing: contracts = round(stop $ / ($ per point x 0.20 x daily ATR(14))), min 1, max 4; // Sizing: contracts = round(stop $ / ($ per point x 0.20 x daily ATR(14))), min 1, max 4;
// stop pts = (stop $ - $20 x contracts) / (contracts x $ per point); target pts = (target $ + commission x contracts) / (contracts x $ per point). // stop pts = (stop $ - $20 x contracts) / (contracts x $ per point); target pts = (target $ + commission x contracts) / (contracts x $ per point).
// Works on any chart timeframe (1 min, 5 min, 1 hour...): every signal is computed from 1-minute data of each contract. // Works on any chart timeframe (1 min, 5 min, 1 hour...): every signal is computed from 1-minute data of each contract.
// Continuous "1!" symbols are fine (roll days change the NQ side about once a year and a few gold signals a year). // Continuous "1!" symbols are fine (roll days change the NQ side about once a year and a few gold signals a year).
// Exact months (e.g. NQZ2026) avoid even that, if you prefer. // Exact months (e.g. NQZ2026) avoid even that, if you prefer.
// Skip US market holidays and early-close days. The Bracket Tracker remains the source for each account's own stop/target $. // Skip US market holidays and early-close days. The Bracket Tracker remains the source for each account's own stop/target $.
// Signals lock the moment the decision candle has closed (gold: 8:19 candle -> shown from 8:20; NQ: 9:30 candle -> from 9:31), // Signals lock the moment the decision candle has closed (gold: 8:19 candle -> shown from 8:20; NQ: the 8:30 / 9:30 candle -> from 8:31 / 9:31, else the 8:32 / 9:32 candle -> from 8:33 / 9:33),
// using that candle's final close, so they never flicker. Until then the side shows "waiting". // using that candle's final close, so they never flicker. Until then the side shows "waiting".
// Set alerts to "Once Per Bar" so they fire the moment the side is known (with "Once Per Bar Close" a 5-minute chart alerts up to 5 minutes late). // Set alerts to "Once Per Bar" so they fire the moment the side is known (with "Once Per Bar Close" a 5-minute chart alerts up to 5 minutes late).
indicator("Bracket Morning Panel", overlay = false) // own pane below the chart, so the table never covers price indicator("Bracket Morning Panel", overlay = false) // own pane below the chart, so the table never covers price
@@ -29,10 +40,12 @@ nqSym = input.symbol("CME_MINI:NQ1!", "NQ", group = grpC, display = display.none
ngSym = input.symbol("NYMEX:NG1!", "Natural gas", group = grpC, display = display.none) ngSym = input.symbol("NYMEX:NG1!", "Natural gas", group = grpC, display = display.none)
grpG = "Gold gap threshold" grpG = "Gold gap threshold"
thrInput = input.float(1.03, "Fallback threshold (%)", step = 0.01, group = grpG, tooltip = "Used until enough days are loaded for the live median. Update monthly.", display = display.none) thrInput = input.float(0.99, "Fallback threshold (%)", step = 0.01, group = grpG, tooltip = "Used until enough days are loaded for the live median. Update monthly.", display = display.none)
lookback = input.int(250, "Median lookback (trading days)", minval = 20, group = grpG, display = display.none) lookback = input.int(250, "Median lookback (trading days)", minval = 20, group = grpG, display = display.none)
minDays = input.int(60, "Days before using the live median", minval = 10, group = grpG, display = display.none) minDays = input.int(60, "Days before using the live median", minval = 10, group = grpG, display = display.none)
newsThr = input.float(4.4, "NQ news day: 8:30 volume vs 8:15-8:29 average (x)", step = 0.1, display = display.none)
grpS = "Sizing (defaults = fresh evaluation, daily loss limit OFF)" grpS = "Sizing (defaults = fresh evaluation, daily loss limit OFF)"
stopUsd = input.float(2000, "Stop $", step = 50, group = grpS, tooltip = "Fresh evaluation: 2000 with the daily loss limit OFF (all the room), 1200 with it ON.", display = display.none) stopUsd = input.float(2000, "Stop $", step = 50, group = grpS, tooltip = "Fresh evaluation: 2000 with the daily loss limit OFF (all the room), 1200 with it ON.", display = display.none)
targetUsd = input.float(3000, "Target $", step = 50, group = grpS, display = display.none) targetUsd = input.float(3000, "Target $", step = 50, group = grpS, display = display.none)
@@ -58,22 +71,91 @@ goldMove() =>
m819 := close[1] / o - 1.0 m819 := close[1] / o - 1.0
[m819, close / o - 1.0] // [move to the 8:19 close (locked), move so far (live)] [m819, close / o - 1.0] // [move to the 8:19 close (locked), move so far (live)]
mins(t) => hour(t, tz) * 60 + minute(t, tz)
// One opening window: open candle at minute o (minutes after midnight ET), pre candle o-1, entries o+1 / o+3.
openWindow(int o) =>
tc = mins(time_close)
var float pre = na
var float c1 = na // open candle close
var float c3 = na // close of the third candle (o+2)
var float hiX = na // highest high / lowest low of the three candles
var float loX = na
var int disp = 0
var int d1 = 0
var int d2 = 0
var int three = 0
var bool done1 = false
var bool done3 = false
if timeframe.change("D")
pre := na
c1 := na
c3 := na
hiX := na
loX := na
disp := 0
d1 := 0
d2 := 0
three := 0
done1 := false
done3 := false
if tc == o + 1 // open candle forming: close[1] is the final pre-candle close
pre := close[1]
if tc == o + 2 and not na(pre) // [1] is the final open candle
op = open[1]
h = high[1]
l = low[1]
c = close[1]
r = h - l
c1 := c
hiX := h
loX := l
d1 := int(math.sign(c - op))
if r > 0 and c != op
sd = c > op ? 1 : -1
wa = sd > 0 ? (op - l) / r : (h - op) / r
disp := math.abs(c - op) / r >= 0.30 and wa <= 0.15 ? sd : 0
done1 := true
if tc == o + 3 and done1 // [1] is the final second candle
hiX := math.max(hiX, high[1])
loX := math.min(loX, low[1])
d2 := int(math.sign(close[1] - open[1]))
if tc == o + 4 and done1 // [1] is the final third candle
hiX := math.max(hiX, high[1])
loX := math.min(loX, low[1])
c3 := close[1]
d3 = int(math.sign(close[1] - open[1]))
three := d1 != 0 and d1 == d2 and d1 == d3 ? d1 : 0
done3 := true
[done1, done3, disp, three, pre, c1, c3, hiX, loX]
nqSignal() => nqSignal() =>
var float c16 = na var float c16 = na // yesterday's 4:00 pm close (3:59 candle)
var float ref = na var float ref = na // c16 as used today
var float px = na var int cur = 0 // old rule's side
var int dir = 0 var float ratio = na // 8:30 candle volume / average 8:15-8:29 volume
var bool newsDone = false
if timeframe.change("D") if timeframe.change("D")
dir := 0
ref := na ref := na
px := na cur := 0
if endsAt(9, 32) and not na(c16) // 9:31 candle: close[1] is the final close of the 9:30 candle ratio := na
newsDone := false
if mins(time_close) == 512 // 8:31 candle forming: [1] is the final 8:30 candle
base = 0.0
for i = 2 to 25
m = mins(time[i])
if m >= 495 and m <= 509 // candles 8:15-8:29
base += volume[i]
ratio := base > 0 ? volume[1] / (base / 15) : na
newsDone := true
[a1, a3, aDisp, aThree, aPre, aC1, aC3, aHi, aLo] = openWindow(510) // 8:30
[b1, b3, bDisp, bThree, bPre, bC1, bC3, bHi, bLo] = openWindow(570) // 9:30
if mins(time_close) == 572 and not na(c16) // 9:31 candle forming: [1] is the final 9:30 candle
ref := c16 ref := c16
px := close[1] cur := close[1] > c16 ? -1 : 1
dir := close[1] > c16 ? -1 : 1
if endsAt(16, 1) // 4:00 candle: close[1] is the final 3:59 close (today's 4:00 pm close, used tomorrow) if endsAt(16, 1) // 4:00 candle: close[1] is the final 3:59 close (today's 4:00 pm close, used tomorrow)
c16 := close[1] c16 := close[1]
[dir, ref, px] [newsDone, ratio, a1, a3, aDisp, aThree, aPre, aC3, aHi, aLo, b1, b3, bDisp, bThree, bPre, bC1, bC3, bHi, bLo, cur, ref]
clSignal() => clSignal() =>
var float c901 = na var float c901 = na
@@ -104,10 +186,17 @@ sizeFor(atrD, pv, mt, comm) =>
tp = math.ceil((targetUsd + comm * n) / (n * pv) / mt - 1e-6) * mt tp = math.ceil((targetUsd + comm * n) / (n * pv) / mt - 1e-6) * mt
[n, sp, tp, sp * n * pv, tp * n * pv] // last two: what to type as Risk USD / Reward USD (whole position) [n, sp, tp, sp * n * pv, tp * n * pv] // last two: what to type as Risk USD / Reward USD (whole position)
// ---------- display helpers ----------
sideText(d) => d == 1 ? "LONG" : d == -1 ? "SHORT" : "waiting"
sideColor(d) => d == 1 ? color.lime : d == -1 ? color.new(#ff5252, 0) : color.silver
num(x) => na(x) ? "-" : str.tostring(x, "#.##")
pts(x) => na(x) ? "-" : str.tostring(x, "#.####") // prices/points: enough decimals for NG (0.001 tick)
usd(x) => na(x) ? "-" : "$" + str.tostring(x, "#,##0.00")
// ---------- data ---------- // ---------- data ----------
[g819, gLive] = request.security(gcSym, "1", goldMove()) [g819, gLive] = request.security(gcSym, "1", goldMove())
[s819, sLive] = request.security(siSym, "1", goldMove()) [s819, sLive] = request.security(siSym, "1", goldMove())
[nqDir, nqRef, nqPx] = request.security(nqSym, "1", nqSignal()) [nwDone, nwRatio, a1, a3, aDisp, aThree, aPre, aC3, aHi, aLo, nqDone1, nqDone3, nqDisp, nqThree, nqPre, nqPx, nqC932, nqHi, nqLo, nqCur, nqRef] = request.security(nqSym, "1", nqSignal())
[clDir, clOpen, clSettle, clEntryNow, ngEntryNow] = request.security(clSym, "1", clSignal()) [clDir, clOpen, clSettle, clEntryNow, ngEntryNow] = request.security(clSym, "1", clSignal())
[gcAtr, gcPv, gcMt] = request.security(gcSym, "D", dailyInfo(), lookahead = barmerge.lookahead_on) [gcAtr, gcPv, gcMt] = request.security(gcSym, "D", dailyInfo(), lookahead = barmerge.lookahead_on)
@@ -141,6 +230,42 @@ if not goldDone and not na(gap819)
if hist.size() > lookback if hist.size() > lookback
hist.shift() hist.shift()
// ---------- NQ decision ----------
driveOf(done3, pre, c3, hi, lo, atrD) =>
mv = c3 - pre
sg = nz(math.sign(mv))
ext = sg > 0 ? hi : lo
pull = (ext - c3) * sg
dr = done3 and sg != 0 and math.abs(mv) >= 0.05 * atrD and pull <= 0.25 * math.abs(ext - pre) ? int(sg) : 0
[dr, mv, pull]
// normal-day rule (9:30 window)
[nqDrive, nqMv, nqPull] = driveOf(nqDone3, nqPre, nqC932, nqHi, nqLo, nqAtr)
hDir = not nqDone1 ? 0 : nqDisp != 0 ? nqDisp : not nqDone3 ? 0 : nqDrive != 0 ? nqDrive : nqThree != 0 ? nqThree : nqCur
hBranch = not nqDone1 ? "waiting for the 9:30 candle" : nqDisp != 0 ? "1. displacement 9:30 candle -> follow" :
not nqDone3 ? "no 9:30 displacement; waiting for the 9:32 candle" :
nqDrive != 0 ? "2. drive " + num(nqMv) + " pts from 9:29 (min " + num(0.05 * nqAtr) + "), gave back " + num(nqPull) + " -> follow" :
nqThree != 0 ? "3. three candles same way -> follow" :
"4. old rule: 9:30 close " + num(nqPx) + " vs prior 4:00 close " + num(nqRef)
hEntry = nqDisp != 0 ? "9:31" : nqDone1 ? "9:33" : "9:31 / 9:33"
// news day (8:30 window)
news = nwDone and not na(nwRatio) and nwRatio >= newsThr
[aDrive, aMv, aPull] = driveOf(a3, aPre, aC3, aHi, aLo, nqAtr)
newsSig = aDisp != 0 ? aDisp : not a3 ? 0 : aDrive != 0 ? aDrive : aThree
newsWait = news and aDisp == 0 and not a3 // 8:31-8:32: waiting for the 8:32 candle
newsTrade = news and newsSig != 0
pending = not nwDone and not nqDone1 // before 8:31 (no 8:30 data -> treated as a normal day at 9:31)
nqDir = pending or newsWait ? 0 : newsTrade ? newsSig : hDir
tag = not nwDone ? "" : (news ? "NEWS DAY" : "normal day") + " (8:30 volume " + num(nwRatio) + "x vs " + num(newsThr) + "x): "
nqBranch = pending ? "waiting for the 8:30 candle (news check at 8:31)" :
newsWait ? tag + "no 8:30 displacement; waiting for the 8:32 candle" :
newsTrade ? tag + (aDisp != 0 ? "a. 8:30 displacement -> follow" :
aDrive != 0 ? "b. 8:30 drive " + num(aMv) + " pts from 8:29 (min " + num(0.05 * nqAtr) + "), gave back " + num(aPull) + " -> follow" :
"c. 8:30 three candles same way -> follow") :
tag + (news ? "no 8:30 signal -> normal rule: " : "") + hBranch
nqEntry = pending ? "8:31 / 8:33 / 9:31 / 9:33" : newsWait ? "8:33 (or 9:31 / 9:33)" : newsTrade ? (aDisp != 0 ? "8:31" : "8:33") : hEntry
// ---------- sizing ---------- // ---------- sizing ----------
[gcN, gcSp, gcTp, gcRiskUsd, gcRewUsd] = sizeFor(gcAtr, gcPv, gcMt, gcComm) [gcN, gcSp, gcTp, gcRiskUsd, gcRewUsd] = sizeFor(gcAtr, gcPv, gcMt, gcComm)
[clN, clSp, clTp, clRiskUsd, clRewUsd] = sizeFor(clAtr, clPv, clMt, clComm) [clN, clSp, clTp, clRiskUsd, clRewUsd] = sizeFor(clAtr, clPv, clMt, clComm)
@@ -148,11 +273,6 @@ if not goldDone and not na(gap819)
[ngN, ngSp, ngTp, ngRiskUsd, ngRewUsd] = sizeFor(ngAtr, ngPv, ngMt, ngComm) [ngN, ngSp, ngTp, ngRiskUsd, ngRewUsd] = sizeFor(ngAtr, ngPv, ngMt, ngComm)
// ---------- display ---------- // ---------- display ----------
sideText(d) => d == 1 ? "LONG" : d == -1 ? "SHORT" : "waiting"
sideColor(d) => d == 1 ? color.lime : d == -1 ? color.new(#ff5252, 0) : color.silver
num(x) => na(x) ? "-" : str.tostring(x, "#.##")
pts(x) => na(x) ? "-" : str.tostring(x, "#.####") // prices/points: enough decimals for NG (0.001 tick)
usd(x) => na(x) ? "-" : "$" + str.tostring(x, "#,##0.00")
var table t = table.new(position.top_right, 10, 6, bgcolor = color.new(color.black, 15), border_width = 1) var table t = table.new(position.top_right, 10, 6, bgcolor = color.new(color.black, 15), border_width = 1)
if barstate.islast if barstate.islast
@@ -194,9 +314,9 @@ if barstate.islast
table.cell(t, 9, 3, pts(ngTp), text_color = color.new(color.lime, 40)) table.cell(t, 9, 3, pts(ngTp), text_color = color.new(color.lime, 40))
table.cell(t, 0, 4, "NQ", text_color = color.white) table.cell(t, 0, 4, "NQ", text_color = color.white)
table.cell(t, 1, 4, "9:31", text_color = color.white) table.cell(t, 1, 4, nqEntry, text_color = color.white)
table.cell(t, 2, 4, sideText(nqDir), text_color = sideColor(nqDir)) table.cell(t, 2, 4, sideText(nqDir), text_color = sideColor(nqDir))
table.cell(t, 3, 4, "9:30 close " + num(nqPx) + " vs prior 4:00 close " + num(nqRef), text_color = color.white) table.cell(t, 3, 4, nqBranch, text_color = color.white)
table.cell(t, 4, 4, num(nqAtr), text_color = color.white) table.cell(t, 4, 4, num(nqAtr), text_color = color.white)
table.cell(t, 5, 4, num(nqN), text_color = color.white) table.cell(t, 5, 4, num(nqN), text_color = color.white)
table.cell(t, 6, 4, usd(nqRiskUsd), text_color = color.red) table.cell(t, 6, 4, usd(nqRiskUsd), text_color = color.red)
@@ -217,5 +337,6 @@ alertcondition(clEntryNow and clDir == 1, "Crude LONG", "Crude bracket LONG at
alertcondition(clEntryNow and clDir == -1, "Crude SHORT", "Crude bracket SHORT at 9:01 ET") alertcondition(clEntryNow and clDir == -1, "Crude SHORT", "Crude bracket SHORT at 9:01 ET")
alertcondition(ngEntryNow and clDir == 1, "Nat gas LONG", "Nat gas bracket LONG at 6:01 pm ET for the next trading day (same side as crude)") alertcondition(ngEntryNow and clDir == 1, "Nat gas LONG", "Nat gas bracket LONG at 6:01 pm ET for the next trading day (same side as crude)")
alertcondition(ngEntryNow and clDir == -1, "Nat gas SHORT", "Nat gas bracket SHORT at 6:01 pm ET for the next trading day (same side as crude)") alertcondition(ngEntryNow and clDir == -1, "Nat gas SHORT", "Nat gas bracket SHORT at 6:01 pm ET for the next trading day (same side as crude)")
alertcondition(nqNew and nqDir == 1, "NQ LONG", "NQ bracket LONG at 9:31 ET") alertcondition(news and not news[1], "NQ news day", "NQ news day: 8:30 signal check (entry 8:31 / 8:33, else the normal 9:31 / 9:33 rule)")
alertcondition(nqNew and nqDir == -1, "NQ SHORT", "NQ bracket SHORT at 9:31 ET") alertcondition(nqNew and nqDir == 1, "NQ LONG", "NQ bracket LONG now")
alertcondition(nqNew and nqDir == -1, "NQ SHORT", "NQ bracket SHORT now")
@@ -0,0 +1,31 @@
Direction prediction in general
Christoffersen & Diebold (2006), Management Science, the key theory paper.
Volatility dependence produces sign dependence, so long as expected returns are nonzero.
nber
The standard finding of little or no conditional mean dependence is entirely consistent with a significant degree of sign dependence. In other words, direction can be predictable even when the size of the move isn’t.
nber
Caveat: they find sign dependence is not likely to be found in very high-frequency (e.g., daily) or very low-frequency (e.g., annual) returns; instead, it is more likely to be found at intermediate return horizons. Our one-day bracket sits at the hard end, which fits the 52–54% accuracy we see.
repec
Leung, Daouk & Chen (2000), International Journal of Forecasting. This is the “direction, not size” argument made formally. They start from the notion that a prediction with little forecast error does not necessarily translate into capital gain, and find the group of classification models performs significantly better than models that forecast price levels.
bohrium
bohrium
Pesaran & Timmermann (1992) gave the standard statistical test for whether directional accuracy beats chance. It’s useful if we ever want a formal check on the live hit rates.
Outcomes defined like our bracket
López de Prado, Advances in Financial Machine Learning (2018), “triple-barrier” labeling. This is almost exactly how we score trades: if the upper barrier is touched first, we mark the observation as 1. If the lower barrier is touched first, we mark the observation as -1. If the vertical barrier is touched first, it is marked as 0. Upper and lower barriers are our target and stop; the time barrier is our 4:40 exit.
arxiv
His companion idea, “meta-labeling”, builds a second model that evaluates whether each signal is likely to be profitable. That’s the trade-or-skip question, which our filter tests covered.
mql5
Intraday direction effects in futures (the research closest to our results)
Gao, Han, Li & Zhou (2018), Journal of Financial Economics. The first half-hour return on the market as measured from the previous day’s market close predicts the last half-hour return. It’s stronger on more volatile days, on higher volume days, on recession days, and on major macroeconomic news release days.
wustl
repec
Baltussen, Da, Lammers & Martens (2021), Journal of Financial Economics. Using intraday returns on over 60 futures on equities, bonds, commodities, and currencies between 1974 and 2020, we find strong market intraday momentum everywhere. Their explanation: hedging short gamma exposure requires trading in the direction of price movements, thereby creating price momentum, driven by options market makers and leveraged ETFs.
repec
eur
Lou, Polk & Skouras (2019), Journal of Financial Economics, “A Tug of War”. Overnight and intraday returns behave differently and tend to offset each other. That’s the family our old NQ rule (fade the gap at the open) belongs to.
+47
View File
@@ -0,0 +1,47 @@
#!/usr/bin/env python3
"""Price check (free, downloads nothing): CME options-on-futures data needed to estimate dealer gamma.
Two schemas per product: 'statistics' (daily open interest + settlement prices) and 'definition'
(strike, expiry, call/put of every option). Same API key setup as get_futures_1m.py.
export DATABENTO_API_KEY=db-xxxxxxxxxxxxxxxx
python3 options_cost.py # NQ, ES, gold, crude options, 2016 -> latest
python3 options_cost.py --parents NQ.OPT --start 2020-01-01
"""
import argparse, os, sys
import databento as db
import pandas as pd
DATASET = "GLBX.MDP3"
# CME option product codes: NQ / ES equity index options, OG = gold (COMEX), LO = crude (NYMEX)
DEFAULT = ["NQ.OPT", "ES.OPT", "OG.OPT", "LO.OPT"]
p = argparse.ArgumentParser()
p.add_argument("--parents", nargs="+", default=DEFAULT)
p.add_argument("--schemas", nargs="+", default=["statistics", "definition"])
p.add_argument("--start", default="2016-01-01")
p.add_argument("--end", default=None)
a = p.parse_args()
key = os.environ.get("DATABENTO_API_KEY")
if not key:
sys.exit("Set DATABENTO_API_KEY first.")
client = db.Historical(key)
end = a.end
if end is None:
rng = client.metadata.get_dataset_range(dataset=DATASET)
end = rng["end"]
end = pd.Timestamp(end); end = end.tz_localize("UTC") if end.tzinfo is None else end.tz_convert("UTC")
start = pd.Timestamp(a.start, tz="UTC")
print(f"Range {start.date()} -> {end.date()} (cost estimates only, nothing is downloaded or billed)\n")
grand = 0.0
for par in a.parents:
for sch in a.schemas:
params = dict(dataset=DATASET, schema=sch, stype_in="parent", symbols=[par], start=start.isoformat(), end=end.isoformat())
try:
cost = client.metadata.get_cost(**params)
size = client.metadata.get_billable_size(**params)
n = client.metadata.get_record_count(**params)
grand += cost
print(f"{par:8s} {sch:11s} ${cost:9.2f} {size / 1e9:7.2f} GB {n:,} records")
except Exception as e:
print(f"{par:8s} {sch:11s} error: {e}")
print(f"\nTotal estimate: ${grand:,.2f}")
+6
View File
@@ -0,0 +1,6 @@
#!/bin/sh
apk install python3-zstd
pip3 install --user --break-system-packages databento