Daily Stock Analysis

repository·main·Indexed 13 days ago

https://github.com/zhulinsen/daily_stock_analysis

An AI-powered intelligent stock analysis system for A-shares, Hong Kong, US, Japan, Korea, and Taiwan markets. It automatically analyzes stocks and pushes 'Decision Dashboards' and 'Market Reviews' to platforms including WeChat, Feishu, Telegram, Discord, Slack, and Email. Features include a Web UI for configuration and monitoring, an Agent-based strategy querying system supporting technical theories like Chan and Wave Theory, and the ability to define custom trading strategies via YAML Strategy Skills.

Tokens
140.1K
Snippets
306
Records
597
Agent score
98%

What's inside Daily Stock Analysis

  1. Configure LLM (Large Language Model) access

    main

    The project provides a unified AI model access experience supporting official APIs, OpenAI-compatible platforms, and local models. It is powered by LiteLLM.

    Users can choose from three configuration priority levels depending on their needs:

    1. Simple Model Configuration: For beginners who want the quickest setup.
    2. Channel (Channels) Mode Configuration: For advanced users managing multiple API keys, fallback models, or custom Base URLs.
    3. YAML Advanced Configuration: For power users requiring complex load balancing, request routing, or multi-platform high availability.

    Important Compatibility Notes:

    • Dependency Boundary: The system uses litellm>=1.80.10,!=1.82.7,!=1.82.8,<2.0.0.
    • Rollback Path: If a configuration fails, use your .env backup or the POST /api/v1/system/config/import endpoint to restore settings. You can manually refill keys like LITELLM_MODEL, LLM_*, AGENT_LITELLM_MODEL, VISION_MODEL, LLM_TEMPERATURE, or LLM_USAGE_HMAC_* before restarting.
  2. Navigate the Daily Stock Analysis documentation

    main

    The documentation for daily_stock_analysis is organized by user intent. Use the following paths to find specific guidance:

    Getting Started

    • Project Overview: See README.md for core capabilities and quick start.
    • Beginner Setup: For non-coders using the desktop client, see beginner-client-setup.md (covers client download, model configuration like Anspire Open/AIHubMix, and news source setup).
    • Full Configuration & Deployment: For comprehensive environment preparation and running modes, see full-guide.md.

    Configuration Tasks

    • LLM (Large Language Models):
      • General LLM configuration: LLM_CONFIG_GUIDE.md.
      • Specific provider presets and error diagnosis: llm-providers.md.
      • Multi-channel LiteLLM examples: examples/litellm_config.example.yaml.
    • Notifications: Configure channels like WeChat Work, Feishu, Telegram, Discord, Slack, or Email via notifications.md.
    • Stock Data: For Tushare-specific stock list configuration, see TUSHARE_STOCK_LIST_GUIDE.md.

    Advanced Usage & Features

    • Bots & IM Integration: Learn about Bot commands, Webhooks, and platform-specific setup (Feishu, DingTalk, Discord) in bot-command.md and the bot/ directory.
    • Real-time Alerts: Manage rules and notification cooling states in alerts.md.
    • Decision Signals: Understand AI suggestion fields and risk linkage in decision-signals.md.
    • Intelligence Sources: Configure RSS/Atom news feeds in intelligence-sources.md.

    Deployment & Development

    • Deployment: Options include Server, Docker, systemd, or Supervisor via DEPLOY.md. For cloud-specific deployment, see deploy-webui-cloud.md or docker/zeabur-deployment.md.
    • Desktop Packaging: Instructions for Electron and Web build artifacts are in desktop-package.md.
    • API Reference: The FastAPI OpenAPI specification is available at architecture/api_spec.json.
    • Troubleshooting: Check FAQ.md for common issues or data-source-stability.md for data source fallback and failure handling.
  3. Understand the Project Structure

    main

    The project is organized into several key modules. Use main.py as the primary entry point. The core logic resides in src/, including analyzer.py for AI analysis, config.py for settings, and notification.py for alerts. Data acquisition is handled by data_provider/, while the api/ directory contains the FastAPI backend service. Frontend applications are located in apps/dsa-web/.

    daily_stock_analysis/
    ├── main.py              # Main entry point
    ├── src/                 # Core business logic
    │   ├── analyzer.py      # AI analyzer
    │   ├── config.py        # Configuration management
    │   ├── notification.py  # Message push notifications
    │   └── ...
    ├── data_provider/       # Multi-source data adapters
    ├── bot/                 # Bot interaction module
    ├── api/                 # FastAPI backend service
    ├── apps/dsa-web/        # React frontend
    ├── docker/              # Docker configuration
    ├── docs/                # Project documentation
    └── .github/workflows/   # GitHub Actions
  4. Overview of LLM Configuration Methods

    main

    The project provides a unified AI model access flow powered by [LiteLLM], supporting official APIs, OpenAI-compatible platforms, and local models. Users can choose from three configuration tiers based on their needs:

    1. Simple Model Config (Beginners): For users who want to get the system running quickly with minimal setup.
    2. Channels Mode Config (Advanced Users): For users managing multiple API keys, fallback models, and custom Base URLs.
    3. Advanced YAML Config (Veterans): For complex requirements like load balancing, request routing, and high availability.

    For specific provider presets, GitHub Actions variable mapping, and troubleshooting details.reason errors, refer to the Provider Configuration Guide.

  5. Understand the Output Formats

    main

    The system generates automated reports which are typically pushed via notification channels. The two primary report types are:

    1. Decision Dashboard (决策仪表盘): Provides a summary of analyzed stocks with buy/hold/sell signals, scores, and sentiment (e.g., bullish/bearish). It includes detailed sections for each stock covering:

      • News Summary: Sentiment and fundamental performance expectations.
      • Risk Alerts: Specific risk points like capital outflow or chip concentration.
      • Positive Catalysts: Growth drivers like industry positioning or profit growth.
      • Latest Dynamics: Recent news updates.
    2. Market Review (大盘复盘): Provides a summary of the overall market, including:

      • Major Indices: Performance of indices like SSE, SZSE, and ChiNext.
      • Market Overview: Number of advancing/declining stocks and limit-up/limit-down counts.
      • Sector Performance: Leading and lagging sectors.
  6. Understand Field Quality Status in AnalysisContextPack

    main

    The AnalysisContextPack uses specific status terms to describe the quality of data fields or data blocks. These statuses describe the state of the data itself, not whether the business process (like an analysis) succeeded.

    Available Statuses:

    • available: Field exists, source and timestamp are interpretable, and the current path is usable (e.g., real-time price is present).
    • missing: The current path requires this field, but it was not retrieved or is empty (e.g., no recent daily line in DB).
    • not_supported: The current market, data source, or path does not support this field (e.g., a market without chip distribution).
    • fallback: The preferred source was unavailable, so a backup source or older path was used (e.g., falling back from real-time price to historical close).
    • stale: The field exists, but the data freshness is insufficient (e.g., price_stale or fx_stale).
    • estimated: The field is an estimated value and should not be treated as a complete fact (e.g., technical estimates generated from real-time prices).
    • partial: The data block is partially available and partially missing (e.g., data_quality=partial).
    • fetch_failed: The current path attempted to fetch the data, but the fetch failed (e.g., fundamental_context.status == "failed").
  7. Understand LLM configuration priority

    main

    The system follows a strict hierarchy for LLM configuration. If a higher-priority method is detected, lower-priority methods are ignored.

    Priority Order (Highest to Lowest):

    1. YAML Configuration: Using LITELLM_CONFIG or LITELLM_CONFIG_YAML.
    2. Channel Mode: Using LLM_CHANNELS to define multiple providers/keys.
    3. Simple Model Mode: Providing a single model name directly.

    Note: If you want to use multiple keys or fallback providers, you must use Channel Mode or YAML. Mixing Simple Model settings with Channel Mode settings will result in the Simple settings being ignored.

  8. Access the AnalysisContextPack overview in reports

    main

    The system provides a low-sensitivity summary of the data used for analysis via report.details.analysis_context_pack_overview. This is useful for verifying data coverage without exposing raw payloads or sensitive LLM prompts.

    Key features:

    • Web UI: Displays a collapsible summary after the 'Strategy Points' and 'News' sections. It shows counts of available, missing, and other status items.
    • API Behavior: The details.context_snapshot field in API responses will strip out the analysis_context_pack_overview to prevent redundant data in transparency panels.
    • Persistence: This overview is derived from the analysis_history.context_snapshot. If SAVE_CONTEXT_SNAPSHOT is set to false, the overview may not be available for historical records.

    What is NOT included in the overview:

    • Full AnalysisContextPack or raw analysis_context_pack_summary prompt strings.
    • items.value (actual data values).
    • Full news content, trend results, or raw fundamental/chip payloads.
  9. Understand Runtime Consumption of AnalysisContextPack Summary

    main

    In the runtime (P3), the full AnalysisContextPack is not exposed to downstream consumers like analyzers or agents. Instead, they consume a low-sensitivity version called analysis_context_pack_summary.

    Summary Content

    The analysis_context_pack_summary is a string generated via format_analysis_context_pack_prompt_section(). It is restricted to metadata and status indicators to prevent leaking large raw payloads. It includes:

    • subject
    • pack_version
    • Block status, source, warnings, and missing_reason
    • metadata.news_result_count
    • data_quality.warnings
    • P5 low-sensitivity data constraints

    It specifically excludes raw payloads such as news.content, trend_result, chip, or fundamental_context.

    Integration in Agent Paths

    • AgentExecutor: Inserts the summary after the market phase segment but before pre-fetched JSON.
    • AgentOrchestrator: Places the summary in ctx.meta["analysis_context_pack_summary"]. It is forbidden to write this to ctx.data.
    • BaseAgent: Inserts the summary after the market phase user message but before _inject_cached_data().
    • Data Access: Agents may attempt to read storage.get_analysis_context() for daily_bars status. This is a fail-open operation; if it fails, it simply marks daily_bars_missing without writing raw payloads to the context.
  10. Understand the Screening Engine caching and persistence model

    main

    The screening engine uses a multi-layered caching strategy to ensure availability even when real-time data sources fail. Data is stored in data/screening/ or managed via DataFetcherManager and SearchService with specific TTLs (Time To Live) and fallback behaviors.

    Cache Locations and Behaviors

    Data TypeLocation / ManagerTTL / Behavior
    Market Snapshotdata/screening/snapshot.last_good.jsonReused within 5 mins without fallback marker. If expired and real-time sources fail, falls back to the last good snapshot marked as stale/fallback.
    Daily K-Linedata/screening/daily_history/Keyed by code, source, and lookback window. Default TTL 24h. Falls back to expired cache if real-time sources fail (marked stale).
    Industry/Concept Mappingdata/screening/industry_provider_cache/Default TTL 24h. Includes history for trend calculation.
    Hotspots (List & History)data/screening/hotspots.json, hotspot.history.jsonlExplicit refresh. Falls back to the most recent available snapshot on real-time failure.
    Hotspot Detailsdata/screening/hotspot_details/Default TTL 30 mins. Only caches structured basic details. Falls back to expired details with stale duration on failure.
    Real-time QuotesDataFetcherManagerDefault TTL 10 mins (uses REALTIME_CACHE_TTL).
    Fundamentals/Fund FlowDataFetcherManagerDefault TTL 120 seconds (uses FUNDAMENTAL_CACHE_TTL_SECONDS).
    News/AnnouncementsSearchService (Memory)Default TTL 10 mins. Concurrent requests for the same topic are merged in the parent process.
    Full Screening ResultsDSA Database screening_runs tableWritten idempotently by run_id upon completion. Database write failures do not block the main screening process.

    Note: The engine avoids redundant requests by using DSA's native news, fundamental, and real-time quote pipelines instead of independent scraping.

  11. Understand Strategy Deliberation modes (v0 to v4)

    main

    Deliberation is an optional process triggered by high-severity conflicts. It aims to resolve disagreements through structured reasoning.

    Available Modes:

    • mediator_v0 (Baseline): Deterministic. Converts conflicts into auditable agendas. Only allows unchanged or softened (reducing confidence or intensity, e.g., strong_buy $\rightarrow$ buy) revisions. Prohibits reversing signals.
    • llm_mediator_v1: An LLM-enhanced mode. It uses the v0 agenda but allows an LLM to suggest revisions. Must pass strict schema guards (no new participants, no signal reversals) or it falls back to v0.
    • self_review_v2: An agent-driven mode where individual strategy agents review the baseline deliberation. Each agent only responds to its own assigned agenda/skill. Falls back to baseline on any error.
    • multi_round_v4: A configurable multi-round mode. Can run up to 4 rounds. It uses a fallback mode (v0, v1, or v2) and stops when stable or when max_rounds is reached. Each round must follow the same strict revision rules (no reversals, no increasing confidence).

    Revision Projection (v3)

    When deliberation is present, a revision_projection block is generated. This is a preview only (mode: "preview_only") that shows what the final_signal would look like if all softened revisions were applied. It never overrides the authoritative final_signal.

  12. Adhere to the 9 Strategy Invariants

    main

    All implementations of the multi-strategy contract must satisfy these nine invariants to prevent contract breakage:

    1. I-1 Evidence Chain Exclusivity: Every item in the Evidence Chain must be valid (is_valid_strategy_signal == True).
    2. I-2 No Silent Conversion: Unrecognized signals must go to Diagnostics, never converted to hold within the Evidence Chain.
    3. I-3 Zero Evidence $\rightarrow$ insufficient: If valid count is 0, or sum(confidences) == 0, final_signal must be hold and consensus_level must be insufficient.
    4. I-4 Single Sample $\rightarrow$ insufficient: Exactly 1 valid opinion always results in insufficient consensus.
    5. I-5 Hold-final Consistency: If final_signal is hold, all hold valid opinions must be in supporting_skills.
    6. I-6 Payload/Renderer Parity: The text rendered in UI (Markdown, WeChat, etc.) must match the strategy_synthesis payload exactly.
    7. I-7 Canonical-First Scoring: All internal scoring and conflict detection must use the canonical lowercase values from normalize_strategy_signal().
    8. I-8 Multi-language Empty Placeholders: Use labels.none_label for empty skill lists; do not hardcode strings like "None" or "无".
    9. I-9 Deliberation Monotonic Conservatism: Deliberation must only result in softened or unchanged states. It must never reverse a signal or increase confidence/adjustment values beyond the baseline.