What External Libraries Does daily_stock_analysis Depend On? Complete Dependency Guide

The daily_stock_analysis project depends on 35+ external Python libraries declared in requirements.txt, spanning market data providers (efinance, akshare, tushare), AI/LLM orchestration (litellm, tiktoken), web APIs (FastAPI, uvicorn), and enterprise notification SDKs (lark-oapi, dingtalk-stream).

The daily_stock_analysis repository is a Python-based quantitative platform for A-share, HK, and US stock analysis. Its third-party dependencies are strictly organized by functional domain in requirements.txt, allowing the modular architecture to swap data sources, LLM providers, and notification channels without touching core business logic.

Core Runtime and Configuration Libraries

The foundation layer handles environment management, database persistence, job scheduling, and resiliency patterns.

python-dotenv (>=1.0.0, line 6) loads configuration from .env files. In src/config.py and main.py, the code calls dotenv_values to read API keys and database URLs without hard-coding secrets.

tenacity (>=8.2.0, line 7) provides exponential back-off for transient failures. Data-provider wrappers in data_provider/ use the @retry decorator to recover from network blips when scraping real-time quotes.

SQLAlchemy (>=2.0.0, line 8) acts as the ORM layer. The repository pattern in src/repositories/stock_repo.py defines models and database sessions using SQLAlchemy 2.0 syntax, abstracting SQLite (or PostgreSQL) interactions.

schedule (>=1.2.0, line 9) enables cron-like job execution. src/scheduler.py builds recurring tasks based on the configured run time, triggering analysis pipelines at market open or close.

exchange-calendars (>=4.5.0, line 10) supplies trading-day logic. src/core/trading_calendar.py imports this library to determine whether today is a valid trading session for A-shares, HKEX, or NASDAQ before running data ingestion.

Data Source Adapters (Multi-Provider Strategy)

The platform implements a priority-ordered failover chain for market data, declared in requirements.txt lines 13-20.

AI and LLM Integration Stack

The analyzer module relies on a unified LLM client to generate natural-language recommendations.

litellm (>=1.80.10,<1.82.7, line 35) provides a single interface for OpenAI, Gemini, Anthropic, and other providers. src/analyzer.py imports litellm.completion to route requests based on the LITELLM_CONFIG environment variable.

tiktoken (>=0.8.0,<0.12.0, line 36) counts tokens before sending prompts. The same src/analyzer.py file uses tiktoken.encoding_for_model to truncate context windows and avoid rate-limit errors.

openai (>=1.0.0, line 37) is imported explicitly for direct ChatCompletion calls when the configuration specifies OpenAI as the sole provider.

PyYAML (>=6.0, line 38) parses optional YAML configuration files for the LLM client. src/config.py loads these overrides to adjust temperature and model parameters without restarting the service.

Collaboration and Notification Libraries

The notification layer supports enterprise messaging platforms.

lark-oapi (>=1.0.0, line 23) drives Feishu (Lark) integration. bot/platforms/feishu.py instantiates the Client class to send interactive cards and create shared documents.

dingtalk-stream (>=0.24.3, line 50) enables DingTalk group alerts. bot/platforms/dingtalk.py uses this SDK to push markdown-rich messages to enterprise chat groups.

discord.py (>=2.0.0, line 55) and PyNaCl (>=1.5.0, line 56) power the Discord bot. bot/platforms/discord.py posts analysis summaries to channels, while PyNaCl handles cryptographic signature verification for Discord interactions.

Data Processing and Analytics

The analytics layer uses standard scientific Python stacks plus domain-specific utilities.

pandas (>=2.0.0, line 26) and numpy (>=1.24.0, line 29) form the core calculation engine. src/services/analysis_service.py builds factor tables, calculates rolling moving averages, and performs vectorized operations on price history.

pypinyin (>=0.50.0, line 27) resolves Chinese stock names to ticker codes. src/utils/pinyin_util.py converts Chinese characters to pinyin for fuzzy matching user inputs against the security master.

openpyxl (>=3.1.0, line 28) generates Excel exports. src/services/excel_export.py writes .xlsx workbooks containing technical indicator tables for offline review.

json-repair (>=0.55.1, line 30) sanitizes malformed API responses. src/utils/json_helper.py calls this library to fix truncated JSON before deserialization, preventing crashes from dirty upstream data.

Web Framework and API Infrastructure

A FastAPI-based web layer exposes analysis results via REST endpoints.

fastapi (>=0.109.0, line 66) defines the async API router. api/app.py mounts endpoints that serve JSON market data and accept CSV uploads for batch analysis.

uvicorn ([standard]>=0.27.0, line 67) runs the ASGI server. main.py launches uvicorn via start_api_server to handle concurrent requests.

python-multipart (>=0.0.6, line 68) enables multipart/form-data parsing for file uploads in FastAPI routes.

jinja2 (>=3.1.0, line 63) renders HTML reports. src/reports/report_template.html is processed through Jinja2 to inject dynamic tables and charts before email distribution.

Networking and Content Extraction

Supporting libraries handle HTTP transport, web scraping, and report formatting.

requests (>=2.31.0, line 45) and httpx[socks] (line 49) provide synchronous and asynchronous HTTP clients. Data providers use requests for simple GET calls, while the optional --use-proxy mode routes traffic through httpx with SOCKS proxy support.

markdown2 (>=2.4.0, line 46) converts markdown to HTML. src/services/report_generator.py uses this to prepare email-friendly content.

imgkit (>=1.2.0, line 47) renders HTML to PNG images (requires wkhtmltopdf binary). src/services/image_stock_extractor.py generates static chart snapshots for mobile notifications.

fake-useragent (>=1.4.0, line 48) rotates User-Agent headers to avoid IP bans when scraping public market data.

newspaper3k (>=0.2.8, line 59) extracts article text from news URLs. src/services/news_extractor.py pulls the main body content for sentiment analysis, while lxml_html_clean (line 60) fixes import errors in the underlying HTML parser.

tavily-python (>=0.3.0, line 41) and google-search-results (>=2.4.0, line 42) enable news retrieval. src/search_service.py queries Tavily Search API or SerpAPI to fetch recent headlines for a given ticker symbol.

Dependency Implementation Examples

Below are representative code patterns showing how these external libraries integrate into the daily_stock_analysis workflow.

Loading environment configuration:


# src/config.py

from dotenv import dotenv_values

env = dotenv_values(".env")
DATABASE_URL = env.get("DATABASE_URL")

Fetching market data with exponential backoff:


# data_provider/efinance_provider.py

import requests
from tenacity import retry, stop_after_attempt, wait_exponential

@retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, max=10))
def fetch_quote(symbol: str) -> dict:
    resp = requests.get(f"https://api.efinance.com/quote/{symbol}")
    resp.raise_for_status()
    return resp.json()

Processing data with pandas and generating LLM prompts:


# src/services/analysis_service.py & src/analyzer.py

import pandas as pd
import numpy as np
import litellm
import tiktoken

df = pd.DataFrame(fetch_quote("600519")["history"])
df["MA5"] = df["close"].rolling(5).mean()

prompt = f"Analyze trend: {df.tail().to_markdown()}"
enc = tiktoken.encoding_for_model("gpt-4")
if len(enc.encode(prompt)) < 8192:
    response = litellm.completion(model="gpt-4", messages=[{"content": prompt}])

Rendering reports and sending notifications:


# src/services/report_generator.py & bot/platforms/feishu.py

from jinja2 import Environment, FileSystemLoader
from lark_oapi import Client

# Render HTML via Jinja2

env = Environment(loader=FileSystemLoader("src/reports"))
html = env.get_template("report.html").render(data=df)

# Send to Feishu

client = Client(app_id="...", app_secret="...")
client.im.message.create(receive_id_type="chat_id", content=html)

Summary

  • daily_stock_analysis declares 35+ external libraries in requirements.txt, organized by functional domain rather than alphabetically.
  • Data ingestion relies on a priority chain of China-specific providers (efinance, akshare, tushare, pytdx, baostock) with global fallbacks (yfinance, longbridge).
  • The AI layer uses litellm for provider-agnostic LLM calls, tiktoken for context management, and openai for direct API access.
  • Notification modules integrate enterprise SDKs (lark-oapi, dingtalk-stream, discord.py) for multi-channel alerting.
  • Web exposure uses fastapi and uvicorn, while data processing depends on pandas, numpy, and SQLAlchemy.
  • File paths like src/analyzer.py, data_provider/efinance_provider.py, and bot/platforms/feishu.py demonstrate concrete integration points for each dependency.

Frequently Asked Questions

What is the primary data source for daily_stock_analysis?

efinance (EastMoney) is the primary data source, declared in requirements.txt line 13. The data_provider/efinance_provider.py module uses this library to fetch real-time quotes and fundamental data. If efinance fails or rate-limits, the system automatically falls back to akshare, tushare, and eventually yfinance for non-Chinese equities.

How does daily_stock_analysis handle LLM API compatibility?

The project uses litellm (line 35) as a unified router for multiple LLM providers including OpenAI, Gemini, and Anthropic. src/analyzer.py calls litellm.completion() with a configurable model string, eliminating the need to rewrite client code when switching between GPT-4, Claude, or Gemini models. tiktoken handles token counting to prevent context window overflows.

Can daily_stock_analysis run without enterprise messaging accounts?

Yes. While the repository includes SDKs for lark-oapi (Feishu), dingtalk-stream, and discord.py, these are optional. The core analysis engine functions independently; notifications can be disabled by omitting the respective API keys in .env or removing the bot configuration from main.py.

Which web framework serves the API endpoints?

FastAPI (>=0.109.0, line 66) provides the REST API infrastructure. The api/app.py file defines async endpoints for data retrieval and batch processing, while uvicorn (line 67) serves as the ASGI server. python-multipart (line 68) enables file upload support for CSV batch jobs.

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:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →