AlphaSift

July 3, 2026 · View on GitHub

AlphaSift is an agent-friendly stock discovery and ranking engine. It scans a broad market universe, applies auditable YAML strategies, enriches candidates with optional market context, ranks them with deterministic factors and optional LLM judgment, and saves runs for later T+N evaluation.

This README is the default English version. A Chinese version is available at README.zh-CN.md.

Disclaimer

  • This project is for learning, research, and engineering experiments only.
  • It is not investment advice, a return guarantee, or a buy/sell instruction.
  • Outputs depend on third-party market data, optional LLM providers, local configuration, and strategy parameters. They can be delayed, incomplete, wrong, or unsuitable for real trading.
  • Users are responsible for independent research, compliance checks, transaction costs, liquidity risks, announcement timing, and all resulting decisions.

What AlphaSift does

  • L1 deterministic screening: hard filters and factor scoring over the full market snapshot.
  • L2 optional LLM ranking: structured cross-candidate reasoning, theses, catalysts, risks, confidence, and portfolio risk buckets.
  • L3 pluggable post-analysis: local scorecard by default, with optional DSA or external HTTP analyzers.
  • Hotspot discovery: topic/sector heat ranking, hotspot detail resolution, leader stock fallbacks, cache quality metadata, and history sidecars.
  • Daily feature enrichment: optional candidate-level daily K-line features such as moving averages, MACD/RSI, breakout strength, volume ratio, pullback distance, and platform duration.
  • Evaluation loop: save runs, evaluate later using newer snapshots, deduct transaction cost, tag follow-through / failed-breakout outcomes, review failure samples, and optionally fetch price paths for max drawdown / max favorable excursion.
  • Agent-native interface: SKILL.md describes capabilities and callable interfaces for AI agents.

Quick start

# Install in editable mode
pip install -e .

# Copy configuration template
cp .env.example .env
# Edit .env if you want LLM ranking:
# GEMINI_API_KEY / OPENAI_API_KEY / DEEPSEEK_API_KEY
# or LITELLM_MODEL / LLM_CHANNELS / LITELLM_CONFIG

# List built-in strategies
alphasift strategies

# UI/agent overview: strategy groups, source health, recent runs
alphasift overview --explain

# Local read-only JSON API for dashboards/agents
alphasift serve --host 127.0.0.1 --port 8765

# Run the no-key demo
alphasift quickstart

# Screen without LLM ranking
alphasift screen dual_low --no-llm

# Screen with LLM ranking, if a provider key is configured
alphasift screen dual_low

# Reuse another project's environment file
alphasift --env-file /home/ubuntu/daily_ai_assistant/.env screen balanced_alpha

# Add market or theme context to the LLM prompt
alphasift screen balanced_alpha --context "Brokerage names are seeing volume expansion today."

# Add candidate-level news / announcement / fund-flow context
alphasift screen balanced_alpha --candidate-context-file candidate_context.csv

# Show local L3 scorecard explanations
alphasift screen balanced_alpha --explain

# Add DSA as an optional L3 analyzer; requires DSA_API_URL
alphasift screen dual_low --post-analyzer dsa

# Disable L3 post-analysis explicitly
alphasift screen dual_low --no-post-analysis

# Audit project and strategy configuration
alphasift audit

# Save a run and generate a Markdown review report
alphasift screen dual_low --no-llm --save-run
alphasift runs --json
alphasift report <run_id> --output data/reports/dual_low.md

Example output shape:

$ alphasift screen dual_low --no-llm
Universe 5190 -> filtered 337 -> output Top 5
rank  code    name       score  price   change   pe     pb
1     002039  黔源电力   72.7   20.72   -2.49%   14.76  1.99
2     002444  巨星科技   71.0   30.82   +0.29%   14.59  1.95
3     002128  电投能源   70.9   31.60   -2.41%   14.00  1.90

Screening examples

The following recorded examples were run on April 12, 2026, using the previous trading day's A-share close data from April 10, 2026. LLM ranking was disabled with --no-llm; these rows are examples of engine output, not recommendations.

Dual Low

Full market 5190 stocks -> 337 after hard filters -> Top 5 output.

RankCodeNameScorePriceChangePEPB
1002039黔源电力72.720.72-2.49%14.761.99
2002444巨星科技71.030.82+0.29%14.591.95
3002128电投能源70.931.60-2.41%14.001.90
4002236大华股份70.817.43+1.04%14.861.50
5600583海油工程68.97.02+4.15%14.891.17

Volume Breakout

Full market 5190 stocks -> 126 after hard filters -> Top 5 output.

RankCodeNameScorePriceChange
1002837英维克74.099.05+6.40%
2688183生益电子73.895.30+7.09%
3300803指南针73.3101.68+3.07%
4002384东山精密73.0143.55+8.83%
5300277汽轮科技73.019.74+5.73%

Hotspot workflow

AlphaSift can discover current market hotspots and resolve a specific topic into a detail payload with raw timeline evidence, compact display-ready route events, leader stocks, source confidence, stale/fallback metadata, and quality diagnostics.

# Discover hotspot topics and write schema_version=2 cache/history sidecars
alphasift hotspots --provider akshare --top 12 --output data/hotspots.json --history data/hotspot.history.jsonl --explain

# Inspect a single hotspot topic
alphasift hotspot "AI compute" --top-stocks 10 --timeline --fallback-cache data/hotspots.json --explain

# Safe offline/no-network check
alphasift hotspots --provider none --explain

Hotspot cache files include:

  • schema_version: currently 2
  • generated_at
  • metadata: provider, row count, source errors, stale/fallback state
  • hotspots: normalized topic rows
  • sidecars such as *.meta.json and JSONL history when requested

Leader stock fallbacks are intentionally explicit. When live constituent APIs fail and AlphaSift uses last-good/cache leaders, returned stocks carry fields such as source="last_good_cache.leader_stocks", source_confidence, and fallback_used=true instead of pretending to be live provider data.

Hotspot details keep the raw timeline for auditability and also expose a compact route list for applications. route is grouped by day, newest first, trimmed for UI display, and falls back to a short current heat/stage/leader summary when no timeline evidence is available.

Python API

from alphasift import screen

result = screen("dual_low", use_llm=False)
for pick in result.picks:
    print(f"{pick.rank}. {pick.code} {pick.name} score={pick.final_score:.1f}")

Saved-run evaluation helpers are also exported:

from alphasift import evaluate_saved_run, evaluate_saved_runs

Configuration

AlphaSift is designed to reuse LiteLLM-style configuration used by daily_stock_analysis and similar projects.

VariableRequiredDescriptionDefault
LITELLM_MODELRecommendedMain model in provider/model formatgemini/gemini-2.5-flash
LITELLM_FALLBACK_MODELSNoComma-separated fallback models-
LLM_CHANNELSNoMulti-channel provider config using LLM_{NAME}_*-
LITELLM_CONFIGNoLiteLLM Router YAML file-
GEMINI_API_KEY / OPENAI_API_KEY / DEEPSEEK_API_KEYFor LLM rankingProvider API key-
OPENAI_BASE_URL / OLLAMA_API_BASENoOpenAI-compatible or Ollama endpoint-
LLM_MAX_TOKENSNoMax tokens requested from LLM ranking; keeps local servers from generating unbounded output after client timeout2048
LLM_CONTEXTNoExtra market/theme context for LLM ranking-
LLM_CANDIDATE_CONTEXT_ENABLEDNoFetch candidate news/announcements/fund-flow context by defaultfalse
INDUSTRY_MAP_FILESNoLocal code-to-industry/concepts/board-heat files-
INDUSTRY_PROVIDERNoOptional board/industry provider such as aksharenone
SNAPSHOT_SOURCE_PRIORITYNoSnapshot source orderDepends on Tushare token
SNAPSHOT_FALLBACK_MAX_AGE_HOURSNoMax acceptable age for last-good snapshot fallback; empty disables the guard-
ALPHASIFT_SOURCE_CALL_TIMEOUT_SECNoGlobal caller-side timeout for third-party wrapper data-source calls; 0/off disables-
ALPHASIFT_SNAPSHOT_CALL_TIMEOUT_SECNoSnapshot wrapper timeout for efinance/akshare_em/tushare60
ALPHASIFT_DAILY_CALL_TIMEOUT_SECNoDaily wrapper timeout for akshare/baostock/tushare/yfinance20
ALPHASIFT_EASTMONEY_MIN_INTERVAL_SECNoMinimum interval for direct Eastmoney HTTP calls1.0
ALPHASIFT_EASTMONEY_JITTER_SECNoRandom jitter added to the Eastmoney interval0.3
TUSHARE_TOKEN / TUSHARE_API_TOKENFor TushareTushare Pro token-
POST_ANALYZERSNoL3 analyzers; set none to disablescorecard
DSA_API_URLFor DSA analyzerDSA service URL or full analysis endpoint-
DAILY_ENRICH_ENABLEDNoEnable candidate-level daily K-line enrichmentfalse
DAILY_SOURCENoDaily K-line source: auto, tencent, sina, akshare, baostock, or tushareauto
ALPHASIFT_DATA_DIRNoRun records, caches, and evaluation results./data
STRATEGIES_DIRNoCustom strategy directoryauto-detect

Example multi-channel LiteLLM config:

LLM_CHANNELS=primary
LLM_PRIMARY_PROTOCOL=openai
LLM_PRIMARY_BASE_URL=https://api.deepseek.com/v1
LLM_PRIMARY_API_KEYS=sk-xxx,sk-yyy
LLM_PRIMARY_MODELS=deepseek-chat,deepseek-reasoner
LITELLM_MODEL=openai/deepseek-chat
LITELLM_FALLBACK_MODELS=openai/gpt-4o-mini,anthropic/claude-3-5-sonnet

Example single-provider config:

GEMINI_API_KEY=...
LITELLM_MODEL=gemini/gemini-2.5-flash

You can load external .env files repeatedly:

alphasift --env-file /path/to/daily_stock_analysis/.env \
  --env-file /path/to/daily_ai_assistant/.env \
  screen balanced_alpha

For the full configuration reference, see docs/configuration.md.

Data sources

AlphaSift supports multiple A-share market snapshot sources and automatically falls back by priority.

Default without Tushare token:

sina -> efinance -> akshare_em -> em_datacenter

Default with TUSHARE_TOKEN / TUSHARE_API_TOKEN and no manual priority override:

tushare -> sina -> efinance -> akshare_em -> em_datacenter
SourceBackendNotes
sinaSina Finance Market CenterDirect HTTP full-market source with PE/PB/turnover/market-cap fields
efinanceEastmoney push2Fast during live sessions
akshare_emEastmoney push endpoint via AkShare-style accessBackup live source
em_datacenterEastmoney Data CenterOften available outside trading hours
tushareTushare Pro daily + daily_basicRequires token; previous/nearest trading day data

Daily K-line enrichment defaults to DAILY_SOURCE=auto. The auto chain uses tushare -> tencent -> sina -> akshare -> baostock when a Tushare token is configured, otherwise tencent -> sina -> akshare -> baostock. Tencent is a direct HTTP K-line source with no wrapper dependency and is preferred over Eastmoney-heavy wrapper paths for candidate-level history enrichment; Sina provides a second direct HTTP fallback before wrapper sources. Repeatedly failing sources are temporarily skipped, and expired daily cache can be used as a marked stale fallback when every live daily source fails.

Source support matrix:

CapabilityPrimary chainFields
Daily K-line enrichmenttushare when token exists, then tencent, sina, akshare, baostock with health-aware auto reorderingOHLCV, qfq where supported, technical factors, 20d volatility/ATR/drawdown controls, per-row daily_source provenance, daily_quality_score/flags, source-health stats; low-quality/fetch-failed/stale rows feed the final risk overlay
Full-market snapshotsina, then efinance, akshare_em, em_datacenter; tushare first when token existsprice, change, amount, market cap, PE/PB, turnover
Candidate contextnews, fund_flow, announcement, quotenews, announcements, fund flow, Tencent quote valuation/turnover
Last-good fallbackdaily history cache and snapshot cachemarked with stale/fallback attrs when live sources fail

If a source is unavailable, times out, or lacks fields required by a strategy, AlphaSift skips it and tries the next source. Direct HTTP sources use request timeouts; third-party wrapper calls such as efinance, AkShare, Baostock, Tushare, and yfinance also have caller-side timeouts inspired by adjacent provider-manager projects, so a stuck wrapper cannot block the whole run indefinitely. Eastmoney-only HTTP fallbacks use a shared retrying session with serial throttling and jitter, following the same anti-ban pattern documented by a-stock-data; tune ALPHASIFT_EASTMONEY_MIN_INTERVAL_SEC upward for batch runs on sensitive networks. If all live sources fail, the last-good snapshot fallback is explicitly marked as stale/fallback data; SNAPSHOT_FALLBACK_MAX_AGE_HOURS can reject overly old fallback cache to avoid repeating stale selections.

Built-in strategies

StrategyTypeDescription
dual_lowValueLow PE + low PB defensive value screen
blue_chip_incomeIncomeHigh-liquidity blue-chip and dividend-quality defensive screen
volume_breakoutTrendVolume expansion and resistance breakout
quality_valueValueReasonable valuation, liquidity, and controlled volatility
low_volatility_qualityQualityDefensive quality screen using daily volatility, drawdown, ATR, and data-quality controls
capital_heatMomentumActive capital flow without extreme overheating
oversold_reversalReversalRepair candidates with controlled drawdown and still-valid liquidity
balanced_alphaFrameworkGeneral multi-factor discovery strategy
momentum_qualityFrameworkTrend confirmation plus quality filters
shrink_pullbackTrendPullback into support during a broader uptrend; uses daily enrichment

Use alphasift overview --json/--explain for one UI/agent payload that combines strategy groups, strategy facets, strategy cards, optional strategy recommendations, data-source health_summary, strategy coverage, data-source history, saved-evaluation performance, recent runs, and next actions. Use alphasift serve for a local read-only JSON API with /health, /result-schema, /overview, /strategies, /strategy?name=<strategy_name>, /strategy-compare?base=<base>&target=<target>, /strategy-facets, /strategy-cards, /strategy-readiness, /strategy-run-summary, /data-source-history, /strategy-performance, /strategy-templates, /strategy-template?name=<template_name>, /runs, /report?run=<run_id>, and /doctor/data-sources endpoints. Use alphasift strategies --json or alphasift strategies --explain to inspect strategy style, data requirements, active filters, factor weights, and profile overrides. Add matching flags such as --risk-profile defensive --holding-period swing --strict --json when a UI or agent needs ranked strategy recommendations, or --compare dual_low low_volatility_quality --json / /strategy-compare when reviewing strategy parameter drift. Use /strategy-facets when a UI needs filter values, counts, and backing strategy names for category, tag, style, data-requirement, and required-field controls. Use /strategy-cards when a UI needs one card per strategy with catalog metadata, readiness state, saved-run history, saved-evaluation performance, top factors, next actions, and lanes for needs-history, needs-evaluation, performance leaders, and attention. Use /strategy-readiness when a UI needs ready/attention/unchecked counts and missing-field impacts before live screening. Use /strategy-run-summary when a UI needs saved-run history by strategy without evaluating against live quotes, /data-source-history when it needs recent snapshot-source error/degradation/fallback rates, samples, stability status, and next actions from saved-run metadata, and /strategy-performance when it needs saved-evaluation return/win-rate leaderboards without re-running live evaluation. Use alphasift strategies --templates --explain and alphasift strategies --template <name> to start from reusable strategy authoring templates. Use alphasift doctor data-sources --all-strategies --explain to inspect the cross-strategy data-source field coverage matrix, source health_summary, and live snapshot quality_summary before relying on live screening. Add custom YAML strategies under strategies/. See docs/strategy-guide.md.

Project layout

alphasift/
├── SKILL.md                 # Agent skill description and callable interface
├── README.zh-CN.md          # Chinese README
├── strategies/              # Strategy YAML files
├── docs/
│   ├── configuration.md     # Configuration reference
│   ├── design.md            # Design principles
│   ├── positioning.md       # Product positioning
│   ├── reference.md         # Structure, boundaries, observed runs
│   ├── scoring.md           # Scoring details
│   ├── strategy-guide.md    # Strategy authoring guide
│   └── usage.md             # Usage guide
└── alphasift/               # Python package
    ├── cli.py               # CLI entry point
    ├── config.py            # Environment configuration
    ├── context.py           # LLM context assembly
    ├── candidate_context.py # Candidate news/announcement/fund-flow context
    ├── daily.py             # Daily K-line feature enrichment
    ├── hotspot.py           # Hotspot discovery/detail/cache contract
    ├── industry.py          # Industry/concept/board heat mapping
    ├── models.py            # Data models
    ├── snapshot.py          # Market snapshot loading and fallback
    ├── filter.py            # L1 hard filters
    ├── scorer.py            # Factor scoring
    ├── ranker.py            # L2 LLM ranking
    ├── risk.py              # Independent risk layer
    ├── post_analysis.py     # L3 post-analysis plugins
    ├── dsa.py               # Optional DSA integration
    ├── store.py             # Run persistence
    ├── overview.py          # UI/agent overview payload
    ├── evaluate.py          # T+N evaluation
    ├── pipeline.py          # Main orchestration
    └── strategy.py          # Strategy YAML loader

Relationship with daily_stock_analysis

daily_stock_analysis (DSA) is an external single-stock deep-analysis service. AlphaSift is upstream: it discovers and ranks candidates across the market. DSA is downstream: it can analyze a small final shortlist in depth.

  • AlphaSift does broad discovery, deterministic scoring, LLM ranking, hotspot analysis, and saved-run evaluation.
  • DSA does individual stock deep analysis through its own API, usually POST /api/v1/analysis/analyze.
  • The integration is optional and configured through DSA_API_URL.
  • To control cost and latency, AlphaSift only calls DSA for final selected candidates.
  • The default L3 analyzer is local scorecard; DSA and external HTTP analyzers are optional.

Known limitations

  • Strategies that depend on daily K-line features enrich only the L1 top candidates, not the entire historical market.
  • AlphaSift is not a full backtesting engine or portfolio execution system.
  • DSA post-analysis is synchronous and better suited to low-frequency final-candidate review.
  • Tushare fallback depends on the user's own token, point balance, and permissions.
  • T+N evaluation compares saved run prices with later snapshots; it is not a rigorous event-study backtest and does not model dividends, suspensions, slippage, or rebalancing constraints.
  • The repository keeps both strategies/ and alphasift/strategies/ mirrors for development and packaged usage; built-in strategy files should stay in sync.

Verification

Last recorded full-suite check:

$ python -m pytest -q
176 passed, 1 skipped in 1.56s

Documentation

License

Apache License 2.0