repo stringclasses 454
values | file_path stringlengths 5 201 | extension stringclasses 1
value | content stringlengths 8 509k | num_lines int64 3 16.9k | size_bytes int64 8 511k |
|---|---|---|---|---|---|
Vibe-Trading | agent/src/factors/zoo/academic/cma.py | .py |
# ============================================================
# 中文名称: 投资风格因子 (CMA)
# 简要说明: Fama-French五因子模型中的投资因子(Conservative Minus Aggressive),做多保守投资做空激进投资公司的收益。
# 典型用途: 捕获低投资公司相对于高投资公司的超额收益。
# ============================================================
"""academic CMA: investment factor as inverse 60-day volume g... | 68 | 2,966 |
Vibe-Trading | agent/src/factors/zoo/academic/smb.py | .py |
# ============================================================
# 中文名称: 市值规模因子 (SMB)
# 简要说明: Fama-French三因子模型中的规模因子(Small Minus Big),做多小市值做空大市值的投资组合收益。
# 典型用途: 捕获小市值公司相对于大市值公司的超额收益,用于规模效应分析。
# ============================================================
"""academic SMB: size factor as inverse log of 60-day average doll... | 62 | 2,712 |
Vibe-Trading | agent/src/factors/zoo/academic/mkt_rf.py | .py |
# ============================================================
# 中文名称: 市场超额收益因子 (Mkt-RF)
# 简要说明: Fama-French三因子模型中的市场因子,代表市场组合相对于无风险利率的超额收益。
# 典型用途: 作为市场基准beta,用于资产定价模型中衡量系统性风险暴露。
# ============================================================
"""academic MKT_RF: market factor as 21-day return, cross-sectionally z-scor... | 60 | 2,605 |
Vibe-Trading | agent/src/factors/zoo/academic/corr_rewire.py | .py | # ============================================================
# 中文名称: 相关性重连因子 (Correlation Rewiring)
# 简要说明: 近期事件窗口与前置平静基线窗口的相关系数矩阵逐行平均绝对变化,衡量资产与市场整体关系的重构幅度;因子值取负(相关性结构稳定的资产得分高)。
# 典型用途: 风险/拥挤度横截面监控,慢性恶化(阴跌)资产识别;与波动率类因子互补的结构性风险视角。
# ============================================================
"""Correlation-rewiring s... | 188 | 8,345 |
Vibe-Trading | agent/src/factors/zoo/academic/retskew.py | .py |
# ============================================================
# 中文名称: 收益偏度因子 (RETSKEW)
# 简要说明: 过去一段时间日收益分布偏度越低(越负偏),预期收益越高。Harvey & Siddique(2000)的偏度溢价。
# 典型用途: 捕获特质偏度溢价,做多负偏(类彩票反向)的股票,用于偏度风格分析。
# ============================================================
"""academic return skewness: inverse trailing skewness of da... | 61 | 2,697 |
Vibe-Trading | agent/src/factors/zoo/academic/illiq.py | .py |
# ============================================================
# 中文名称: Amihud非流动性因子 (ILLIQ)
# 简要说明: 单位成交额带来的价格冲击越大,流动性越差,预期收益越高(流动性溢价)。Amihud(2002)。
# 典型用途: 捕获非流动性溢价,做多流动性差的股票,用于流动性风格分析。
# ============================================================
"""academic Amihud illiquidity: average absolute return per dollar of... | 63 | 2,785 |
Vibe-Trading | agent/src/factors/zoo/academic/hml.py | .py |
# ============================================================
# 中文名称: 价值因子 (HML)
# 简要说明: Fama-French三因子模型中的价值因子(High Minus Low),做多高账面市值比做空低账面市值比的收益。此处使用负的252日收益作为代理。
# 典型用途: 捕获价值股相对于成长股的超额收益,用于价值投资策略。
# ============================================================
"""academic HML: value factor as inverse 252-day retur... | 67 | 3,064 |
Vibe-Trading | agent/src/factors/zoo/academic/strev.py | .py |
# ============================================================
# 中文名称: 短期反转因子 (STREV)
# 简要说明: 做多过去一个月输家、做空过去一个月赢家的收益。短期(月度)价格存在反转效应。
# 典型用途: 捕获一个月尺度的均值回复,用于短期反转策略。
# ============================================================
"""academic short-term reversal: inverse trailing 21-day return.
Reference:
Jegadeesh, ... | 59 | 2,467 |
Vibe-Trading | agent/src/factors/zoo/academic/carhart_mom.py | .py |
# ============================================================
# 中文名称: 动量因子 (MOM)
# 简要说明: Carhart四因子模型中的动量因子(Momentum),做多过去表现好做空过去表现差的股票收益。
# 典型用途: 捕获股价趋势延续效应,用于动量投资策略。
# ============================================================
"""academic Carhart momentum: 12-month return excluding the most recent month.
Referen... | 66 | 2,965 |
Vibe-Trading | agent/src/api/system_routes.py | .py | """System and utility HTTP routes.
Mounted by ``agent/api_server.py`` via ``register_system_routes(app, ...)``.
"""
from __future__ import annotations
import logging
import os
import signal
import threading
import time
from collections import deque
from datetime import datetime, timezone
from typing import Deque, Di... | 469 | 19,334 |
Vibe-Trading | agent/src/api/runs_routes.py | .py | """Run listing and detail HTTP routes.
Mounted by ``agent/api_server.py`` via ``register_runs_routes(app, ...)``.
"""
from __future__ import annotations
import csv
import json
import math
import os
import statistics
from collections import deque
from datetime import datetime
from pathlib import Path
from typing impo... | 901 | 33,641 |
Vibe-Trading | agent/src/api/state.py | .py | """Lazy-init service singletons shared by session, channel, and live routes."""
from __future__ import annotations
import os
from fastapi import HTTPException
from src.api._compat import host_attr as _host_attr, set_host_attr as _set_host_attr
from src.api.helpers import RUNS_DIR, SESSIONS_DIR
from src.config.acces... | 111 | 3,583 |
Vibe-Trading | agent/src/api/_compat.py | .py | """Shared monkeypatch compatibility layer for extracted API modules.
Tests monkeypatch ``api_server._API_KEY`` (and similar). Route modules
resolve dependencies via ``sys.modules["api_server"]``, so the patched
value lives on the *host* module, not on the extracted module.
"""
from __future__ import annotations
imp... | 27 | 850 |
Vibe-Trading | agent/src/api/options_routes.py | .py | """Options analysis HTTP routes for the Web UI.
Mounted by ``agent/api_server.py`` via ``register_options_routes(app, ...)``.
Pulled into its own module because ``api_server.py`` is already huge, matching
the ``alpha_routes.py`` slice pattern.
Routes (auth via the caller-supplied ``require_auth`` dependency):
- ``PO... | 236 | 9,644 |
Vibe-Trading | agent/src/api/channels_routes.py | .py | """IM channel HTTP routes.
Mounted by ``agent/api_server.py`` via ``register_channels_routes(app, ...)``.
"""
from __future__ import annotations
from typing import Any, Awaitable, Callable
from fastapi import Depends, FastAPI
from pydantic import BaseModel
# -------------------------------------------------------... | 116 | 3,939 |
Vibe-Trading | agent/src/api/sessions_routes.py | .py | """Session and goal HTTP routes.
Mounted by ``agent/api_server.py`` via ``register_sessions_routes(app)``.
"""
from __future__ import annotations
import asyncio
import json
import logging
import re
from datetime import datetime, timezone
from typing import Any, Dict, List, Optional
from fastapi import Depends, Fast... | 802 | 32,208 |
Vibe-Trading | agent/src/api/alpha_routes.py | .py | """Alpha Zoo HTTP routes for the Web UI.
Mounted by ``agent/api_server.py`` via ``register_alpha_routes(app, ...)``. Pulled
into its own module because ``api_server.py`` is already ~1800 lines.
Routes (auth via the caller-supplied ``require_auth`` /
``require_event_stream_auth`` dependencies):
- ``GET /alpha/list``... | 792 | 30,915 |
Vibe-Trading | agent/src/api/models.py | .py | """Pydantic response models shared across API route modules."""
from __future__ import annotations
from typing import Any, Dict, List, Optional
from pydantic import BaseModel, Field
class Artifact(BaseModel):
"""Artifact file metadata."""
name: str = Field(..., description="File name")
path: str = Fie... | 105 | 4,880 |
Vibe-Trading | agent/src/api/qveris_routes.py | .py | """QVeris settings and status routes."""
from __future__ import annotations
import sys as _sys
from typing import Any, Literal
from fastapi import APIRouter, Depends, HTTPException, Request, Security
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from pydantic import BaseModel, Field
from src... | 232 | 7,275 |
Vibe-Trading | agent/src/api/live_routes.py | .py | """Live-trading channel HTTP routes (consent commit, kill switch, C2 status, runner control).
Mounted by ``agent/api_server.py`` via ``register_live_routes(app)``.
These are the privileged SURFACE actions of the live-trading channel
(live-trading SPEC, Consent §1/§3/§4). None is an agent tool:
- ``POST /mandate/comm... | 1,041 | 42,819 |
Vibe-Trading | agent/src/api/scheduled_routes.py | .py | """Scheduled research HTTP routes.
Mounted by ``agent/api_server.py`` via ``register_scheduled_routes(app, ...)``.
"""
from __future__ import annotations
import logging
import re
import sys as _sys
import time
import uuid
from typing import Any, Awaitable, Callable, Dict, List, Optional
from fastapi import Depends,... | 482 | 18,121 |
Vibe-Trading | agent/src/api/security.py | .py | """Auth dependencies, CORS parsing, DNS-rebinding guard, and shell-tools gating."""
from __future__ import annotations
import hmac
import ipaddress
import logging
import re
import secrets
import threading
import time
import urllib.parse
from pathlib import Path
from typing import List, Optional
from fastapi import H... | 670 | 24,979 |
Vibe-Trading | agent/src/api/swarm_routes.py | .py | """Swarm HTTP routes.
Mounted by ``agent/api_server.py`` via ``register_swarm_routes(app, ...)``.
"""
from __future__ import annotations
import json
from typing import Any, Awaitable, Callable
from fastapi import Depends, FastAPI, Header, HTTPException, Query, Request
from fastapi.responses import StreamingResponse... | 260 | 10,645 |
Vibe-Trading | agent/src/api/settings_routes.py | .py | """LLM and data-source settings HTTP routes.
Mounted by ``agent/api_server.py`` via ``register_settings_routes(app, ...)``.
"""
from __future__ import annotations
import importlib.util
import json
import os
import sys as _sys
from pathlib import Path
from typing import Any, Awaitable, Callable, Dict, List, Literal, ... | 690 | 25,793 |
Vibe-Trading | agent/src/api/helpers.py | .py | """Path constants, dotenv I/O, SPA deep-link middleware, and path-parameter validation."""
from __future__ import annotations
import os
import re
import tempfile
from pathlib import Path
from typing import Dict
from fastapi import HTTPException, Request, status
from fastapi.responses import FileResponse
from src.ap... | 270 | 9,653 |
Vibe-Trading | agent/src/api/auth_routes.py | .py | """Auth helper routes — short-lived SSE tickets for browser EventSource auth.
Mounted by ``agent/api_server.py`` via ``register_auth_routes(app, ...)``.
A browser ``EventSource`` cannot send an ``Authorization`` header, so instead of
putting the long-lived API key in the SSE URL (where it leaks into browser
history, ... | 56 | 2,190 |
Vibe-Trading | agent/src/api/uploads_routes.py | .py | """Upload and Shadow Account report HTTP routes.
Mounted by ``agent/api_server.py`` via ``register_uploads_routes(app, ...)``.
"""
from __future__ import annotations
import re
import uuid
from pathlib import Path
from typing import Any, Awaitable, Callable
from fastapi import Depends, FastAPI, HTTPException, Upload... | 179 | 6,659 |
Vibe-Trading | agent/src/session/goal_state.py | .py | """Goal-state payload helpers for WebSocket channel adapters."""
from __future__ import annotations
from typing import Any
def goal_state_ws_blob(meta: dict[str, Any] | None = None) -> dict[str, Any]:
"""Build a WebSocket payload for the current active goal state.
The WebSocket gateway stores goal snapshot... | 29 | 1,224 |
Vibe-Trading | agent/src/session/webui_turns.py | .py | """In-process WebUI turn timing helpers for channel adapters."""
from __future__ import annotations
import time
_TURN_STARTED_AT: dict[str, float] = {}
def mark_websocket_turn_started(chat_id: str, started_at: float | None = None) -> float:
"""Record that a WebSocket chat turn started and return its timestamp... | 28 | 869 |
Vibe-Trading | agent/src/session/models.py | .py | """Session data models for the core Session, Message, and Attempt entities."""
from __future__ import annotations
import uuid
from dataclasses import dataclass, field, asdict
from datetime import datetime, timezone
from enum import Enum
from typing import Any, Dict, List, Optional
def _utc_now_iso() -> str:
ret... | 342 | 11,725 |
Vibe-Trading | agent/src/session/store.py | .py | """Filesystem-backed persistence for Session, Message, and Attempt records."""
from __future__ import annotations
import json
import logging
import os
from pathlib import Path
from typing import Any, Dict, List, Optional
from src.session.models import Attempt, Message, Session
logger = logging.getLogger(__name__)
... | 259 | 8,213 |
Vibe-Trading | agent/src/session/__init__.py | .py | """Session management package for conversations, persistence, and SSE streams."""
from src.session.models import Session, Message, Attempt, SessionStatus, AttemptStatus
from src.session.store import SessionStore
from src.session.events import EventBus, SSEEvent
from src.session.service import SessionService
__all__ =... | 19 | 486 |
Vibe-Trading | agent/src/session/search.py | .py | """SQLite FTS5 session search index for cross-session full-text search.
Stores an inverted index of all conversation messages. The primary data
remains in the file-based SessionStore; this module provides a fast search
layer on top.
Database location: ``sessions.db`` under the runtime root (default
``~/.vibe-trading`... | 365 | 12,653 |
Vibe-Trading | agent/src/session/service.py | .py | """Session lifecycle orchestration for message flow, attempt creation, and execution scheduling.
V5: Uses AgentLoop instead of the fixed pipeline behind the generate skill.
"""
from __future__ import annotations
import asyncio
import concurrent.futures
import threading
import time
from datetime import datetime
from ... | 605 | 23,913 |
Vibe-Trading | agent/src/session/events.py | .py | """SSE event bus with support for last_event_id recovery and buffering.
V5: Fixes the thread-safety issue caused by calling queue.put_nowait() on asyncio.Queue from a background thread.
"""
from __future__ import annotations
import asyncio
import json
import logging
import threading
import time
import uuid
logger =... | 265 | 8,635 |
Vibe-Trading | agent/src/utils/media_decode.py | .py | """Media decoding helpers for channel adapters."""
from __future__ import annotations
import base64
import binascii
import re
import uuid
from pathlib import Path
class FileSizeExceeded(ValueError):
"""Raised when a file exceeds the max size limit."""
_DATA_URL_RE = re.compile(r"^data:([^;,]+)((?:;[^,]*)*);bas... | 66 | 1,983 |
Vibe-Trading | agent/src/live/audit.py | .py | """Live-action audit ledger (SPEC.md Consent §5).
Every live action — order placed, order rejected by the gate, mandate committed,
breach raised, kill switch tripped/cleared — appends one immutable record to a
dedicated, append-only ledger at ``<runtime_root>/live/audit.jsonl``. This ledger
is segregated from per-run ... | 352 | 15,373 |
Vibe-Trading | agent/src/live/enforcement.py | .py | """Pre-trade mandate enforcement (SPEC.md Mandate Enforcement §5–§6).
This module owns the broker-agnostic order representation
(:class:`OrderIntent`), the breach contract the consent layer consumes
(:class:`BreachEvent`, SPEC §6 verbatim), and the pure decision function
:func:`check_mandate` that the enforcement gate... | 798 | 31,742 |
Vibe-Trading | agent/src/live/__init__.py | .py | """Live trading channel (Robinhood Agentic Trading).
Bounded-autonomy live execution: the agent trades autonomously inside a
user-committed mandate, on funds ring-fenced in the broker's dedicated
agentic account, with an out-of-band kill switch and a full audit trail.
All live-channel state lives under ``~/.vibe-trad... | 11 | 490 |
Vibe-Trading | agent/src/live/classification.py | .py | """Read/write classification for live-channel remote MCP tools.
We do not own the broker's tool names or schemas — they are discovered at
runtime from a server we do not control and are invite-gated, so classification
must be driven by discovery data plus a maintainer-curated map, never a blind
hardcoded name match th... | 90 | 3,615 |
Vibe-Trading | agent/src/live/registry.py | .py | """Live-broker tool wrapping for the registry (SPEC §7.2 + integration seam).
``build_mcp_tool_wrappers`` returns a plain :class:`~src.tools.mcp.MCPRemoteTool`
for every discovered tool. For a live broker (e.g. Robinhood) that is not safe:
every order-placing (WRITE or UNKNOWN) tool must be re-wrapped in
:class:`~src.... | 229 | 10,025 |
Vibe-Trading | agent/src/live/halt.py | .py | """Kill switch for the live trading channel (SPEC.md Consent §4).
The kill switch is a single, instant, global halt of all live activity. It is
enforced at the filesystem layer — **independent of the LLM cooperating** — via
an out-of-band sentinel file. The enforcement gate (P3) checks
:func:`halt_flag_set` at the top... | 281 | 10,982 |
Vibe-Trading | agent/src/live/daily_count.py | .py | """Per-broker daily order counter (UTC calendar day, atomic write).
Shared by every live order path (the MCP ``LiveOrderGuardTool`` keeps its own
in-class copy for now; the direct-SDK gate uses these helpers). The counter is
advisory defense-in-depth — the broker enforces the real ceiling — so any
read failure reads a... | 135 | 4,342 |
Vibe-Trading | agent/src/live/paths.py | .py | """Filesystem layout for the live trading channel.
All live-channel state is rooted at ``<runtime_root>/live`` (where
``runtime_root`` defaults to ``~/.vibe-trading``, the same root the swarm
config and persistent memory resolve, via :func:`src.config.paths.get_runtime_root`).
Layout (see the live-trading SPEC §2)::
... | 53 | 1,855 |
Vibe-Trading | agent/src/live/sdk_order_gate.py | .py | """Pre-trade mandate gate for DIRECT-SDK connectors (SPEC Mandate Enforcement §3).
The MCP :class:`~src.live.order_guard.LiveOrderGuardTool` gates Robinhood by
wrapping a remote MCP tool. Direct-SDK connectors (tiger / alpaca / okx /
binance / futu) place orders through a normal Python call, not an MCP tool, so
they n... | 727 | 25,212 |
Vibe-Trading | agent/src/live/order_guard.py | .py | """Pre-trade enforcement gate (SPEC.md Mandate Enforcement §3).
:class:`LiveOrderGuardTool` is the dedicated wrapper that owns the live-order
gate. It subclasses :class:`~src.tools.mcp.MCPRemoteTool` and is instantiated
only for a broker's order-placing (WRITE/UNKNOWN) remote tools; every read tool
keeps the untouched... | 831 | 32,468 |
Vibe-Trading | agent/src/live/extractors/__init__.py | .py | """Per-broker order-intent extractors (SPEC.md Mandate Enforcement §4).
Vibe-Trading does not control a broker's tool arg schema, so the enforcement
gate cannot hard-code arg names. Each broker ships an ``extract_order_intent``
function that maps the broker's ``place_order``-style kwargs to the normalized
:class:`~src... | 46 | 1,706 |
Vibe-Trading | agent/src/live/advisory/__init__.py | .py | """Pre-trade advisory interface — observational risk assessments on live orders.
The advisory layer sits **outside** the mandate gate. It provides a
broker-agnostic hook for external services (e.g. invinoveritas ``/review``,
local rule engines, MCP advisory providers) to render a *risk opinion* on a
proposed order. Ad... | 274 | 9,291 |
Vibe-Trading | agent/src/live/advisory/mock.py | .py | """Mock advisory provider for testing.
:class:`MockAdvisory` is a configurable in-memory implementation of
:class:`~src.live.advisory.PreTradeAdvisoryInterface` that records every
invocation and supports deterministic verdict injection, optional delay, and
forced failure — everything a test suite needs to exercise the... | 89 | 3,014 |
Vibe-Trading | agent/src/live/mandate/store.py | .py | """Read-only mandate loader.
This module exposes exactly ONE public function, :func:`load_mandate`. There is
deliberately NO ``save_mandate`` / ``set_mandate`` here or in any module
importable by the agent loop or registered as a tool — mandate writes happen
only in the consent UX commit path (``src.live.mandate.commi... | 133 | 5,305 |
Vibe-Trading | agent/src/live/mandate/model.py | .py | """Mandate data model — the immutable bounded-autonomy contract.
Frozen dataclasses (no Pydantic): the mandate is read once at boot and never
mutated, so plain frozen dataclasses give the strongest immutability guarantee
with zero validation surface the agent could exploit. See
the live-trading SPEC, Mandate §1.
"""
... | 149 | 5,642 |
Vibe-Trading | agent/src/live/mandate/__init__.py | .py | """Bounded-autonomy mandate for the live trading channel.
The mandate is the user-defined safety boundary: quantitative hard caps
(:class:`~src.live.mandate.model.HardCaps`) plus a discovery universe
(:class:`~src.live.mandate.model.UniverseConstraint`) plus consent provenance
(:class:`~src.live.mandate.model.ConsentM... | 10 | 498 |
Vibe-Trading | agent/src/live/mandate/commit.py | .py | """The single mandate writer — the COMMIT half of the consent state machine.
This module is deliberately **not** a tool and **not** importable/registerable
through the agent tool registry (``src.tools.__init__`` only discovers
:class:`~src.agent.tools.BaseTool` subclasses; nothing here subclasses it). It
is a plain fu... | 502 | 21,148 |
Vibe-Trading | agent/src/live/runtime/reconcile.py | .py | """Crash recovery + position reconciliation (SPEC.md §7.5 component 5).
This is the hardest piece of the persistent runtime and has **no reference-agent
analog**. On startup and before every trading tick the runner must answer one
question before it is allowed to trade again: *does broker truth match the
durable last-... | 609 | 24,882 |
Vibe-Trading | agent/src/live/runtime/liveness.py | .py | """Runner liveness for the live runtime (SPEC.md §7.5 #3).
A persistent trading runner must be *detectably* alive. Each runner writes a
heartbeat file (its last-tick epoch-ms timestamp) under ``live_root()/runtime/``
every tick; a stale heartbeat means the process died without cleanup (zombie /
SIGKILL / host crash). ... | 191 | 6,377 |
Vibe-Trading | agent/src/live/runtime/scheduler.py | .py | """Wall-clock scheduler for the live runtime (SPEC.md §7.5 #1).
Follows the reference ``cron/service.py`` shape: an asyncio timer that sleeps until
the earliest ``next_run_at`` across all jobs, fires the due jobs, advances each
fired job's ``next_run_at``, then re-sleeps. The sleep is **capped** at a
re-check interval... | 329 | 11,639 |
Vibe-Trading | agent/src/live/runtime/runner.py | .py | """Persistent live-trading runner loop (SPEC.md §7.5 components 2 + 7).
The runner is the persistent process that turns the interactive consent channel
into an *autonomous* one: it wakes on a schedule / market trigger, decides and
trades inside the committed mandate, sleeps, and survives restarts. This module
implemen... | 798 | 34,210 |
Vibe-Trading | agent/src/live/runtime/flatten.py | .py | """Preemptive kill-switch action: cancel resting orders, then flatten positions.
SPEC.md §7.5 component 6. The filesystem ``HALT`` sentinel (``src.live.halt``)
is the LLM-independent *trigger*; this module is the *action* the runner executes
once a trip is observed. It upgrades the cooperative order-time halt (which o... | 318 | 12,454 |
Vibe-Trading | agent/src/live/runtime/__init__.py | .py | """Persistent live-trading runtime (SPEC.md §7.5).
The runtime makes the "agentic" framing honest: a persistent process that
wakes on a schedule, decides + trades inside the committed mandate, sleeps,
and survives restarts. This package holds the *shell* (scheduler, durable
crash-safe job store, runner liveness); the ... | 14 | 722 |
Vibe-Trading | agent/src/live/runtime/triggers.py | .py | """Live-runtime triggers — when an autonomous tick is due (SPEC §7.5 component 4).
This layers market-session, interval, and event triggers over R1's wall-clock
scheduler. The reference scheduler is time-only; trading additionally needs market-session
awareness ("is the US equity market open right now?") and event-dri... | 348 | 13,190 |
Vibe-Trading | agent/src/live/runtime/jobstore.py | .py | """Durable, crash-safe job store for the live runtime (SPEC.md §7.5 #1).
The scheduler's set of jobs must survive a SIGKILL mid-write: a persistent
trading runner that loses or truncates its job store on a crash would silently
stop watching the mandate's cadence. This store guarantees:
* **Atomic save** — write a tem... | 289 | 10,197 |
Vibe-Trading | agent/src/hypotheses/cli_handlers.py | .py | """CLI handlers for ``vibe-trading hypothesis {list,show,invalidate}``.
All logic lives here; ``agent/cli.py`` only wires this in via :func:`add_subparser`
and :func:`dispatch`. Handlers print to stdout (Rich when available, plain
``print`` fallback) and return an int exit code. Errors are reported as a
one-line stder... | 324 | 10,181 |
Vibe-Trading | agent/src/hypotheses/__init__.py | .py | """Durable research hypothesis registry."""
from src.hypotheses.registry import (
HYPOTHESIS_STATUSES,
Hypothesis,
HypothesisRegistry,
default_hypotheses_path,
)
__all__ = [
"HYPOTHESIS_STATUSES",
"Hypothesis",
"HypothesisRegistry",
"default_hypotheses_path",
]
| 16 | 296 |
Vibe-Trading | agent/src/hypotheses/registry.py | .py | """Pure-code durable research hypothesis registry.
The registry is intentionally small: local JSON storage, deterministic reads,
and no dependency on LLMs or live trading services.
"""
from __future__ import annotations
import hashlib
import json
import os
import re
from dataclasses import asdict, dataclass, field
f... | 387 | 13,908 |
Vibe-Trading | agent/src/skills/ichimoku/example_signal_engine.py | .py | """一目均衡表(Ichimoku Kinko Hyo)信号引擎。
五线系统:转换线/基准线交叉触发,云带位置+方向三重过滤。
纯 pandas 实现,无外部技术分析库依赖。
"""
from typing import Dict, Optional
import pandas as pd
class SignalEngine:
"""一目均衡表信号引擎。
通过 TK 交叉事件触发,三重过滤生成高质量交易信号:
1. 转换线/基准线金叉或死叉(触发条件)
2. 价格相对云带的位置(方向确认)
3. 云带自身方向(趋势确认)
Attributes:
tenk... | 196 | 6,284 |
Vibe-Trading | agent/src/skills/ashare-pre-st-filter/scripts/fetch_sina_penalties.py | .py | #!/usr/bin/env python3
"""新浪财经 A 股监管处罚记录抓取脚本(独立 stdlib 实现)。
用途:为 ashare-pre-st-filter skill 的 E2 证据面提供输入。
数据源:vip.stock.finance.sina.com.cn/corp/go.php/vGP_GetOutOfLine/stockid/<6位>.phtml
解析目标:HTML 表格 <table id="collectFund_1">,每条记录由 <thead>(类型/公告日期) + 4 行 (标题/批复原因/批复内容/处理人) 构成。
安全约束:
- SSRF 防护:仅允许 host == vip.stock... | 628 | 22,705 |
Vibe-Trading | agent/src/skills/elliott-wave/example_signal_engine.py | .py | """艾略特波浪理论信号引擎。
通过 Zigzag 检测 Swing 点,匹配 5 浪推动和 3 浪调整结构,
结合 Fibonacci 浪间关系验证,生成趋势见顶/调整结束信号。
纯 pandas/numpy 实现,无外部波浪库依赖。
"""
from typing import Dict, List, Optional, Tuple
import numpy as np
import pandas as pd
class SignalEngine:
"""艾略特波浪理论信号引擎。
检测流程:
1. Zigzag Swing 点检测(滚动窗口局部极值)
2. 5 浪推动结构匹配 + 三大... | 459 | 15,309 |
Vibe-Trading | agent/src/skills/harmonic/example_signal_engine.py | .py | """谐波形态(Harmonic Patterns)信号引擎。
基于 Fibonacci 几何学派,识别 Gartley/Bat/Butterfly/Crab 等 XABCD 五点形态,
在 PRZ(潜在反转区)生成交易信号。
优先使用 pyharmonics 库,若不可用则回退到内置检测器。
"""
from typing import Dict, List, Optional, Tuple
import numpy as np
import pandas as pd
# --------------------------------------------------------------------------... | 511 | 15,892 |
Vibe-Trading | agent/src/skills/fundamental-filter/example_signal_engine.py | .py | """基本面因子过滤选股信号引擎。
基于 PE/PB/ROE 等财务指标对 A 股进行价值筛选,
满足全部条件的股票等权做多。支持 tushare `extra_fields`
以及 `fundamental_fields` 注入的财务报表字段。
"""
from typing import Dict, List
import numpy as np
import pandas as pd
class SignalEngine:
"""基本面因子过滤信号引擎。
通过 PE/PB/ROE 三重过滤筛选价值股,满足条件的股票等权分配。
Attributes:
pe_min: PE 下... | 169 | 6,060 |
Vibe-Trading | agent/src/skills/vnpy-export/scripts/cta_template.py | .py | """
Vibe-Trading → vnpy export: MA crossover strategy template.
This file is the reference implementation for the vnpy-export skill.
Copy it to your vnpy project's strategies/ folder and adjust parameters.
Requirements:
pip install vnpy vnpy_ctastrategy vnpy_ctp (or vnpy_tts for paper trading)
Usage in vnpy Tra... | 133 | 4,517 |
Vibe-Trading | agent/src/skills/technical-basic/example_signal_engine.py | .py | """技术面基础指标合集信号引擎。
将趋势(EMA/ADX)、均值回归(BB/RSI)、量价(OBV/量比)三维度合并,
通过投票机制生成综合交易信号。纯 pandas 实现,适用于任何 OHLCV 数据。
"""
from typing import Dict
import numpy as np
import pandas as pd
def compute_rsi(close: pd.Series, period: int = 14) -> pd.Series:
"""计算 RSI(Wilder EWM 平滑)。
Args:
close: 收盘价序列。
period:... | 303 | 9,612 |
Vibe-Trading | agent/src/skills/tushare/scripts/fund_data_example.py | .py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
基金数据获取示例脚本
"""
import tushare as ts
import pandas as pd
import os
# 读取环境变量中的token, 或者读取本地记录的token
from src.config.accessor import get_env_config
token = get_env_config().data.tushare_token or ts.get_token()
# 初始化pro接口
pro = ts.pro_api(token)
def get_fund_list():
... | 90 | 2,381 |
Vibe-Trading | agent/src/skills/tushare/scripts/stock_data_example.py | .py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
股票数据获取示例脚本
"""
import tushare as ts
import pandas as pd
import os
# 读取环境变量中的token, 或者读取本地记录的token
from src.config.accessor import get_env_config
token = get_env_config().data.tushare_token or ts.get_token()
# 初始化pro接口
pro = ts.pro_api(token)
def get_stock_list():... | 91 | 2,495 |
Vibe-Trading | agent/src/skills/chanlun/example_signal_engine.py | .py | """缠论形态识别信号引擎。
基于 czsc 库实现缠中说禅理论的买卖点信号生成。
核心链路:K线 → 分型 → 笔 → 中枢 → 买卖点。
"""
from typing import Optional, Dict
from datetime import datetime
import pandas as pd
from czsc import CZSC, RawBar, Freq, ZS
from czsc.signals.cxt import (
cxt_first_buy_V221126,
cxt_first_sell_V221126,
cxt_bi_base_V230228,
cxt... | 226 | 6,734 |
Vibe-Trading | agent/src/skills/okx-market/scripts/candle_data_example.py | .py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""加密货币K线数据获取示例脚本。"""
from typing import Optional
import requests
import pandas as pd
from datetime import datetime
BASE_URL = "https://www.okx.com/api/v5"
CANDLE_COLUMNS = ["ts", "open", "high", "low", "close", "vol", "volCcy", "volCcyQuote", "confirm"]
INDEX_CANDLE_C... | 104 | 3,337 |
Vibe-Trading | agent/src/skills/okx-market/scripts/market_data_example.py | .py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""加密货币行情数据获取示例脚本。"""
from typing import Optional
import requests
import pandas as pd
from datetime import datetime
BASE_URL = "https://www.okx.com/api/v5"
def get_ticker(inst_id: str) -> Optional[dict]:
"""获取单个产品的实时行情。
Args:
inst_id: 交易产品ID,如 BTC-USD... | 113 | 3,335 |
Vibe-Trading | agent/src/skills/event-driven/example_signal_engine.py | .py | """Event-driven example signal engine (sentiment pre-filter / long-only).
Companion to ``fundamental-filter/example_signal_engine.py``. It consumes the
point-in-time-safe ``event_score`` column produced by
:func:`backtest.loaders.rsshub_events.enrich_price_frames_with_events` (set
``event_feeds`` in the backtest confi... | 105 | 3,971 |
Vibe-Trading | agent/src/skills/strategy-dev-manager/templates/factor_signal_engine.py | .py | """Factor SignalEngine template for Strategy Development Manager.
Generated by sdm_register for factor: {FACTOR_NAME}
Source: {SOURCE_PAPER}
Formula: {FORMULA_LATEX}
This template satisfies the backtest runner SignalEngine contract:
- Class named SignalEngine
- No-arg constructor (all params have defaults)
- generate... | 83 | 2,717 |
Vibe-Trading | agent/src/skills/strategy-dev-manager/templates/strategy_signal_engine.py | .py | """Strategy SignalEngine template for Strategy Development Manager.
Generated by sdm_register for strategy: {STRATEGY_NAME}
Source: {SOURCE_PAPER}
Signal definition: {SIGNAL_DEFINITION}
Entry rules: {ENTRY_RULES}
Exit rules: {EXIT_RULES}
Position sizing: {POSITION_SIZING}
This template satisfies the backtest runner ... | 93 | 3,129 |
Vibe-Trading | agent/src/skills/minute-analysis/example_signal_engine.py | .py | """分钟级数据分析工具。
通过 OKX API 获取分钟 K 线,计算 VWAP/TWAP/成交量分布等日内指标。
仅供分析输出,不可用于回测引擎(仅支持日线)。
"""
from typing import Optional
import numpy as np
import pandas as pd
import requests
BASE_URL = "https://www.okx.com/api/v5"
def fetch_minute_candles(
inst_id: str, bar: str = "5m", limit: int = 300
) -> Optional[pd.DataFram... | 147 | 4,400 |
Vibe-Trading | agent/src/skills/sec-edgar/scripts/sec_filings_example.py | .py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""End-to-end SEC EDGAR fetch example.
Resolves a ticker to its CIK, lists recent 10-K filings with their primary
document URLs, and prints a single XBRL us-gaap metric series — all through the
bundled, IP-throttled ``sec_edgar_client`` transport (no API key required).
R... | 162 | 5,339 |
Vibe-Trading | agent/src/skills/multi-factor/zoo_signal_engine.py | .py | """Composite signal engine over Alpha Zoo factors.
Ingests one or more alphas from the Alpha Zoo registry and combines them into
a single signal panel. Unlike ``example_signal_engine`` (per-symbol API that
takes ``dict[code, OHLCV DataFrame]`` and returns ``dict[code, Series]``), this
engine consumes a wide-panel ``di... | 379 | 16,276 |
Vibe-Trading | agent/src/skills/multi-factor/example_signal_engine.py | .py | """多因子截面排名选股信号引擎。
对多只股票计算动量/波动率/量比等因子,截面标准化后综合打分,
选取 TopN 等权做多。纯 pandas 实现。
"""
from typing import Dict, List
import numpy as np
import pandas as pd
def zscore_cross_section(series_map: Dict[str, float]) -> Dict[str, float]:
"""对截面数据做 Z-score 标准化。
Args:
series_map: 标的代码到因子值的映射。
Returns:
... | 203 | 7,208 |
Vibe-Trading | agent/src/skills/volatility/example_signal_engine.py | .py | """波动率策略信号引擎。
基于历史波动率(HV)百分位排名进行均值回归交易:
低波区间做多等待扩张,高波区间做空等待收缩。纯 pandas 实现。
"""
from typing import Dict
import numpy as np
import pandas as pd
def compute_hv(close: pd.Series, window: int = 20, annualize: int = 252) -> pd.Series:
"""计算年化历史波动率。
Args:
close: 收盘价序列。
window: 波动率计算窗口。
an... | 163 | 5,141 |
Vibe-Trading | agent/src/skills/seasonal/example_signal_engine.py | .py | """季节性/日历效应策略信号引擎。
基于月份效应、周内效应等时间规律生成交易信号。
纯 pandas 实现,适用于任何 OHLCV 数据。
"""
from typing import Dict, List
import numpy as np
import pandas as pd
class SignalEngine:
"""季节性日历效应信号引擎。
根据月份和周内效应生成做多/做空信号。
Attributes:
bullish_months: 看多月份列表。
bearish_months: 看空月份列表。
use_weekday: 是否启用... | 146 | 4,943 |
Vibe-Trading | agent/src/skills/pair-trading/example_signal_engine.py | .py | """配对交易策略信号引擎。
基于两个相关标的的价格比值 Z-score 进行均值回归交易。
需要恰好两个标的,等权分配。纯 pandas 实现。
"""
from typing import Dict
import numpy as np
import pandas as pd
class SignalEngine:
"""配对交易信号引擎。
计算两个标的的价格比值,通过 Z-score 判断偏离程度,
偏离过大时反向交易等待回归。
Attributes:
lookback: 均值和标准差回看窗口。
entry_z: 开仓 Z-score 阈值。
... | 153 | 4,851 |
Vibe-Trading | agent/src/skills/cross-market-strategy/example_signal_engine.py | .py | """Cross-market strategy example: vol-adjusted dual-MA with per-market parameters.
Supports any combination of A-shares, crypto, US/HK/Canada equity, forex, and futures.
The CompositeEngine handles calendar alignment, market rules, and shared capital.
"""
import re
import numpy as np
import pandas as pd
# Per-mark... | 83 | 2,993 |
Vibe-Trading | agent/src/skills/candlestick/example_signal_engine.py | .py | """K线形态识别信号引擎。
纯 pandas 向量化实现 15 种经典蜡烛图形态识别:
- 单根形态 (5): 锤子线、倒锤子、射击之星、十字星、纺锤线
- 双根形态 (6): 看涨/看跌吞没、看涨/看跌孕线、刺穿线、乌云盖顶
- 三根形态 (4): 晨星、暮星、三白兵、三乌鸦
信号约定: 1=做多, -1=做空, 0=观望
"""
from typing import Dict
import numpy as np
import pandas as pd
# ---------------------------------------------------------------------------
# 向量... | 591 | 19,762 |
Vibe-Trading | agent/src/skills/eastmoney/scripts/fund_flow_example.py | .py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""资金流向 + 板块联动研究示例。
运行前提:在 agent/ 目录下执行(导入根为 agent/)。无需 token,
所有请求经东方财富共享 IP 限速层节流。
"""
import json
from src.tools.fund_flow_tool import FundFlowTool
from src.tools.sector_tool import SectorInfoTool
def study_main_force(code: str, days: int = 30) -> dict | None:
... | 60 | 1,952 |
Vibe-Trading | agent/src/skills/eastmoney/scripts/screen_search_example.py | .py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""代码搜索 + 全市场选股研究示例。
运行前提:在 agent/ 目录下执行(导入根为 agent/)。无需 token。
所有请求经东方财富共享 IP 限速层节流(按源 IP 限流)。
"""
import json
from src.tools.market_screener_tool import MarketScreenerTool
from src.tools.symbol_search_tool import SymbolSearchTool
def resolve_symbol(query: str, limit... | 55 | 1,784 |
Vibe-Trading | agent/src/skills/eastmoney/scripts/disclosure_example.py | .py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""龙虎榜 + 大宗交易 + 融资融券披露面研究示例。
运行前提:在 agent/ 目录下执行(导入根为 agent/)。无需 token。
所有请求经东方财富共享 IP 限速层节流(按源 IP 限流)。
"""
import json
from src.tools.block_trades_tool import BlockTradesTool
from src.tools.dragon_tiger_tool import DragonTigerTool
from src.tools.margin_trading_tool imp... | 69 | 2,543 |
Vibe-Trading | agent/src/skills/eastmoney/scripts/fundamentals_example.py | .py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""研报舆情 + 跨源财报基本面研究示例。
运行前提:在 agent/ 目录下执行(导入根为 agent/)。无需 token。
研报走东方财富;财报由 get_financial_statements 按市场路由
(美股 SEC EDGAR,A 股/港股东财),并经共享 per-host 限速层节流。
"""
import json
from src.tools.financial_statements_tool import FinancialStatementsTool
from src.tools.research_repo... | 68 | 2,459 |
Vibe-Trading | agent/src/skills/smc/example_signal_engine.py | .py | """Smart Money Concepts (ICT) 信号引擎。
基于 smartmoneyconcepts 库实现机构交易学派的核心分析:
- 结构突破 (BOS) / 性质转变 (ChoCH)
- 公允价值缺口 (FVG)
信号逻辑:ChoCH 优先触发方向,BOS 确认,FVG 同向过滤。
"""
import os
import sys
from typing import Dict, Optional
# smartmoneyconcepts prints emoji on import — force UTF-8 on Windows
if sys.platform == "win32":
os.e... | 191 | 6,241 |
Vibe-Trading | agent/src/goal/models.py | .py | """Data models for finance research goals."""
from __future__ import annotations
from dataclasses import dataclass, field
from enum import Enum
from typing import Any
class GoalStatus(str, Enum):
"""Lifecycle states for a finance research goal."""
ACTIVE = "active"
PAUSED = "paused"
WAITING_USER = ... | 162 | 4,467 |
Vibe-Trading | agent/src/goal/store.py | .py | """SQLite-backed store for finance research goals."""
from __future__ import annotations
import hashlib
import json
import os
import sqlite3
import threading
import uuid
from contextlib import contextmanager
from dataclasses import asdict
from datetime import datetime, timezone
from enum import Enum
from functools im... | 1,022 | 39,082 |
Vibe-Trading | agent/src/goal/policy.py | .py | """Policy helpers for finance research goals."""
from __future__ import annotations
import re
_EXECUTION_PATTERNS = (
re.compile(r"\b(place|submit|execute|send)\b.{0,40}\b(order|trade)\b", re.I),
re.compile(
r"\b(buy|sell|short|long)\b.{0,40}\b(now|immediately|market order|limit order|shares?|contrac... | 49 | 1,378 |
Vibe-Trading | agent/src/goal/__init__.py | .py | """Finance research goal runtime primitives."""
from src.goal.models import (
AuditRow,
EvidenceInput,
EvidenceRecord,
GoalClaim,
GoalCriterion,
GoalRecord,
GoalStatus,
RiskTier,
StaleGoalError,
)
from src.goal.policy import normalize_required_text, reject_live_execution_objective
f... | 31 | 629 |
Vibe-Trading | agent/src/goal/context.py | .py | """Context helpers for session-scoped research goals."""
from __future__ import annotations
from typing import Any
OPEN_CRITERION_STATUSES = {"", "pending", "open", "unsatisfied", "missing", "stale", "too_weak"}
CONTINUABLE_GOAL_STATUSES = {"active", "needs_refresh", "insufficient_evidence"}
DEFAULT_GOAL_CRITERIA ... | 179 | 7,691 |
Vibe-Trading | agent/src/memory/hierarchy.py | .py | """Hierarchical directory routing for memory entries (Tier 2).
Organizes memory files into category subdirectories based on memory_type,
enabling O(category_size) scoped searches instead of O(n) flat scans.
Feature flag: VT_MEMORY_HIERARCHY (default off).
"""
from __future__ import annotations
import logging
import... | 436 | 15,607 |
Vibe-Trading | agent/src/memory/lifecycle.py | .py | """Memory lifecycle management: quality scoring, decay, and garbage collection.
Provides reinforcement learning-style quality updates, Ebbinghaus-inspired
importance decay, and capacity-based garbage collection. All write operations
are guarded by file-level locking (single-writer model).
Feature flags (env vars):
... | 421 | 15,674 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.