text
stringlengths
185
73.3k
repo
stringlengths
7
100
path
stringlengths
4
146
language
stringclasses
7 values
hash
stringlengths
16
16
score
float64
7
8.5
stars
int64
0
237k
"""Cliente da Web API do qBittorrent (v2).""" import re import httpx import config class QbitError(Exception): pass def _hash_from_magnet(magnet: str) -> str | None: """Extrai o infohash de um magnet (xt=urn:btih:...). None se não achar.""" m = re.search(r"xt=urn:btih:([0-9a-zA-Z]+)", magnet or "") ...
ezenere/Outstasher
services/qbittorrent.py
.py
f3745fd795f57b61
7.6
15
"""Estágio 2: alinhamento monotônico com penalidade de gap afim (banda). Needleman-Wunsch SEMI-GLOBAL (gaps livres nas pontas — recap no começo e créditos no fim são a norma) com gap afim: abrir custa caro (OPEN), estender custa quase nada (EXTEND). É o que faz o DP preferir UM gap de 400 frames (cena removida) a 400 ...
ezenere/Outstasher
services/series/align/dp.py
.py
5d538ade117d3da5
7.6
15
"""Nomes de pasta/arquivo de séries no layout padrão do Jellyfin/Plex: Série (Ano) [tmdbid-N]/Season 01/Série (Ano) S01E02 [pt+orig].mkv Mesmo esquema de tag [tmdbid-N] dos filmes (services/catalog.py) — o scanner do catálogo e o Jellyfin usam a mesma convenção nas duas mídias. """ from services import catalog ...
ezenere/Outstasher
services/series/naming.py
.py
fedd384c7bbc153b
7.6
15
"""Parsing de nomes de release de TV: episódios, packs e sinais de suspeita. Tudo aqui é função pura sobre o TÍTULO do torrent (mais metadados opcionais do TMDB/Jackett) — nada de rede ou estado. O selector de séries e o gate de torrents incompatíveis são construídos em cima destas primitivas. """ import re from datac...
ezenere/Outstasher
services/series/parse.py
.py
03930dcaa7d3f5db
7.6
15
"""Rebusca de correspondências entre episódios DESALINHADOS. Quando o alinhamento por conteúdo conclui que um par não tem quase nada em comum ("conflito de alinhamento"), o sintoma clássico é ordem de episódios trocada entre as duas versões: cada arquivo é de um episódio real, só que casado com o parceiro errado. Com ...
ezenere/Outstasher
services/series/rematch.py
.py
f6959cd2622aa10c
7.6
15
"""Configuração compartilhada da suíte (pytest). Filosofia: os testes rodam no AMBIENTE COMPLETO da aplicação — o mesmo onde o servidor roda (numpy, httpx, python-dotenv, fastapi instalados e ffmpeg/ffprobe no PATH). Nada é stubado. Se um requisito faltar, a coleção é ABORTADA com uma mensagem explicando o que instala...
ezenere/Outstasher
tests/conftest.py
.py
0d4e64778298b3b4
8.1
15
""" Walk-Forward Backtest: Momentum Strategy 2020-2025 YTD Monthly rebalancing with 12-1 month momentum factor """ import pandas as pd import numpy as np from datetime import datetime, timedelta import sys import os sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) from...
PAT0216/paper-trader
scripts/backtests/momentum_backtest.py
.py
388c48453153cefb
8.02
10
""" Walk-Forward Backtest: Momentum Strategy 2016-2025 vs S&P 500 Monthly rebalancing with 12-1 month momentum factor """ import pandas as pd import numpy as np from datetime import datetime, timedelta import sys import os import json sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(...
PAT0216/paper-trader
scripts/backtests/momentum_vs_spy.py
.py
aecf288a1553c0a1
8.02
10
#!/usr/bin/env python3 """ Backtest Runner Script Executes backtesting over historical data and generates performance reports. Usage: python run_backtest.py [--start YYYY-MM-DD] [--end YYYY-MM-DD] [--output results/] """ import argparse import os import sys import yaml import pandas as pd from datetime import datetim...
PAT0216/paper-trader
scripts/backtests/run_backtest.py
.py
d5a49adeaab16300
8.02
10
#!/usr/bin/env python3 """ Walk-Forward Backtesting Script - FIXED VERSION True out-of-sample validation using proper Backtester infrastructure. Now includes Phase 7 risk controls for valid comparison. Process: Year 1: Train on 2010-2014, Test on 2015 (with risk controls) Year 2: Train on 2010-2015, Test on 2...
PAT0216/paper-trader
scripts/backtests/run_walkforward.py
.py
36c131282528e12f
8.02
10
#!/usr/bin/env python3 """ Production Simulation Script - Demonstrates 3-day trade flow WITHOUT modifying production data. This script: 1. Reads current ledger and snapshot state 2. Simulates what trades WOULD happen each day 3. Shows the expected ledger/snapshot updates 4. Generates proof output for each simulated da...
PAT0216/paper-trader
scripts/simulate_production.py
.py
815f2d267411255d
7.52
10
""" Backfill ledgers with walk-forward simulation from October 1st, 2025. """ import pandas as pd import numpy as np from datetime import datetime, timedelta import sys import os sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) from src.data.cache import DataCache # C...
PAT0216/paper-trader
scripts/utils/backfill_ledgers.py
.py
5142230918eecafd
7.52
10
""" Compute current portfolio values from ledger holdings and latest prices. Outputs a JSON snapshot for the dashboard to read. IMPORTANT: Portfolio values come from the ledger's PORTFOLIO,VALUE rows (the authoritative source), NOT from recalculating holdings × prices. Usage: python compute_portfolio_snapshot.py ...
PAT0216/paper-trader
scripts/utils/compute_portfolio_snapshot.py
.py
288205d68fc410da
7.52
10
""" Fetch Historical Fundamental Data via yfinance Fetches quarterly financials (income statement, balance sheet) from yfinance. Gets ~4-5 years of history which is enough for backtesting. Output: data/fundamentals_historical.csv """ import pandas as pd import yfinance as yf import os import time import json from da...
PAT0216/paper-trader
scripts/utils/fetch_fundamentals.py
.py
4df4136dd786a9c1
7.52
10
#!/usr/bin/env python3 """ Point-in-Time Backtest: Momentum Strategy Oct 1, 2025 - Dec 19, 2025 Monthly rebalancing with 12-1 month momentum factor + transaction costs """ import pandas as pd import numpy as np from datetime import datetime, timedelta import sys import os import json sys.path.insert(0, os.path.dirnam...
PAT0216/paper-trader
scripts/validation/pit_momentum_oct_dec.py
.py
30e522888ab738f2
7.52
10
""" Portfolio Comparison Analytics Compares multiple portfolios and calculates performance metrics. """ import pandas as pd import numpy as np from typing import Dict, List, Optional from dataclasses import dataclass from datetime import datetime import os @dataclass class PortfolioMetrics: """Performance metri...
PAT0216/paper-trader
src/analytics/portfolio_comparison.py
.py
7c6be400b5b42fa8
7.52
10
""" Transaction Cost Module for Backtesting Models realistic trading costs including slippage, commissions, and market impact. Uses retail-realistic assumptions based on modern discount brokerage environments. """ import numpy as np import pandas as pd from typing import Dict, Optional, Tuple from dataclasses import ...
PAT0216/paper-trader
src/backtesting/costs.py
.py
77181f1e1add510d
8.02
10
""" Performance Metrics Module for Backtesting Calculates professional-grade quant metrics including risk-adjusted returns, drawdown analysis, regime-based performance, and trade quality metrics. """ import numpy as np import pandas as pd from typing import Dict, Optional, Tuple, List from dataclasses import dataclas...
PAT0216/paper-trader
src/backtesting/performance.py
.py
64773fae2420014b
8.02
10
""" SQLite Data Cache for Paper Trader - Phase 4 Caches OHLCV and macro data locally to: 1. Avoid rate limits from yfinance 2. Enable fast backtesting 3. Support incremental daily updates Database: data/market.db Tables: price_data, macro_data, cache_metadata """ import sqlite3 import pandas as pd import os from dat...
PAT0216/paper-trader
src/data/cache.py
.py
e0bf02b15cf1e2b4
7.52
10
""" Data Loader for Paper Trader - Phase 4 Smart data loading with SQLite caching: 1. Check cache first 2. Fetch only new bars (incremental update) 3. Rate limit handling with retries 4. Graceful fallbacks """ import yfinance as yf import pandas as pd import time from datetime import datetime, timedelta from typing i...
PAT0216/paper-trader
src/data/loader.py
.py
d539e31def2ace64
7.52
10
""" Macro Data Module for Paper Trader - Phase 3.6 Fetches macroeconomic indicators from FRED (Federal Reserve Economic Data). These features provide market-wide context for individual stock predictions. Features: - VIX (fear index) for regime detection - Retry logic with exponential backoff - File-based caching (24-...
PAT0216/paper-trader
src/data/macro.py
.py
a54e2116fbfa4442
7.52
10
""" Price Utilities - Functions for fetching prices from the market database. Extracted from compute_portfolio_snapshot.py for reusability. """ import os import sqlite3 import pandas as pd from typing import Dict, List from datetime import datetime try: from zoneinfo import ZoneInfo except ImportError: from ...
PAT0216/paper-trader
src/data/price_utils.py
.py
b3f448f91af4fedd
7.52
10
""" Universe Manager Reconstructs point-in-time S&P 500 universes by walking backwards from the current constituent list using historical changes (adds/removes). """ import pandas as pd from datetime import datetime import os class UniverseManager: def __init__(self, current_tickers: list[str], changes_csv: str):...
PAT0216/paper-trader
src/data/universe.py
.py
802182e84c0b356f
7.52
10
""" Data Validation Module for Paper Trader Ensures data quality and integrity by detecting missing values, outliers, stale data, and potential data errors before they impact trading decisions. """ import pandas as pd import numpy as np from datetime import datetime, timedelta from typing import Dict, List, Tuple, Op...
PAT0216/paper-trader
src/data/validator.py
.py
2673866d36034028
7.52
10
""" SHAP-based Model Explainability Provides interpretability for XGBoost trading model decisions using SHAP (SHapley Additive exPlanations) values. Key Features: - Feature importance for individual predictions - Waterfall plots showing decision breakdown - Top contributing features for each trade signal Usage: ...
PAT0216/paper-trader
src/explainability/shap_analyzer.py
.py
c7431b5489599b99
7.52
10
""" Behavioral Alpha Factors (40 Factors) Based on research paper: "Dual-Task MLP on Behavioral Alpha Factors" Groups: 1. Momentum & Herding (12 factors): Capture trend-following behavior 2. Volume-Price Divergence (9 factors): Detect conviction and reversals 3. Oversold Reversals (12 factors): Bottom detection signa...
PAT0216/paper-trader
src/features/behavioral_factors.py
.py
58ab5d18ec5ed0c8
7.52
10
""" Factor Investing Features Based on Fama-French academic research (1993, 2015). Factors implemented: 1. Value: Book-to-Market ratio (inverse of P/B) 2. Quality: Return on Equity (ROE) + low debt 3. Momentum: 12-month return excluding last month (12-1) Combined into composite score for stock ranking. """ import p...
PAT0216/paper-trader
src/features/factor_features.py
.py
8d4509d43444bfc1
7.52
10
import pandas as pd import numpy as np def compute_rsi(series, period=14): delta = series.diff() gain = (delta.where(delta > 0, 0)).rolling(window=period).mean() loss = (-delta.where(delta < 0, 0)).rolling(window=period).mean() rs = gain / loss return 100 - (100 / (1 + rs)) def compute_macd(series...
PAT0216/paper-trader
src/features/indicators.py
.py
56137431137caf48
7.52
10
"""High-level Python API for galdr. This module is intentionally small and boring. The CLI remains the full-featured interface; these wrappers give Python users a clean path for notebooks, scripts, and web apps without needing to know galdr's on-disk file layout first. """ from __future__ import annotations from dat...
sellemain/galdr
src/galdr/api.py
.py
9c2e1cc21e60a53c
7.45
7
"""Shared audio context for one galdr listen run.""" from __future__ import annotations from dataclasses import dataclass import librosa import numpy as np @dataclass(frozen=True) class AudioContext: """Loaded mono audio shared across analysis modules.""" y: np.ndarray sr: int duration: float ...
sellemain/galdr
src/galdr/audio_context.py
.py
5c84e75598f4a3b4
7.45
7
#!/usr/bin/env python3 """Catalog state — cross-track accumulated statistics. The stateful listener needs memory. This module maintains a catalog index that tracks running statistics across all analyzed tracks, so each new analysis can compute relative metrics. The catalog index is stored as catalog_state.json. Defau...
sellemain/galdr
src/galdr/catalog.py
.py
1cda5c283ba6c227
7.45
7
"""Output schema and provenance helpers for galdr analysis artifacts.""" from __future__ import annotations import hashlib from datetime import datetime, timezone from pathlib import Path from typing import Any try: from . import __version__ as _GALDR_VERSION except Exception: # pragma: no cover - defensive dur...
sellemain/galdr
src/galdr/provenance.py
.py
0b8f088595f3ea9d
7.45
7
"""Tempo validation helpers for galdr. Librosa's single beat-tracking estimate can lock to an alternate pulse. These helpers keep the detected pulse, then add a small candidate/felt-pulse layer backed by windowed cross-checks. """ from __future__ import annotations from collections import defaultdict from dataclasse...
sellemain/galdr
src/galdr/tempo.py
.py
de8e172fa9452b75
7.45
7
"""Smoke tests for galdr package — verify imports and basic structures.""" import pytest def test_import_galdr(): """Package imports without error.""" import galdr assert hasattr(galdr, "__version__") assert isinstance(galdr.__version__, str) assert galdr.__version__ != "" def test_import_anal...
sellemain/galdr
tests/test_smoke.py
.py
bd73c4a5628a874c
7.95
7
"""The MaxMind GeoLite2 country database: fetch it, cache it, prune it. SPLIT OUT OF download.py ON 2026-07-27. That file was 568 lines covering two subjects that share nothing but the words "download something from GitHub": the patched Firefox engine, and this. Measured before the split - the geoip half calls four he...
feder-cr/invisible_core
src/invisible_core/_geoip_db.py
.py
d08798f1134f7bd9
7.5
9
"""Invisible-but-headed browser windows. Playwright's ``headless=True`` flips Firefox onto a different code path - no widget tree, software-only rendering, distinct timing - and anti-bot systems can spot the divergence. Running the browser *headed* but hidden gives us the real rendering pipeline while keeping the wind...
feder-cr/invisible_core
src/invisible_core/_headless.py
.py
f6ec407390ba4d7f
7.5
9
"""Empirically-calibrated WebGL GPU personas for Windows ANGLE D3D11. We expose a FALSE GPU (this is a multi-user tool - never leak each host's real GPU), chosen deterministically per seed from a small set of renderer-string "buckets" that Firefox's SanitizeRenderer emits and that FP Pro's tampering_ml scores as CLEAN...
feder-cr/invisible_core
src/invisible_core/_webgl_personas.py
.py
c792610ea76f4243
7.5
9
"""Public helpers for building Firefox launch config without using ``InvisiblePlaywright``. Use these when you need to call ``playwright.firefox.launch()`` (or ``firefox.launch_persistent_context()``) directly with our patched binary and stealth prefs, instead of using the ``InvisiblePlaywright`` context manager. Typ...
feder-cr/invisible_core
src/invisible_core/config.py
.py
bca2e9ae83c6fec2
7.5
9
"""Direct-launch helpers shared by the Playwright wrapper and the profile manager: write a user.js from a prefs dict, and build the subprocess env the patched binary reads at startup. No Playwright, no Qt.""" from __future__ import annotations import json import hashlib import os from dataclasses import dataclass, fie...
feder-cr/invisible_core
src/invisible_core/launch.py
.py
602edced7f7714a1
7.5
9
"""Refuse to run the suite against a DIFFERENT copy of the package than the one being edited. This exists because the failure it catches is invisible and it has already cost real work. On 2026-07-27, mid-release, `pytest` in this repo was reading `site-packages` rather than `src/`, and it produced two separate wrong v...
feder-cr/invisible_core
tests/conftest.py
.py
ab25a6327b0905f5
8
9
"""The public config API's humanize default, and what it hands a caller. `get_default_stealth_prefs` is for somebody driving the patched binary with their own Playwright - nobody inside this project's own packages calls it (three when this was written - invisible_core, invisible_playwright, invisible_firefox; two sinc...
feder-cr/invisible_core
tests/test_config_api.py
.py
1718f34a22f42201
8
9
"""The public `config` helpers, as behaviour. MOVED FROM invisible_playwright/tests/unit/ ON 2026-07-27, with two tests left behind: the two that assert the WRAPPER re-exports these, which is a claim about the wrapper and belongs there. This file sat one directory below the wrapper's top-level tests, and the first cu...
feder-cr/invisible_core
tests/test_config_defaults.py
.py
feba23427cbbd0a4
8
9
"""What the consumer imports from this package, asserted from inside it. WHY. `invisible-playwright` pins `invisible-core==` to an exact version, so a name that disappears here does not fail somebody's build - it fails their IMPORT, on the machine of whoever upgrades next, with a traceback naming a symbol rather than ...
feder-cr/invisible_core
tests/test_consumer_contract.py
.py
5ebe3f00cb88660a
8
9
"""Profile generator - seed reproducibility and basic shape.""" # MOVED FROM invisible_playwright/tests/ ON 2026-07-27. # # _fpforge is this package's fingerprint generator. Its tests reached it through # a back-compat shim in the wrapper, which is how coverage for a module ends up # in a suite that belongs to another ...
feder-cr/invisible_core
tests/test_fpforge.py
.py
12d52447feca6bc6
8
9
"""The geo step has to be bounded as a STEP, not just per request. The bug: three IP-echo endpoints, tried in sequence, ten seconds each. Every individual request was bounded and the step as a whole was not, so the worst case was thirty seconds of a launch and one launch in six spent 35s here. A per-request timeout an...
feder-cr/invisible_core
tests/test_geo_budget.py
.py
c2b97507072817f5
8
9
"""The juggler provenance contract exists twice. This is what compares them. WHAT THE CONTRACT IS. Four file paths inside a built engine, two marker byte strings that must appear in them, and the directory those paths live under. Together they answer "is this a build of OUR patched Firefox, or a stock one?" - the ques...
feder-cr/invisible_core
tests/test_juggler_contract.py
.py
8ff5a6f5cde29c32
8
9
"""Two fixes that were made and then left unguarded. Both were listed as still-open in `70-known-bugs.md` on 2026-07-25 and both had in fact been fixed in the code by 2026-07-26. What had NOT happened is a test: reverting either one left the suite fully green, 75 passed. A fix nothing holds in place is a fix with a re...
feder-cr/invisible_core
tests/test_pin_recovery_message.py
.py
8ca41ef29bbffdc9
8
9
import json import os import sys from pathlib import Path def get_base_dir(): """Returns the base directory of the application.""" if getattr(sys, "frozen", False): # Running as a built .exe return Path(sys.executable).parent else: # Running as a script return Path(__file__...
rdevz-ph/PyAMPP-Windows
core/config.py
.py
d58e67f0ee7a5700
7.42
6
import requests import zipfile import os import shutil import secrets from pathlib import Path # Use minimal headers as they worked initially for MySQL HEADERS = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)" } def validate_url(url): """Simplified validation that was working for MySQL initially."...
rdevz-ph/PyAMPP-Windows
core/downloader.py
.py
e70dc00e15e0a920
7.42
6
import os import subprocess from pathlib import Path from core.server_manager import ServerManager from core.config import config_manager class MySQLManager(ServerManager): def __init__(self): self.update_paths() super().__init__("MySQL", self.exe_path, config_manager.get("mysql_port")) def up...
rdevz-ph/PyAMPP-Windows
core/mysql_manager.py
.py
f31b6e30e0649289
7.42
6
from enum import Enum class EventTypes(Enum): """Типы событий.""" CHAT_INITIALIZED = 0 """Чат инициализирован.""" NEW_MESSAGE = 1 """Новое сообщение в чате.""" NEW_DEAL = 2 """Создана новая сделка (когда покупатель оплатил товар).""" NEW_REVIEW = 3 """Новый отзыв от покупателя."""...
KaDerix/PlayerokCardinal
PlayerokAPI/enums.py
.py
78eb7090a910e46a
7.45
7
"""Конвертация сумм Playerok (рубли в API).""" from __future__ import annotations def to_rub(amount) -> float: if amount is None: return 0.0 try: return float(amount) except (TypeError, ValueError): return 0.0 def balance_display_rub(balance) -> tuple[float, float, float]: ""...
KaDerix/PlayerokCardinal
Utils/playerok_money.py
.py
abd8b507444631f5
7.45
7
""" В данном модуле описаны функции для ПУ настроек прокси. Модуль реализован в виде плагина. """ from __future__ import annotations from typing import TYPE_CHECKING if TYPE_CHECKING: from cardinal import Cardinal from telebot.types import CallbackQuery, Message import logging from locales.localizer import Local...
KaDerix/PlayerokCardinal
tg_bot/default_cp.py
.py
c6a3844cfc60970c
7.45
7
import logging from fastapi import APIRouter, HTTPException, Request from models.account import AccountCreate, AccountPublic, AccountStatus, AccountUpdate from services.immich_client import ImmichClient logger = logging.getLogger(__name__) router = APIRouter(prefix="/api/accounts", tags=["accounts"]) MIN_SUPPORTED_...
Trust1509/immich-family-tools
backend/routers/accounts.py
.py
072718b31a576dcb
7.5
9
""" Match suggestions router. GET /api/matches – Return cached match list (recompute if stale) POST /api/matches/refresh – Invalidate cache and recompute POST /api/matches/{id}/dismiss – Mark a match as dismissed """ import time import logging from fastapi import APIRouter, Request from models.matc...
Trust1509/immich-family-tools
backend/routers/faces.py
.py
f902929952e24dc3
7.5
9
"""Direct, context-free model completions used by the bundled batch skill.""" from __future__ import annotations import json from typing import Any from ene.messages import ImagePart, Message, TextPart from ene.models import REASONING_EFFORTS, ReasoningEffort from ene.providers import CompletionRequest, ProviderUsag...
ashawkey/ene
ene/backend/batch.py
.py
08b385e0af06901b
7.42
6
"""Skill discovery and interactive skill commands.""" import json import uuid from pathlib import Path from ene.messages import Message, ToolCall from ene.tools import format_tool_result class SkillCommandsMixin: def _cmd_skills(self, raw: str = "/skills"): """List, reload, or manually load skills. ...
ashawkey/ene
ene/backend/skill_commands.py
.py
f1b747d5b71320ff
7.42
6
"""Compute self-BLEU for a set of generated text samples. Self-BLEU measures how similar generated samples are to each other. High self-BLEU -> texts are repetitive -> mode collapse. Low self-BLEU -> texts are diverse -> healthy generation. """ import argparse import json import math import random from collections imp...
Fangjiage-1/FLRS
scripts/compute_self_bleu.py
.py
7c8942fdb0103893
7.52
10
"""Layer primitives for the ELF transformer.""" import math from typing import Optional import torch import torch.nn as nn import torch.nn.functional as F from einops import rearrange, repeat # Init defaults: # - Linear weights: xavier_uniform; biases: 0 # - TimestepEmbedder MLPs and learned tokens: normal(0.02) # ...
Fangjiage-1/FLRS
src/modules/layers.py
.py
e19bf62ef5b0e0d6
7.52
10
#!/usr/bin/env python """Frozen T5 text embedder, wrapping `transformers.T5EncoderModel`.""" from typing import Any, Optional import torch import torch.nn as nn from utils.logging_utils import log_for_0 class T5EncoderConfig: """Configuration class for T5Encoder.""" def __init__(self, model_name: str, dty...
Fangjiage-1/FLRS
src/modules/t5_encoder.py
.py
03bd8edc00d407da
7.52
10
import torch import numpy as np @torch.no_grad() def encode_text( input_ids, attention_mask, encoder, latent_mean, latent_std, use_bf16=True, ): """Encoder pass from text to latent with normalization.""" autocast_enabled = bool(use_bf16) and input_ids.is_cuda with torch.amp.autocas...
Fangjiage-1/FLRS
src/utils/encoder_utils.py
.py
3f2d2ca7efe7e226
7.52
10
import inspect import logging import os def _process_index() -> int: """Return torch.distributed rank, falling back to env vars or 0.""" try: import torch.distributed as dist if dist.is_available() and dist.is_initialized(): return dist.get_rank() except Exception: pass...
Fangjiage-1/FLRS
src/utils/logging_utils.py
.py
94427e79649907c8
7.52
10
"""Freeze (or verify) the research baseline: golden stdout + fingerprints. .venv/Scripts/python scripts/freeze_research_baseline.py # verify .venv/Scripts/python scripts/freeze_research_baseline.py --write # freeze MI Lab Layer 1, Step 0. Writing goldens is DELIBERATE: without --write this tool ...
martex-dev/martex-quant
scripts/freeze_research_baseline.py
.py
6ab3f4115dcedb6e
7.5
9
"""Hypothesis 08 kill test: funding extremes vs forward spot returns. .venv/Scripts/python scripts/h08_funding_killtest.py Spec pre-registered in docs/hypotheses/08-funding-extremes.md (committed before this ran). Funding history is cached to data/funding/<sym>.parquet so re-runs are offline. """ from __future__...
martex-dev/martex-quant
scripts/h08_funding_killtest.py
.py
fdbd4da272e2ed16
8
9
"""Hypothesis 09 kill test: calendar effects (pre-registered sub-claims only). .venv/Scripts/python scripts/h09_calendar_killtest.py """ from __future__ import annotations from pathlib import Path import polars as pl from martex_quant.data.models import Interval from martex_quant.data.store.parquet_store import Pa...
martex-dev/martex-quant
scripts/h09_calendar_killtest.py
.py
990b0f24a4e5f47f
8
9
"""Hypotheses 13 (shock persistence) + 14 (vol-expansion breakout) kill tests. .venv/Scripts/python scripts/h13_h14_killtests.py Specs pre-registered in docs/hypotheses/13-*.md and 14-*.md. """ from __future__ import annotations from pathlib import Path import polars as pl from martex_quant.data.store.parquet...
martex-dev/martex-quant
scripts/h13_h14_killtests.py
.py
83cd4a2d401742bc
8
9
"""Cross-sectional ranking kill-test batch: hypotheses 24-32. .venv/Scripts/python scripts/h24_32_killtests.py Pre-registered in docs/hypotheses/24-32-ranking-batch.md. """ from __future__ import annotations import json from pathlib import Path import polars as pl from martex_quant.data.models import Interval...
martex-dev/martex-quant
scripts/h24_32_killtests.py
.py
5da44450dbf6780d
8
9
"""H53 kill test: aggressor imbalance (taker-buy ratio), 15m Binance USDM. .venv/Scripts/python scripts/h53_killtest.py Pre-registered in docs/hypotheses/52-57-intraday-frontier.md. H54 (OI divergence) is DATA-BLOCKED: Bybit serves only ~200h of OI history; deep positioning history is paid data. Recorded as block...
martex-dev/martex-quant
scripts/h53_killtest.py
.py
db4b0a55d3a27999
8
9
"""H59: is the live paper drawdown consistent with the backtest's own distribution? .venv/Scripts/python scripts/h59_drawdown_consistency.py Pre-registered in docs/hypotheses/59-live-drawdown-consistency.md, committed before the guarded window was analysed. The null is the strategy's OWN backtested daily returns...
martex-dev/martex-quant
scripts/h59_drawdown_consistency.py
.py
0b43fb7f83a164e5
7.5
9
"""Base rate of the Solana launch cohort, from the recorded forward panel. This is the number the whole meme program hinges on: what an **unselected** new launch does, entered at a price we could actually have paid, net of AMM costs. Everything else - filters, models, wallet signals - is only meaningful as a delta aga...
martex-dev/martex-quant
scripts/meme_base_rate.py
.py
e6ad179f3edab35c
7.5
9
"""Continuously capture the Solana new-pool stream into the launch registry. Run this and leave it running. Every sweep walks the ten pages of GeckoTerminal's new-pool feed — about a five-minute window of launches — and records any pool it has not seen before, exactly as the API described it at first sighting. Nothing...
martex-dev/martex-quant
scripts/meme_record.py
.py
2e26590d87008a9e
7.5
9
"""Pull Bybit USDT-perp 15m OHLCV for the retail intraday batch (H44-50). .venv/Scripts/python scripts/pull_intraday.py Caches to data/intraday/<symbol>_15m.parquet (atomic overwrite). ~12 liquid majors, max available history. Paginates by timestamp until `now` (short batches are NOT an end signal on Bybit) and b...
martex-dev/martex-quant
scripts/pull_intraday.py
.py
98fcd3ec2e19c2c7
7.5
9
from abc import ABC, abstractmethod from typing import Any, Dict, List, Optional, Union from src.core.agent.types import AssistantMessage class LLMClient(ABC): """Provider-agnostic, tool-aware chat client. This is the single primitive the agent harness depends on. Concrete providers (OpenAI, Groq, OpenR...
emqnuele/projectBEA
src/core/agent/llm_client.py
.py
723b92c57193a158
7.56
12
"""Turning our types into the OpenAI wire format. One copy. The consciousness, the agent runner and the conversation turns all build the same two message shapes, and three drifting copies of a serialization detail is how a subtle protocol bug gets introduced in exactly one of them. """ import json from typing import ...
emqnuele/projectBEA
src/core/agent/messages.py
.py
506415d2e28cf298
7.56
12
import inspect from dataclasses import dataclass from typing import Any, Callable, Dict, List, Optional from src.core.agent.types import ToolCall from src.utils.logger import get_logger logger = get_logger("bea.agent.tools") # a handler may be sync or async; it always returns an observation string ToolHandler = Call...
emqnuele/projectBEA
src/core/agent/tools.py
.py
88d1a44b326da3a8
7.56
12
from dataclasses import dataclass, field from typing import Any, Dict, List, Optional @dataclass class ToolCall: """A single tool invocation requested by the model.""" id: str name: str arguments: Dict[str, Any] @dataclass class Usage: """What one model call cost. Zero when the provider did not...
emqnuele/projectBEA
src/core/agent/types.py
.py
5eb56b7d31dcdf25
7.56
12
"""Is this person answering her? A separate gate, and a deterministic one. The score in `rules.py` answers "does this concern me", which is a judgement call and rightly probabilistic. "Are you talking to me" is not a judgement call, and rolling a die on it is exactly what makes a bot feel broken — you reply to her and...
emqnuele/projectBEA
src/core/attention/followup.py
.py
b6ddb071d6c72bb4
7.56
12
"""The attention decision, as pure functions: no IO, so it stays testable. Two questions, kept apart: `is_addressed` ("is this for me?") is deterministic and bypasses cooldown and quiet hours; `score` ("does this concern me?") is probabilistic. """ from typing import Optional, Sequence, Tuple from src.core.perceptio...
emqnuele/projectBEA
src/core/attention/rules.py
.py
69ec5daa382027ed
7.56
12
"""What the attention gate decides. Pure data, no IO.""" from dataclasses import dataclass from enum import Enum class Reaction(str, Enum): """What to do with a perception.""" REACT = "react" # wake the mind now NOTE = "note" # goes into the digest; zero llm calls DROP = "drop" # noise, th...
emqnuele/projectBEA
src/core/attention/types.py
.py
7a4685764e6e479f
7.56
12
"""Local, in-process embeddings (fastembed / ONNX on CPU). Lazy: the model (~100MB) is fetched on the first `embed`, so startup does not wait for it. Two methods only, so a test can inject a deterministic fake. The default is multilingual: with an English-only model, non-English sentences collapse into the same regio...
emqnuele/projectBEA
src/core/memory/embedder.py
.py
9d4dc557e8052ed8
7.56
12
"""The bridge between an HTTP caller and Bea's next reply. Synchronous entrypoints (the dashboard chat box, a Discord voice turn) deposit a perception and wait. One rule: a waiting caller is always freed — silence is an answer, a hang is a bug. """ import asyncio import uuid from typing import Any, Callable, Dict, Li...
emqnuele/projectBEA
src/core/mind/correlation.py
.py
b6b68d380f303efa
7.56
12
"""The one list of moods. It used to live in three places that could drift apart: a table in `operating.md`, a free-text description in the `speak` tool, and the keys of `avatar_map`. The table stays in the file — it is the explanation, and the file is meant to be edited. This is the enforcement: the tool's enum, the ...
emqnuele/projectBEA
src/core/mind/moods.py
.py
b8f4689ec8e3f2cf
7.56
12
"""The floor under the operating manual, and the check that it still fits. `data/prompts/operating.md` stays a file on purpose: anyone who wants to change how she works should be able to open it. What was missing is what happens when it is gone — `load_text` returned an empty string and she quietly lost the mood table...
emqnuele/projectBEA
src/core/mind/operating.py
.py
bbd4825559853f62
7.56
12
"""Where does a perception go: the stage, or a scoped conversation? The stage is what she does live in front of an audience — voice, the game, the console. A scoped conversation is written text in one channel. One rule: a perception goes to exactly one turn, or she answers it twice. """ from typing import Optional ...
emqnuele/projectBEA
src/core/mind/routing.py
.py
47186473e4d27cf1
7.56
12
"""One turn at a time per conversation; different conversations in parallel. Two messages in the same channel would otherwise be answered concurrently: replies out of order, or one reply per message. Coalescing adds no latency: a message arriving while a turn is generating marks the running turn to re-run instead of ...
emqnuele/projectBEA
src/core/mind/scheduler.py
.py
5cae0c54a088044f
7.56
12
"""What the mind can do right now. The set only changes when a capability is toggled, so it is cached and invalidated then rather than rebuilt on every model step. `speak` and `stay_silent` live here: they belong to the mind, not to a skill. """ from typing import Callable, List, Optional from src.core.agent.tools i...
emqnuele/projectBEA
src/core/mind/tools.py
.py
cfdebf10f55072dd
7.56
12
import asyncio import time from typing import List, Optional from src.core.perception.types import Perception, PerceptionKind from src.utils.logger import get_logger logger = get_logger("bea.perception.bus") class PerceptionBus: """The single sensory channel feeding the one consciousness. Every surface (ch...
emqnuele/projectBEA
src/core/perception/bus.py
.py
55872e30e8cb84b9
7.56
12
"""Reading and writing the persona: one file and two config fields. The soul stays a markdown file so it can be opened, diffed and edited by hand. This is the other way in — the dashboard — which means a web request ends up writing to disk, so most of what is here is about refusing to. """ from dataclasses import dat...
emqnuele/projectBEA
src/core/persona_store.py
.py
f93af287e680aae9
7.56
12
from pathlib import Path from typing import Dict, Tuple from src.utils.logger import get_logger logger = get_logger("bea.resources") ALIASES = {"thankingA1": "thanking—"} def load_avatar_resources(avatar_map: Dict[str, Dict[str, str]]) -> Dict[str, Tuple[Path, Path]]: """ Carica e valida le risorse avatar d...
emqnuele/projectBEA
src/core/resources.py
.py
aa2a9d322c68974d
7.56
12
from typing import Any, Dict, List, Optional from src.core.agent.tools import Tool from src.utils.logger import get_logger logger = get_logger("bea.skills") # not an ABC: every hook below is optional, a skill overrides only what it supports class Skill: """A toggleable capability of the one consciousness. ...
emqnuele/projectBEA
src/core/skills/base.py
.py
d14840afc07367a6
7.56
12
#!/usr/bin/env python """ Human-in-the-loop demo of Yutori Navi-Bench where: - The human + Playwright browser act as the "agent loop". - Each page navigation is treated as an agent step. - We call evaluator.update(...) on every step. - At the end, we call evaluator.compute() for the final score. This demonstrates how...
yutori-ai/navi-bench
demo.py
.py
906f0ac1f4b5b453
7.65
19
import asyncio import functools import os from collections.abc import AsyncIterator from contextlib import asynccontextmanager from typing import Protocol, runtime_checkable from loguru import logger from playwright.async_api import Browser, BrowserContext, Error as PlaywrightError, Page, Playwright from navi_bench.b...
yutori-ai/navi-bench
evaluation/browser.py
.py
4bede36a6230a2e0
7.65
19
import argparse import asyncio import functools import inspect from typing import get_args, get_origin from pydantic_core import PydanticUndefined from navi_bench.base import unwrap_optional_type def cli(fn): """Decorator that creates a CLI from the Pydantic Config parameter of an async/sync function. Usag...
yutori-ai/navi-bench
evaluation/cli.py
.py
bb22bf8924014bed
7.65
19
import json import re from urllib.parse import urlencode from beartype import beartype from loguru import logger from navi_bench.base import ( BaseTaskConfig, FinalResult, ResetsViaState, UrlMetricInput, all_or_nothing_coverage_result, basic_normalize_url, build_task_config, parse_filt...
yutori-ai/navi-bench
navi_bench/apartments/apartments_url_match.py
.py
90fcced1546441e4
7.65
19
"""Unified utilities for parsing and evaluating dynamic date expressions.""" import re from datetime import date, datetime, timedelta, timezone from zoneinfo import ZoneInfo from navi_bench.base import UserMetadata from navi_bench.relative_dates import parse_relative_dates _MONTH_STYLE_OPTIONS = {"short", "long"} _...
yutori-ai/navi-bench
navi_bench/dates.py
.py
371871cf7815c15a
7.65
19
"""Shared pytest fixtures and helpers for the navi-bench test suite.""" import asyncio def run_async(coro): """Run an async coroutine to completion and return its result. Shared across the test suite so individual test modules don't each redefine an identical local ``_run`` helper. """ return as...
yutori-ai/navi-bench
tests/conftest.py
.py
42c4f5370c792b85
8.15
19
"""Characterization tests for ``evaluation.cli._build_argparse_kwargs``, which shares its ``Optional[T]``/``T | None`` detection with ``navi_bench.base.basic_pydantic_to_hf_features`` via the extracted ``navi_bench.base.unwrap_optional_type`` helper. These pin the pre-refactor behavior for optional, list, bool, basic, ...
yutori-ai/navi-bench
tests/test_cli.py
.py
2eba993f21b0835a
8.15
19
"""Characterization tests for ``navi_bench.dates.initialize_placeholder_map``. This function had no prior test coverage even though it is the shared placeholder-date resolver used by resy, opentable, and google_flights task generation (all via ``initialize_placeholder_map``). Its string-parsed branch used to discard t...
yutori-ai/navi-bench
tests/test_dates.py
.py
15360484e527c174
8.15
19
"""Characterization tests for ``evaluation.eval_n1``'s fatal-vs-retryable API-error rule. ``eval_n1.py`` had three hand-rolled ``except`` ladders implementing one shared rule -- "an ``APIStatusError`` that is not in ``RETRYABLE_API_ERRORS`` must propagate; everything else is non-fatal" -- spelled three different ways,...
yutori-ai/navi-bench
tests/test_eval_n1.py
.py
12c6fba84f0f8ce5
8.15
19
"""Characterization tests for OpenTableInfoGathering's query-matching logic. These tests pin the behavior of ``_check_multi_candidate_query`` and ``_check_single_candidate_query`` (and, transitively, ``_is_exhausted``), including their shared four-way branch (``"no online availability"`` / time-range ``"unavailable"``...
yutori-ai/navi-bench
tests/test_opentable_info_gathering.py
.py
3a8aafaf0f7dc5a3
7.15
19