# Headless Oracle — DataCamp Workspace Integration Use Headless Oracle in a DataCamp Workspace (Jupyter) notebook to gate financial analysis on cryptographically verified market state. Every cell that touches live market data should call `safe_market_check()` first — if the market is not OPEN, the analysis halts automatically. ## Setup Run this cell once at the top of your workspace: ```python # Cell 1 — Install SDK !pip install headless-oracle ``` ```python # Cell 2 — Configuration import os # Set your Oracle API key. # In DataCamp Workspaces: Environment → Secrets → add ORACLE_KEY # Locally: export ORACLE_KEY=your_key_here ORACLE_KEY = os.environ["ORACLE_KEY"] ORACLE_BASE = "https://headlessoracle.com" ``` ## safe_market_check() Pattern ```python # Cell 3 — Market safety gate from headless_oracle import OracleClient, verify import pandas as pd from datetime import datetime, timezone client = OracleClient(api_key=ORACLE_KEY) def safe_market_check(mic: str = "XNYS") -> dict: """ Fetch and verify a signed market receipt from Headless Oracle. Returns a dict with: - safe_to_trade (bool): True only when status is OPEN and signature is valid - status (str): OPEN | CLOSED | HALTED | UNKNOWN - mic (str): exchange MIC code - expires_at (str | None): ISO 8601 UTC expiry of this receipt - reason (str): human-readable explanation UNKNOWN means the Oracle's signing infrastructure returned an unverifiable state. Treat UNKNOWN as CLOSED — do not proceed with analysis that depends on live data. """ try: receipt = client.status(mic=mic) result = verify(receipt) if not result["valid"]: return { "safe_to_trade": False, "status": "UNKNOWN", "mic": mic, "expires_at": None, "reason": f"Signature invalid: {result['reason']}", } is_open = receipt.get("status") == "OPEN" return { "safe_to_trade": is_open, "status": receipt.get("status", "UNKNOWN"), "mic": mic, "expires_at": receipt.get("expires_at"), "reason": "Verified OPEN." if is_open else f"Market is {receipt.get('status')} — halting analysis.", } except Exception as exc: return { "safe_to_trade": False, "status": "UNKNOWN", "mic": mic, "expires_at": None, "reason": f"Oracle error: {exc}", } ``` ## Full Notebook Cell Sequence — Safe Market Analysis ```python # Cell 4 — Run safety check before any live-data analysis gate = safe_market_check("XNYS") print(f"[{gate['mic']}] {gate['status']} — safe_to_trade={gate['safe_to_trade']}") print(f" Reason : {gate['reason']}") print(f" Expires : {gate['expires_at']}") if not gate["safe_to_trade"]: raise SystemExit(f"Market gate failed: {gate['reason']}. Analysis halted.") ``` ```python # Cell 5 — Build a summary DataFrame (only reached when market is OPEN) # Replace the data source below with your own: yfinance, DataCamp datasets, CSV, etc. import yfinance as yf # or any data source you use in DataCamp tickers = ["AAPL", "MSFT", "GOOGL"] data = yf.download(tickers, period="5d", interval="1d", auto_adjust=True)["Close"] summary = pd.DataFrame({ "ticker": tickers, "last_close": [data[t].iloc[-1] for t in tickers], "5d_change": [(data[t].iloc[-1] / data[t].iloc[0] - 1) * 100 for t in tickers], "oracle_verified_at": gate["expires_at"], }) summary ``` ```python # Cell 6 — Multi-exchange batch check (optional) # Check all supported markets at once before a multi-region analysis (23 available — pick yours) mics = ["XNYS", "XNAS", "XLON", "XJPX", "XPAR", "XHKG", "XSES"] rows = [] for mic in mics: g = safe_market_check(mic) rows.append(g) status_df = pd.DataFrame(rows)[["mic", "status", "safe_to_trade", "reason", "expires_at"]] print(status_df.to_string(index=False)) # Halt if any exchange you need is not OPEN required = {"XNYS", "XLON"} unsafe = {r["mic"] for r in rows if r["mic"] in required and not r["safe_to_trade"]} if unsafe: raise SystemExit(f"Required exchanges not OPEN: {unsafe}. Analysis halted.") ``` ## Important - **Always run `safe_market_check()` before cells that fetch or act on live prices.** Market data fetched outside trading hours may be stale, delayed, or from a prior session. - **The receipt expires in 60 seconds.** Do not cache the result across cells; call `safe_market_check()` at each decision point in a long-running notebook. - **UNKNOWN is not a soft signal.** An UNKNOWN status means the Oracle could not produce a cryptographically verified receipt. Treat it as CLOSED and halt the cell. - **Use `raise SystemExit(...)`** rather than a conditional skip — it stops all subsequent cells from running automatically, which is the correct fail-closed behaviour in a notebook. ## Links - Python SDK: `pip install headless-oracle` — [PyPI](https://pypi.org/project/headless-oracle/) - API docs: https://headlessoracle.com/docs - Supported exchanges: https://headlessoracle.com/v5/exchanges - Get a free API key: https://headlessoracle.com/v5/keys/request