Understanding the src Directory Structure in daily_stock_analysis: A Complete Guide
The src/ directory in ZhuLinsen's daily_stock_analysis repository follows a layered architecture with distinct packages for core orchestration (core/), business services (services/), LLM-driven agents (agent/), data repositories (repositories/), and notification utilities, enabling modular end-to-end stock analysis pipelines.
The daily_stock_analysis platform is an open-source Python project that combines traditional quantitative finance with large language model (LLM) reasoning to generate automated market reports. The src/ directory serves as the primary codebase, implementing a clean separation between data pipelines, business logic, AI orchestration, and persistence layers. Below is a comprehensive breakdown of how this directory is organized, including key modules and their interconnections.
Core Orchestration Layer (src/core/)
The core/ package contains pure Python modules that orchestrate the analysis workflow without external service dependencies. These modules expose high-level functions like run_pipeline() that the application entry points invoke.
pipeline.py– Defines the end-to-end analysis pipeline that coordinates data ingestion, market analysis, and report generation.market_strategy.py– Encapsulates logic for generating market-wide trading signals.trading_calendar.py– Provides utilities for handling trading days, holidays, and session windows.backtest_engine.py– Executes historical back-testing of strategies against price data.config_registry.pyandconfig_manager.py– Implement centralized configuration storage and runtime override mechanisms.market_review.py,market_profile.py,market_context.py– Build contextual market snapshots consumed by downstream agents.
These modules form the backbone of the system, ensuring deterministic workflow execution before LLM augmentation occurs.
Data and Schema Definitions (src/data/ & src/schemas/)
Static reference data and type contracts reside in these sub-packages, providing the foundation for type-safe operations across the platform.
In src/data/:
stock_mapping.py– Maintains static mappings between ticker symbols and internal market identifiers.stock_index_loader.py– Loads index-level market data (e.g., CSI 300 constituents).
In src/schemas/:
report_schema.py– Defines Pydantic models that validate the JSON structure of generated reports, ensuring downstream consumers receive consistent payloads.
These layers ensure that services and agents operate on validated, strongly-typed data structures.
Business Services (src/services/)
The services/ package implements functional business capabilities through dependency-injected components. Each service exposes concise Python APIs used by agents and the CLI.
Key services include:
stock_service.py– Fetches real-time and historical stock data from external providers.social_sentiment_service.py– Aggregates social-media sentiment signals for specified tickers.report_renderer.py– Transforms analysis results into Markdown or PDF formats.portfolio_service.py– Handles portfolio CRUD operations, risk calculations, and data import/export.backtest_service.py– Manages back-testing job execution and result aggregation.analysis_service.py– Coordinates market analysis by invoking LLM agents and aggregating their insights into unified reports.agent_model_service.py– Wraps LLM model loading and inference for providers like OpenAI and Claude.history_service.pyandhistory_loader.py– Persist and retrieve historical analysis runs for trend comparison.task_queue.pyandscheduler.py– Orchestrate background asynchronous jobs using a Celery-like execution model.
These modules abstract complex operations into callable units that the agent framework consumes.
Persistence Abstractions (src/repositories/)
The repositories/ package hides file-system and database implementation details from higher-level services, providing clean data access patterns.
stock_repo.py– Persists raw price and fundamental data.portfolio_repo.py– Stores user portfolio snapshots and allocations.analysis_repo.py– Archives analysis results as JSON artifacts.backtest_repo.py– Records back-test outcome tables and performance metrics.
By decoupling persistence logic from business rules, the system allows swapping storage backends without modifying service code.
LLM Agent Framework (src/agent/)
The agent/ directory implements a modular LLM-driven reasoning engine that can be extended with new tools, skills, and strategies.
Execution Engine:
orchestrator.py– Builds task graphs and manages agent execution flow.runner.pyandexecutor.py– Handle tool invocation and LLM response streaming.memory.pyandprotocols.py– Manage short-term memory and inter-agent communication contracts.
Functional Components:
agents/– Contains concrete agent implementations (technical, risk, portfolio, intel, decision).tools/– Houses reusable tool implementations for market data fetching, back-testing, and analysis helpers.strategies/– Implements routing logic that determines which agent to invoke based on context.skills/– Provides low-level skill primitives (base.py,defaults.py,aggregator.py) that agents call.
Example flow: src/agent/agents/technical_agent.py calls src/agent/tools/market_tools.py to retrieve price data, then uses src/agent/llm_adapter.py to query the LLM, returning structured insights that src/services/analysis_service.py incorporates into final reports.
Notification and Utilities
Notification System (src/notification_sender/ & src/notification.py):
The platform supports multi-channel delivery through a unified façade pattern:
notification.py– Provides a genericNotificationFacadethat routes calls to specific senders by channel name.feishu_sender.py– Integrates with Feishu (Lark) corporate messaging.email_sender.py– Handles SMTP email delivery.discord_sender.py– Posts to Discord via webhook.custom_webhook_sender.py– Supports user-defined HTTP endpoints.astrbot_sender.py– Connects to the AstrBot platform.
Utilities (src/utils/):
data_processing.py– Generic ETL helpers for cleaning and normalizing market data.analysis_metadata.py– Attaches timestamps and version tags to analysis runs.
Practical Examples: Working with the Source Code
Running a Full Analysis Pipeline
from src.analyzer import Analyzer
from src.config import Settings
# Load configuration (reads .env automatically)
settings = Settings()
# Create an analyzer instance
analyzer = Analyzer(settings)
# Run the pipeline for a list of tickers
report = analyzer.run(stocks=["600519", "AAPL", "hk00700"])
# The returned dict adheres to src.schemas.report_schema.ReportSchema
print(report["summary"])
Key files referenced: src/analyzer.py, src/config.py, src/core/pipeline.py.
Invoking an LLM Agent Directly
from src.agent.orchestrator import Orchestrator
from src.agent.tools.market_tools import MarketDataTool
orchestrator = Orchestrator()
result = orchestrator.run_agent(
agent_name="technical_agent",
inputs={"ticker": "AAPL", "period": "30d"}
)
print(result["insight"])
Key files referenced: src/agent/orchestrator.py, src/agent/agents/technical_agent.py.
Sending Reports via Feishu
from src.notification import NotificationFacade
from src.notification_sender.feishu_sender import FeishuSender
facade = NotificationFacade()
facade.send(
channel="feishu",
title="Daily Stock Analysis",
markdown=report["markdown"]
)
Key files referenced: src/notification.py, src/notification_sender/feishu_sender.py.
Summary
src/core/houses the workflow orchestration engine, including the mainpipeline.pyandbacktest_engine.py, with no external service dependencies.src/services/implements business logic for stock fetching, sentiment analysis, portfolio management, and LLM model interaction.src/repositories/abstracts data persistence for stocks, portfolios, analysis results, and back-tests.src/agent/provides an extensible LLM framework with agents, tools, strategies, and execution orchestration.src/schemas/andsrc/data/supply type-safe contracts and static reference data.src/notification_sender/decouples report delivery from core logic, supporting Feishu, Email, Discord, and custom webhooks.
Frequently Asked Questions
What is the entry point for running an analysis in daily_stock_analysis?
The primary entry point is src/analyzer.py, which exposes the Analyzer class. This class initializes the configuration from src/config.py and invokes run_pipeline() defined in src/core/pipeline.py. The repository's root main.py (CLI) typically instantiates this analyzer to handle command-line arguments.
How does the agent framework interact with the core pipeline?
The src/services/analysis_service.py acts as the bridge. It receives data from the core pipeline, invokes specific agents through src/agent/orchestrator.py, and aggregates their insights back into the report structure. Agents utilize tools in src/agent/tools/ (like market_tools.py) to fetch data, then call src/agent/llm_adapter.py for inference.
Where are the LLM model configurations and API keys stored?
Configuration is centralized in src/config.py and src/core/config_registry.py. These modules load environment variables from .env files and expose them as Python settings objects. src/services/agent_model_service.py then uses these settings to initialize connections to providers like OpenAI or Claude.
Can I add a new notification channel without modifying the core logic?
Yes. The notification system uses a façade pattern in src/notification.py. You can create a new sender module in src/notification_sender/ (e.g., slack_sender.py) implementing the same interface as feishu_sender.py, then register it in the façade. The core analysis logic in src/core/pipeline.py remains decoupled from delivery mechanisms.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →