Repository files navigation

FinAssistant Logo

FinAssistant — AI-Powered Financial Analysis

RAG Retrieval & Agent System for China A-Share Market

BackgroundFeaturesData AssetsImplementationTools

中文 | English


1. Background

The China A-share market has diverse data dimensions and massive information volumes. Retail investors and small-to-medium institutions struggle to efficiently integrate stock quotes, sector rotation, financial statements, and market news for comprehensive analysis. This project aims to build a financial RAG retrieval and agent system based on collected A-share data assets, enabling users to perform professional financial analysis through natural language conversations.

Core Objectives

  • Lower Analysis Barriers: Replace manual data queries, indicator calculations, and report writing with natural language
  • Multi-dimensional Data Correlation: Connect stocks, sectors, financials, and news for a panoramic view
  • Agent Collaboration: Multiple specialized agents working together, covering the full workflow from data queries to research reports

Tech Stack

LayerTechnology
Agent FrameworkAgentScope 2.0 (Multi-Agent Orchestration)
Data StorageMySQL (Structured Query) + Milvus (Vector Retrieval)
Data CollectionPython + akshare + DrissionPage
LLMQwen / GPT / Claude
Embeddingtext-embedding-v3 / BGE
FrontendStreamlit / Gradio

2. Feature Modules

Six intelligent agent modules planned based on existing data assets:


2.1 Stock Analysis Agent

Data Support: Daily stock quotes + Company info + Financial statements

Core Features:

FeatureDescriptionImplementation
Fundamental ScoreAuto-score (0-100) based on ROE, gross margin, debt ratio, cash flowExtract key fields from 3 statements, weighted calculation
Valuation PercentilePE/PB/PCF percentile in 1-year history, determine over/undervaluedCalculate percentile on daily PE/PB series
Technical IndicatorsMA(5/10/20/60), MACD, RSI, Bollinger Bands, KDJReal-time calculation based on OHLCV data
Trading SignalsGolden/Dead cross, MA breakout, RSI overbought/oversoldTechnical indicator crossover detection
Stock Profile ReportComprehensive fundamental + technical + valuation + sector reportLLM aggregates analysis results into text

Example Queries:

"How is Pudong Bank's cash flow situation this quarter?"
"What is Ping An Bank's current valuation percentile?"
"Analyze Kweichow Moutai's technical trend and give trading advice"
"Generate a stock profile report for CATL"

To-Do:

  • tools/stock_fundamental.py — Fundamental indicator calculator (Done)
  • tools/stock_valuation.py — Valuation percentile analyzer (Done)
  • tools/stock_technical.py — Technical indicator calculator (Done)
  • tools/stock_analysis.py — Comprehensive stock analysis report (Done)
  • agents/stock_agent.py — Stock analysis agent (Done)

Agent Demo:

$ python agents/stock_agent.py
============================================================
FinAssistant — 金融智能体
============================================================
输入股票代码或问题开始分析,输入 'quit' 退出
============================================================
你: 帮我分析贵州茅台的技术面走势,给出操作建议
FinAssistant:
[调用工具: reset_tools]
[完成] 结果: The currently activated tool group(s): stock-technical.
[调用工具: calc_technical_summary]
[完成] 结果: === 600519.SH 技术指标分析 (2026-07-17) ===
收盘价: 1253.0
【移动平均线 MA】
MA5: 1237.78
MA10: 1217.11
MA20: 1204.07
MA60: 1263.65
均线趋势: 多头排列
【MACD】
DIF: -0.2443
DEA: -11.3353
MACD柱: 22.182
信号: 金叉
【RSI】
RSI(6): 92.76
RSI(12): 68.8
RSI(24): 48.73
RSI(6)信号: 超买
【布林带 BOLL】
上轨: 1252.21
中轨: 1204.07
下轨: 1155.92
【KDJ】
K: 84.3
D: 79.2
J: 94.49
信号: 金叉
【综合研判】
当前信号: MA多头排列, MACD金叉, RSI超买, KDJ金叉
### 贵州茅台(600519.SH)技术面分析与操作建议
#### 一、核心技术指标摘要(近120天)
| 指标类型 | 关键数据 | 信号解读 |
|---------|---------|---------|
| **均线系统** | MA5:1237.78, MA10:1217.11, MA20:1204.07, MA60:1263.65 | 短期均线多头排列,股价略低于MA60(1263.65),中期趋势依然向上 |
| **MACD** | DIF:-0.24, DEA:-11.34, MACD柱:22.18 | 低位金叉形成,空头趋势减弱,短期反弹信号明确 |
| **RSI** | RSI(6):92.76, RSI(12):68.80, RSI(24):48.73 | 短期RSI严重超买(>90),警惕回调风险 |
| **布林带** | 上轨:1252.21, 中轨:1204.07, 下轨:1155.92 | 股价突破上轨,处于强势区间,但短期乖离率偏大 |
| **KDJ** | K:84.30, D:79.20, J:94.49 | 高位金叉,短期上涨动能充足,但J线接近超买区 |
#### 二、综合研判
技术面呈现**强趋势与短期超买并存**的格局:
1. **多头趋势明确**:均线多头排列、MACD低位金叉、KDJ金叉共同构成中期上涨信号
2. **短期回调风险**:RSI超买、股价突破布林上轨提示短期涨幅过大,存在技术性回调需求
#### 三、操作建议
1. **持仓投资者**:
- 继续持有为主,可将MA20(1204.07)作为止损线
- 若股价回落至MA5-MA10区间(1217-1238)可适当加仓
- 短期若冲高至MA60(1263.65)遇阻,可考虑部分止盈
2. **观望投资者**:
- 等待回调至关键支撑位(MA20:1204或布林中轨:1204)再考虑进场
- 若股价直接突破MA60并站稳,可小仓位追涨
⚠️ **风险提示**:技术分析仅供参考,不构成投资建议。市场存在不确定性,需结合自身风险承受能力决策。

2.2 Sector Rotation Analysis Agent

Data Support: Industry/Concept sector daily quotes (90 industry + 374 concept) + Constituent stocks

Core Features:

FeatureDescriptionImplementation
Sector RankingRank by pct_chg, volume change, capital flowAggregate sector daily_index
Rotation TrendSectors with consecutive top N-day gains marked as "hot"Sliding window rank change analysis
Sector ComparisonMulti-sector price curves overlayExtract multiple sector close series
Constituent DistributionAdvance/decline count, limit up/down, median changeLink constituent daily data
Capital FlowVolume change trend, determine inflow/outflowVolume QoQ change analysis
Sector CorrelationConstituent stock overlap between two sectorsSet intersection/union ratio

Example Queries:

"Which industry sectors had the highest gains this week?"
"How has the semiconductor sector performed this month? Is capital flowing in or out?"
"How high is the overlap between AI and robotics concept constituents?"
"Which sectors had limit-down waves today?"

To-Do:

  • tools/sector_ranking.py — Sector ranking tool (Done)
  • tools/sector_rotation.py — Rotation trend identifier (Done)
  • tools/sector_compare.py — Sector comparison tool (Done)
  • tools/sector_detail.py — Sector deep analysis tool (Done)
  • agents/sector_agent.py — Sector analysis agent (Done)

Agent Demo:

$ python agents/sector_agent.py
============================================================
FinAssistant — 板块轮动分析智能体
============================================================
输入板块相关问题开始分析,输入 'quit' 退出
示例:
- 最近一周涨幅最大的行业板块有哪些?
- 半导体板块最近一个月资金是在流入还是流出?
- AI概念和机器人概念的成分股重叠度有多高?
- 今天哪些板块出现了跌停潮?
============================================================
你: 最近一周涨幅最大的行业板块有哪些?
FinAssistant:
[调用工具: get_sector_ranking]
[完成] 结果: === 行业板块涨跌幅排名 (2026-07-17) ===
Top 10:
排名 板块名称 涨跌幅(%) 成交额(亿)
1 通信设备 +5.23 312.45
2 半导体 +4.87 528.91
3 消费电子 +3.65 287.33
...
[调用工具: get_sector_top_gainers]
[完成] 结果: === 连续3天上涨的行业板块 ===
板块名称 连涨天数 累计涨幅(%)
半导体 3 +8.92
通信设备 3 +7.56
...
综合来看,最近一周涨幅最大的行业板块主要集中在科技领域:
1. **通信设备** (+5.23%) — 5G建设持续推进,板块领涨
2. **半导体** (+4.87%) — 国产替代逻辑强化,资金持续流入
3. **消费电子** (+3.65%) — 新品发布预期带动板块走强
其中半导体和通信设备已连续3天上涨,短期动能较强。
⚠️ 风险提示:板块轮动较快,追高需谨慎。以上分析仅供参考,不构成投资建议。

2.3 Cross-Data Correlation Analysis Agent

Data Support: Quotes + Constituents + Financial statements + News (Full data cross-correlation)

Core Features:

FeatureDescriptionImplementation
Stock→Sector MappingQuery which sectors a stock belongs to, recent performanceReverse lookup in constituent data
Sector→Financial AggregationAverage ROE, median PE, total revenue for sector constituentsLink constituent codes to financial statements
News→Quote CorrelationCompanies/sectors mentioned in news, link to recent price trendsNER entity recognition + code matching
Industry ChainInfer upstream/downstream relationships via concept overlapConstituent set similarity clustering
Leader EffectTop N stocks by market cap vs sector overall performanceMarket-cap weighted vs equal-weight index

Example Queries:

"Which concept sectors does BYD belong to? How are they performing?"
"What's the average PE and ROE for the semiconductor sector?"
"Any recent news about solar power? How are related sectors trending?"
"Find the top 5 stocks most correlated with CATL"

To-Do:

  • tools/stock_sector_mapping.py — Stock-sector mapping tool (Done)
  • tools/sector_financial_agg.py — Sector financial aggregation (Done)
  • tools/news_stock_linker.py — News-quote correlation tool (Done)
  • agents/correlation_agent.py — Correlation analysis agent (Done)

2.4 Financial Q&A Agent (RAG)

Data Support: Financial statements (4,593 stocks × multi-period) + Vector database (Milvus)

Core Features:

FeatureDescriptionImplementation
NL Financial Query"Which companies have gross margin > 50%" → SQL/Vector searchVectorize financial fields + structured query
Cross-stock ComparisonHorizontal comparison of financial indicators for same-industry companiesGroup by industry + indicator comparison
Multi-period TrendVertical comparison of same company across periodsTime series analysis + trend detection
Anomaly AlertCash flow plunge, receivables surge, goodwill impairmentThreshold/QoQ change detection
Financial Health ScoreComprehensive solvency, profitability, growth, operational abilityDuPont analysis system + weighted scoring

Example Queries:

"Which banks have positive operating cash flow for the past year?"
"Compare CATL and BYD's debt ratio trends"
"Which companies had gross margin drop > 10% last quarter?"
"Give me a DuPont analysis for Kweichow Moutai"
"Find companies with ROE > 20% for 3 consecutive years"

To-Do:

  • tools/financial_query.py — Financial data query tool (Done)
  • tools/financial_compare.py — Financial comparison tool (Done)
  • tools/financial_anomaly.py — Anomaly detection tool (Done)
  • tools/financial_score.py — Financial health scoring tool (Done)
  • agents/financial_agent.py — Financial Q&A agent (Done)
  • rag/financial_embedding.py — Financial statement vectorization

2.5 Daily Market Report Agent

Data Support: Full data (Quotes + Sectors + News + Financials)

Core Features:

FeatureDescriptionImplementation
Market OverviewMajor index changes, volume, advance/decline statsAggregate all market stock data
Sector Rotation SummaryTop gainers/losers, capital inflow/outflow Top5Sector ranking tool output
Anomaly DetectionLimit up/down, volume breakout, abnormal volatilityFilter conditions
News SummaryMarket-related important news, linked sectorsNews filtering + LLM summary
Watchlist ReportUser's watched stocks daily performance, announcementsPersonalized filtering
Trend AssessmentBased on recent N-day data, market sentiment judgmentMulti-indicator synthesis

Example Queries:

"Generate today's market morning briefing"
"Which stocks hit limit up today? Which sectors do they belong to?"
"How has market sentiment been this week?"
"How are my watchlist stocks performing today?"

To-Do:

  • tools/market_overview.py — Market overview tool (Done)
  • tools/abnormal_detector.py — Anomaly detection tool (Done)
  • tools/market_trend.py — Trend assessment tool (Done)
  • tools/watchlist_report.py — Watchlist report tool (Done)
  • tools/daily_digest.py — Daily report generator (Done, integrates all 6 modules)
  • agents/daily_report_agent.py — Daily report agent (Done)

2.6 Research Report Generation Agent

Data Support: Full data + LLM generation capabilities

Core Features:

FeatureDescriptionImplementation
Stock Deep ReportComprehensive fundamental + technical + valuation + industry positionCall previous tools + LLM long-text generation
Industry ResearchSector trends, constituent financials, industry chain analysisSector tools + Financial tools + LLM
Comparative Report2-3 same-industry companies multi-dimensional comparisonComparison tools + LLM
Event Impact AnalysisNews/policy impact on related sectors and stocksNews correlation + Historical analogy + LLM
Portfolio SuggestionRecommend sector/stock allocation based on risk preferenceOptimization algorithm + LLM

Example Queries:

"Write a deep research report on the semiconductor industry"
"Compare BYD, CATL, and LONGi Green Energy with a comparative analysis"
"Which A-share sectors are most affected by Fed rate hikes?"
"I prefer conservative investing, recommend some sector allocation plans"

To-Do:

  • tools/report_generator.py — Report generation tool (LLM + templates)
  • templates/ — Report templates (stock/industry/comparison/event)
  • agents/report_agent.py — Report generation agent
  • agents/portfolio_agent.py — Portfolio optimization agent

3. Data Assets

3.1 Data Overview

Data TypeVolumeSourceTime Range
SH Stock Daily Quotes2,308 stocksSina Finance (akshare)2026-01-01 ~ Present
SZ Stock Daily Quotes2,895 stocksSina Finance (akshare)2026-01-01 ~ Present
SH Company Info2,308 (Main 1,699 + STAR 609)SSE (akshare)-
SZ Company Info2,895SZSE (akshare)-
SH Financial Statements2,308 stocksSina Finance (akshare)Recent 3 years
SZ Financial Statements2,895 stocksSina Finance (akshare)Recent 3 years
Industry Sector Quotes90 sectorsTonghuashun (akshare)2026-01-01 ~ Present
Concept Sector Quotes374 sectorsTonghuashun (akshare)2026-01-01 ~ Present
Industry Constituents90 sectorsTonghuashun (DrissionPage)-
Concept Constituents374 sectorsTonghuashun (DrissionPage)-
Financial News-Tonghuashun 7x242026-01-01 ~ Present

3.2 MySQL Table Schema

Data is stored in Alibaba Cloud RDS MySQL with two databases: market_data (quotes/financials) and stock_news (news).

market_data.company_info — Company Basic Info

CREATETABLEcompany_info (
id INT AUTO_INCREMENT PRIMARY KEY COMMENT 'Auto-increment ID',
ts_code VARCHAR(20) NOT NULL COMMENT 'Stock code with suffix, e.g., 600000.SH',
symbol VARCHAR(10) NOT NULL COMMENT 'Stock code (numeric only)',
stock_name VARCHAR(50) COMMENT 'Stock short name',
full_name VARCHAR(100) COMMENT 'Company full name',
industry VARCHAR(50) COMMENT 'Industry, e.g., J Finance',
list_date VARCHAR(20) COMMENT 'Listing date, format YYYY-MM-DD',
market VARCHAR(5) COMMENT 'Market, SH=Shanghai SZ=Shenzhen',
updated_at VARCHAR(30) COMMENT 'Data update time',
UNIQUE KEY uk_ts_code (ts_code)
)

market_data.stock_kline — Stock Daily K-line

CREATETABLEstock_kline (
id BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT 'Auto-increment ID',
ts_code VARCHAR(20) NOT NULL COMMENT 'Stock code with suffix',
symbol VARCHAR(10) NOT NULL COMMENT 'Stock code (numeric only)',
trade_date VARCHAR(20) NOT NULL COMMENT 'Trade date, format YYYY-MM-DD',
open DOUBLE COMMENT 'Open price (CNY)',
close DOUBLE COMMENT 'Close price (CNY)',
high DOUBLE COMMENT 'High price (CNY)',
low DOUBLE COMMENT 'Low price (CNY)',
pre_close DOUBLE COMMENT 'Previous close (CNY)',
change_data DOUBLE COMMENT 'Price change (CNY)',
pct_chg DOUBLE COMMENT 'Change percentage (%)',
volume DOUBLE COMMENT 'Volume (shares)',
amount DOUBLE COMMENT 'Turnover (CNY)',
pe DOUBLE COMMENT 'P/E ratio',
pb DOUBLE COMMENT 'P/B ratio',
total_mv DOUBLE COMMENT 'Total market cap (100M CNY)',
total_share DOUBLE COMMENT 'Total shares',
float_share DOUBLE COMMENT 'Float shares',
circ_mv DOUBLE COMMENT 'Circulating market cap (100M CNY)',
ln_pctchg DOUBLE COMMENT 'Log return',
pe_ttm DOUBLE COMMENT 'P/E ratio (TTM)',
pe_static DOUBLE COMMENT 'Static P/E ratio',
pcf DOUBLE COMMENT 'Price-to-Cash-Flow ratio',
UNIQUE KEY uk_code_date (ts_code, trade_date),
KEY idx_trade_date (trade_date),
KEY idx_symbol (symbol)
)

market_data.stock_financial — Financial Statements

CREATETABLEstock_financial (
id BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT 'Auto-increment ID',
ts_code VARCHAR(20) NOT NULL COMMENT 'Stock code with suffix',
symbol VARCHAR(10) NOT NULL COMMENT 'Stock code (numeric only)',
statement_type VARCHAR(20) NOT NULL COMMENT 'Statement type: income/balance/cashflow',
report_date VARCHAR(20) NOT NULL COMMENT 'Report date, e.g., 20260331',
report_data JSON COMMENT 'Complete statement data (JSON)',
UNIQUE KEY uk_code_type_date (ts_code, statement_type, report_date),
KEY idx_symbol (symbol),
KEY idx_report_date (report_date),
KEY idx_statement_type (statement_type)
)

Financial fields vary significantly across industries (banking vs manufacturing), hence JSON storage for complete statement data.

market_data.sector_industry_daily / sector_concept_daily — Sector Daily K-line

CREATETABLEsector_industry_daily (
id BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT 'Auto-increment ID',
sector_name VARCHAR(50) NOT NULL COMMENT 'Sector name',
sector_code VARCHAR(20) NOT NULL COMMENT 'Sector code',
trade_date VARCHAR(20) NOT NULL COMMENT 'Trade date',
open DOUBLE COMMENT 'Open',
high DOUBLE COMMENT 'High',
low DOUBLE COMMENT 'Low',
close DOUBLE COMMENT 'Close',
vol DOUBLE COMMENT 'Volume',
amount DOUBLE COMMENT 'Turnover',
pct_chg DOUBLE COMMENT 'Change (%)',
change_data DOUBLE COMMENT 'Point change',
pct_change DOUBLE COMMENT 'Change (backup)',
turnover_rate DOUBLE COMMENT 'Turnover rate',
UNIQUE KEY uk_code_date (sector_code, trade_date),
KEY idx_trade_date (trade_date),
KEY idx_sector_name (sector_name)
)

market_data.sector_industry_cons / sector_concept_cons — Sector Constituents

CREATETABLEsector_industry_cons (
id BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT 'Auto-increment ID',
sector_name VARCHAR(50) NOT NULL COMMENT 'Sector name',
sector_code VARCHAR(20) NOT NULL COMMENT 'Sector code',
stock_code VARCHAR(10) NOT NULL COMMENT 'Stock code',
stock_name VARCHAR(50) COMMENT 'Stock name',
UNIQUE KEY uk_sector_stock (sector_code, stock_code),
KEY idx_sector_name (sector_name),
KEY idx_stock_code (stock_code)
)

stock_news.news_em — Eastmoney 7x24 News

CREATETABLEnews_em (
id INT AUTO_INCREMENT PRIMARY KEY COMMENT 'Auto-increment ID',
title VARCHAR(500) NOT NULL COMMENT 'News title',
digest TEXT COMMENT 'News digest',
publish_time VARCHAR(30) COMMENT 'Publish time',
url VARCHAR(500) COMMENT 'News URL',
crawl_time VARCHAR(30) COMMENT 'Crawl time',
UNIQUE KEY uk_title_time (title, publish_time)
)

stock_news.news_ths — Tonghuashun Financial News

CREATETABLEnews_ths (
id INT AUTO_INCREMENT PRIMARY KEY COMMENT 'Auto-increment ID',
news_id VARCHAR(20) NOT NULL COMMENT 'News ID',
title VARCHAR(500) NOT NULL COMMENT 'News title',
digest TEXT COMMENT 'News digest',
url VARCHAR(500) COMMENT 'News URL',
tags VARCHAR(500) COMMENT 'Tags (comma separated)',
ctime_str VARCHAR(30) COMMENT 'Publish time',
source VARCHAR(100) COMMENT 'Source',
crawl_time VARCHAR(30) COMMENT 'Crawl time',
UNIQUE KEY uk_news_id (news_id),
KEY idx_ctime (ctime_str)
)

3.3 Data Import Scripts

ScriptTarget TableDescription
import_company_info_to_mysql.pymarket_data.company_infoSH/SZ company info
import_kline_to_mysql.pymarket_data.stock_klineStock daily K-line (560K+ rows)
import_financial_to_mysql.pymarket_data.stock_financialFinancial statements (170K+ rows)
import_sector_to_mysql.pymarket_data.sector_*_dailySector daily K-line
import_sector_cons_to_mysql.pymarket_data.sector_*_consSector constituents
import_news_em_to_mysql.pystock_news.news_emEastmoney news
import_news_ths_to_mysql.pystock_news.news_thsTonghuashun news

3.4 Data Collection Scripts

ScriptPurposeSource
crawl_sh_stock_data.pySH stock quotes + company infoSina Finance / SSE
crawl_sz_stock_data.pySZ stock quotes + company infoSina Finance / SZSE
crawl_financial_reports.pyFinancial statementsSina Finance
crawl_sector_data.pySector daily quotes (Industry + Concept)Tonghuashun (akshare)
crawl_sector_cons.pySector constituentsSina Finance (akshare)
crawl_sector_cons_ths.pySector constituents (backup)Tonghuashun (DrissionPage)
crawl_news_ths.pyFinancial newsTonghuashun 7x24 API
crawl_news_em.pyEastmoney 7x24 news (scheduled)Eastmoney (akshare)

3.5 Known Issues

IssueDescription
Eastmoney API Blockedpush2his.eastmoney.com completely unavailable
Tonghuashun IP BlockedFrequent crawling triggers Nginx 403 block
Inconsistent Sector SourcesQuotes from THS, constituents partially from Sina, names may not match
SH Company Missing IndustrySSE API doesn't provide industry field

4. AgentScope 2.0 Implementation

4.1 Architecture

User Query → FastAPI → Agent (system_prompt + model + toolkit + middlewares)
↓
Toolkit
├── ToolGroup("Stock Analysis") → tools/stock_query.py + skills/stock-analysis/
├── ToolGroup("Sector Analysis") → tools/sector_query.py + skills/sector-rotation/
├── ToolGroup("Financial Q&A") → tools/financial_query.py + skills/financial-qa/
├── ToolGroup("Daily Report") → tools/news_query.py + skills/daily-report/
└── ToolGroup("Research Report") → tools/indicators.py + skills/research-report/

4.2 Directory Structure

FinAssistant/
├── config.py # Global config (paths, model, API Key)
├── main.py # FastAPI service entry
├── main_agent.py # Single agent script (no server, direct chat)
├── core/
│ ├── agent_setup.py # Agent + Toolkit initialization
│ └── middleware.py # Financial scenario middleware
├── tools/ # Tool functions
│ ├── __init__.py
│ ├── stock_query.py # Stock quote/company info query
│ ├── sector_query.py # Sector quote/constituent query
│ ├── financial_query.py # Financial statement query & analysis
│ ├── news_query.py # News query
│ └── indicators.py # Technical/fundamental indicator calculation
├── skills/ # Skill documents (SKILL.md)
│ ├── stock-analysis/SKILL.md
│ ├── sector-rotation/SKILL.md
│ ├── financial-qa/SKILL.md
│ ├── daily-report/SKILL.md
│ └── research-report/SKILL.md
├── data/ # Existing data (don't modify)
└── data_to_mysql_and_milvus/ # Existing crawler scripts (don't modify)

4.3 Implementation Steps

Step 1: config.py

Global configuration for data paths, model config, API keys.

Step 2: tools/ Tool Functions

Each function is async def, returns ToolChunk. Docstring is the tool description — LLM decides when to call based on docstring.

Step 3: skills/SKILL.md Skill Documents

Each skill directory has a SKILL.md with trigger conditions, dependent tools, and execution flow.

Step 4: core/middleware.py Middleware

MiddlewarePurpose
InputValidationMiddlewareFilter non-financial queries
ToolCallAuditMiddlewareLog tool calls to traces/
PerformanceMonitorMiddlewareMonitor inference rounds, latency, tokens
ContextEnrichmentMiddlewareInject current date, trading day context

Step 5: core/agent_setup.py Agent Initialization

Assemble model, tools, toolkit, and agent with middleware.

Step 6: main.py Service Entry

FastAPI service with OpenAI-compatible /v1/chat/completions endpoint.


5. Implemented Tools

tools/stock_fundamental.py — Fundamental Indicator Calculator

Calculates fundamental indicators from MySQL market_data.stock_financial table.

Core Functions:

FunctionDescription
calc_fundamental_indicators(ts_code, report_date=None)Calculate single-period indicators
calc_fundamental_trend(ts_code, periods=4)Calculate recent N-period trend
get_financial_data(ts_code, report_date=None)Get raw statement data
get_report_dates(ts_code, limit=8)Get report date list

Calculated Indicators:

IndicatorFormulaData Source
ROENet Profit / Equity × 100%Income + Balance Sheet
Gross Margin(Revenue - COGS) / Revenue × 100%Income Statement
Net MarginNet Profit / Revenue × 100%Income Statement
Debt RatioTotal Liabilities / Total Assets × 100%Balance Sheet
Cash Flow / Net ProfitOperating Cash Flow / Net ProfitCash Flow + Income
Revenue YoY Growth(Current - Prior Year) /Prior Year
Net Profit YoY Growth(Current - Prior Year) /Prior Year
Revenue QoQ Growth(Current Q - Prior Q) /Prior Q
Net Profit QoQ Growth(Current Q - Prior Q) /Prior Q

Special Handling:

  • Auto bank detection: Via balance sheet fields (loans, deposits)
  • Bank field mapping: Revenue = Net Interest Income + Fee Income; COGS = Interest Expense + Fee Expense
  • YoY calculation: Cumulative values vs same quarter last year (2026Q1 vs 2025Q1)
  • QoQ calculation: Single-quarter values (Q4 = Annual - 9-month cumulative)

Usage:

fromtools.stock_fundamentalimportcalc_fundamental_indicators, calc_fundamental_trend# Single periodresult=calc_fundamental_indicators('600519.SH')
print(result['ROE'], result['毛利率'], result['营收同比增长率'])
# Trend (recent 4 periods)trend=calc_fundamental_trend('600519.SH', periods=4)
fortintrend['trend']:
print(t['report_date'], t['ROE'], t['营收同比增长率'])

tools/stock_valuation.py — Valuation Percentile Analyzer

Calculates PE/PB/PCF percentile in 1-year history from market_data.stock_kline table.

Core Functions:

FunctionDescription
calc_valuation_percentile(ts_code, days=365)Calculate valuation percentile, return structured data
calc_valuation_summary(ts_code, days=365)Generate formatted valuation summary
get_valuation_history(ts_code, days=365)Get N-day valuation history
get_latest_valuation(ts_code)Get latest day valuation data

Valuation Indicators:

IndicatorDescriptionSource
PE_TTMPrice-to-Earnings (Trailing Twelve Months)stock_kline.pe_ttm
PBPrice-to-Bookstock_kline.pb
PCFPrice-to-Cash-Flowstock_kline.pcf

Percentile Rules:

PercentileLevelMeaning
< 20%UndervaluedAt historical low, potentially undervalued
20% - 40%Below AverageBelow historical median
40% - 60%FairAt historical median range
60% - 80%Above AverageAbove historical median
> 80%OvervaluedAt historical high, potentially overvalued

Usage:

fromtools.stock_valuationimportcalc_valuation_percentile, calc_valuation_summary# Get structured dataresult=calc_valuation_percentile('600519.SH')
print(f"PE_TTM: {result['pe_ttm']}, Percentile: {result['pe_ttm_percentile']}%, {result['pe_ttm_level']}")
# Get formatted summaryprint(calc_valuation_summary('600519.SH'))

tools/stock_technical.py — Technical Indicator Calculator

Calculates MA/MACD/RSI/BOLL/KDJ indicators from MySQL market_data.stock_kline table.

Core Functions:

FunctionDescription
calc_technical_indicators(ts_code, days=120)Calculate all technical indicators
calc_technical_summary(ts_code, days=120)Generate formatted summary
get_kline_data(ts_code, days=120)Get K-line data from MySQL

Technical Indicators:

IndicatorFormulaUsage
MA(5/10/20/60)Average of last N closing pricesTrend: Price above MA = bullish; MA crossover = buy/sell signal
MACDDIF = EMA(12) - EMA(26); DEA = EMA(DIF,9); Histogram = (DIF-DEA)×2Golden cross (DIF>DEA) = buy; Dead cross = sell
RSI(6/12/24)RS = Avg Gain / Avg Loss; RSI = 100 - 100/(1+RS)>80 = overbought; <20 = oversold
BOLL(20,2)Upper = MA+2σ; Middle = MA; Lower = MA-2σTouch upper = overbought; Touch lower = oversold
KDJ(9,3,3)RSV, K = 2/3K+1/3RSV, D = 2/3D+1/3K, J = 3K-2DK>80 = overbought; K<20 = oversold; K/D crossover

Signal Interpretation:

SignalMAMACDRSIBOLLKDJ
BullishMA5>MA10>MA20 (Bull alignment)DIF>DEA, Histogram>0RSI<20 (Oversold)Price bounces off lower bandK/D golden cross in oversold zone
BearishMA5<MA10<MA20 (Bear alignment)DIF<DEA, Histogram<0RSI>80 (Overbought)Price falls from upper bandK/D dead cross in overbought zone

Multi-indicator Confirmation:

Buy signals (need 2-3):

  • Price above MA20, MA bullish alignment (MA5>MA10>MA20)
  • MACD golden cross (DIF crosses above DEA)
  • RSI rebounds from oversold (<20 → >20)
  • Price bounces off Bollinger lower band
  • KDJ golden cross in oversold zone

Sell signals (need 2-3):

  • Price below MA20, MA bearish alignment (MA5<MA10<MA20)
  • MACD dead cross (DIF crosses below DEA)
  • RSI enters overbought (>80) then falls
  • Price falls from Bollinger upper band
  • KDJ dead cross in overbought zone

Usage:

fromtools.stock_technicalimportcalc_technical_indicators, calc_technical_summary# Get structured dataresult=calc_technical_indicators('600519.SH')
print(f"Close: {result['close']}, MA5: {result['ma5']}, MACD: {result['macd_signal']}")
# Get formatted summaryprint(calc_technical_summary('600519.SH'))

5.5 Sector Analysis Tools

tools/sector_ranking.py — Sector Ranking Tool

Calculates sector rankings from MySQL sector_industry_daily / sector_concept_daily tables.

Core Functions:

FunctionDescription
get_sector_ranking(sector_type, trade_date, top_n, sort_by)Sector ranking by pct_chg/amount/volume
get_sector_top_gainers(sector_type, days, top_n)Sectors with consecutive N-day gains
get_sector_top_losers(sector_type, days, top_n)Sectors with consecutive N-day losses
get_sector_summary(sector_type, trade_date)Market overview (advance/decline, limit up/down)

Usage:

fromtools.sector_rankingimportget_sector_ranking, get_sector_top_gainers, get_sector_summary# Top 10 industry sectors by pct_chgprint(get_sector_ranking(sector_type='industry', top_n=10))
# Sectors rising for 3 consecutive daysprint(get_sector_top_gainers(sector_type='industry', days=3))
# Industry sector market overviewprint(get_sector_summary(sector_type='industry'))

tools/sector_rotation.py — Rotation Trend Identifier

Analyzes sector momentum and capital rotation direction through short-term vs medium-term performance comparison.

Core Functions:

FunctionDescription
get_sector_momentum(sector_type, short_days, long_days, top_n)Momentum analysis — short vs medium term, momentum score
get_sector_rotation(sector_type, short_days, long_days, top_n)Rotation identification — capital inflow/outflow sectors
get_sector_strength(sector_type, days, top_n)Strength ranking — composite score of gains, up-days, volume
get_hot_cold_sectors(sector_type, days)Hot/cold classification — hot/warm/flat/cold categories

Usage:

fromtools.sector_rotationimportget_sector_momentum, get_sector_rotation, get_hot_cold_sectors# Industry sector momentum (3-day short vs 10-day medium)print(get_sector_momentum(sector_type='industry', short_days=3, long_days=10))
# Sector rotation (capital inflow/outflow)print(get_sector_rotation(sector_type='industry'))
# Hot/cold sector classificationprint(get_hot_cold_sectors(sector_type='industry', days=5))

tools/sector_compare.py — Sector Comparison Tool

Multi-sector price curve overlay comparison with normalization and ASCII trend charts.

Core Functions:

FunctionDescription
compare_sectors(sector_names, sector_type, days)Multi-sector cumulative return comparison (table + ASCII chart)
compare_sector_trend(sector_names, sector_type, days)Trend strength comparison with conclusion

Usage:

fromtools.sector_compareimportcompare_sectors, compare_sector_trend# Compare Baijiu vs Power vs Banks over 20 daysprint(compare_sectors(['白酒', '电力', '银行'], sector_type='industry', days=20))
# Trend strength comparison with conclusionprint(compare_sector_trend(['白酒', '电力', '银行', '证券'], days=20))

tools/sector_detail.py — Sector Deep Analysis Tool

Links constituent stock data to provide internal sector structure analysis.

Core Functions:

FunctionDescription
get_constituent_distribution(sector_name, sector_type, trade_date)Constituent distribution — advance/decline, limit up/down, median change, top/bottom 5
get_sector_money_flow(sector_name, sector_type, days)Capital flow analysis — volume trend, price-volume coordination, inflow/outflow
get_sector_correlation(sector_name1, sector_name2, sector_type)Sector correlation — Jaccard coefficient, overlapping constituents

Usage:

fromtools.sector_detailimportget_constituent_distribution, get_sector_money_flow, get_sector_correlation# Baijiu sector constituent distributionprint(get_constituent_distribution('白酒', sector_type='industry'))
# Power sector capital flow analysisprint(get_sector_money_flow('电力', sector_type='industry', days=10))
# Baijiu vs Beer sector correlationprint(get_sector_correlation('白酒', '啤酒', sector_type='industry'))

tools/news_stock_linker.py — News-Stock Linker

Links news headlines to mentioned companies/sectors and correlates with their recent price trends.

Core Functions:

FunctionDescription
find_news_by_keyword(keyword, limit)Search news by keyword (title/digest fuzzy match)
search_news_with_market(keyword, limit, days_before, days_after)Search news and auto-correlate with matched stocks/sectors price trends

Usage Example:

fromtools.news_stock_linkerimportfind_news_by_keyword, search_news_with_market# Search news by keywordprint(find_news_by_keyword('半导体', limit=5))
# Search news and correlate with market dataprint(search_news_with_market('贵州茅台', limit=3, days_before=3, days_after=3))

5.6 Sector Analysis Agent

agents/sector_agent.py — Sector Analysis Agent

Integrates sector ranking, rotation, comparison, and deep analysis tool groups for sector rotation analysis.

Tool Group Structure:

Tool GroupToolsDescription
sector-rankingget_sector_ranking / get_sector_top_gainers / get_sector_top_losers / get_sector_summarySector ranking
sector-rotationget_sector_momentum / get_sector_rotation / get_sector_strength / get_hot_cold_sectorsRotation analysis
sector-comparecompare_sectors / compare_sector_trendSector comparison
sector-detailget_constituent_distribution / get_sector_money_flow / get_sector_correlationDeep analysis

Run:

python agents/sector_agent.py

5.7 Correlation Analysis Agent

agents/correlation_agent.py — Correlation Analysis Agent

Integrates stock-sector mapping, sector financial aggregation, and news-market correlation tool groups for cross-data analysis.

Tool Group Structure:

Tool GroupToolsDescription
stock-sectorfind_stock_sectorsStock-sector mapping
sector-financeget_sector_financial_agg / get_sector_valuation_statsSector financial aggregation, valuation distribution
news-marketfind_news_by_keyword / search_news_with_marketNews search, news-market correlation

Run:

python agents/correlation_agent.py

5.8 Financial Health Scoring Tool

tools/financial_score.py — Financial Health Scoring Tool

Computes a four-dimension composite financial health score (0-100) with rating (Excellent/Good/Fair/Poor).

Scoring Dimensions:

DimensionWeightIndicators
Profitability30%ROE(40%) + Gross Margin(30%) + Net Margin(30%)
Growth25%Revenue YoY Growth(50%) + Net Profit YoY Growth(50%)
Safety25%Debt Ratio(40%) + Cash Flow/NP(35%) + AR Ratio(25%)
Quality20%Deducted NP Ratio(50%) + Cash Flow Consistency(50%)

Anomaly Deduction: HIGH -5pts, MEDIUM -2pts, max -15pts.

Core Functions:

FunctionDescription
calc_financial_score(ts_code, report_date=None)Calculate single stock financial health score
format_financial_score(ts_code, report_date=None)Generate formatted Markdown output
score_sector(sector_name, sector_type, top_n)Batch score sector constituents

Run:

python tools/financial_score.py --ts_code 600519.SH
python tools/financial_score.py --sector 白酒 --top_n 10
python tools/financial_score.py --ts_codes 600519.SH,300750.SZ,601318.SH

5.9 Financial Q&A Agent

agents/financial_agent.py — Financial Q&A Agent

Integrates fundamental indicators, trend analysis, comparison, anomaly detection, financial scoring, and batch screening tool groups for complex financial Q&A.

Tool Group Structure:

Tool GroupToolsDescription
fundamentalcalc_fundamental_indicators / calc_fundamental_trend / get_financial_data / get_report_datesFinancial indicator calculation
comparecompare_companies / compare_periodsFinancial comparison and trends
score-anomalyformat_financial_score / calc_financial_score / detect_anomaliesScoring and anomaly detection
screeningscreen_cashflow_positive_stocks / screen_margin_decline_stocks / screen_roe_stocksBatch screening
queryquery_financial_dataFinancial data query

Example Queries:

"Which banks have positive operating cash flow for the past year?"
"Compare CATL and BYD's debt ratio trends"
"Which companies had gross margin drop > 10% last quarter?"
"Give me a DuPont analysis for Kweichow Moutai"
"Find companies with ROE > 20% for 3 consecutive years"

Run:

python agents/financial_agent.py

5.10 Daily Market Report Agent

agents/daily_report_agent.py — Daily Market Report Agent

Integrates market overview, trend assessment, sector rotation, anomaly detection, news correlation, and watchlist report tool groups for natural language Q&A on daily market briefings.

Tool Group Structure:

Tool GroupToolsDescription
market-overviewget_market_overview / format_market_overviewMarket overview
market-trendanalyze_market_trend / format_market_trendTrend assessment
sector-analysisget_sector_ranking / get_sector_rotation / get_hot_cold_sectors etc. (8 tools)Sector analysis
abnormal-detectiondetect_abnormal / format_abnormalAnomaly detection
newsfind_news_by_keyword / search_news_with_marketNews search
watchlistget_watchlist_report / format_watchlist_reportWatchlist report
daily-digestgenerate_daily_digestOne-click daily report

Example Queries:

"Generate today's market morning briefing"
"Which stocks hit limit up today? Which sectors do they belong to?"
"How has market sentiment been this week?"
"Which sectors are seeing capital inflow?"
"What important news is there today?"
"How are my watchlist stocks performing?"

Run:

python agents/daily_report_agent.py

5.11 Daily Market Report Tools

tools/market_overview.py — Market Overview Tool

Aggregates all market stock data to compute daily market overview (advance/decline counts, limit up/down, turnover, etc.).

Core Functions:

FunctionDescription
get_market_overview(trade_date=None)Get market overview as structured data
format_market_overview(trade_date=None)Generate formatted Markdown output

Output Metrics:

MetricDescription
Advance/DeclineUp/down/flat counts and percentages
Limit Up/DownMain board >=9.9%, ChiNext/STAR >=19.9%
Total TurnoverMarket-wide turnover (100M CNY)
Avg/Median ChangeOverall market change level
Market SentimentStrong rally/Bullish/Neutral/Bearish/Weak decline

Run:

python tools/market_overview.py
python tools/market_overview.py --trade_date 20260801

tools/abnormal_detector.py — Anomaly Detection Tool

Detects daily market anomalies: limit up/down stocks, volume breakouts, abnormal price movements, sector anomalies.

Core Functions:

FunctionDescription
detect_abnormal(trade_date=None)Detect anomalies, return structured data
format_abnormal(trade_date=None)Generate formatted Markdown output

Detection Types:

TypeCondition
Limit Up/DownMain board >=9.9%, ChiNext/STAR >=19.9%
Volume BreakoutVolume ratio >3 AND gain >3% (ratio = current vol / 20-day avg vol)
Price Surge
Sector Anomaly

Run:

python tools/abnormal_detector.py
python tools/abnormal_detector.py --trade_date 20260801

tools/market_trend.py — Trend Assessment Tool

Multi-dimensional market sentiment analysis based on recent N-day data.

Core Functions:

FunctionDescription
analyze_market_trend(days=5)Analyze market trend, return structured data
format_market_trend(days=5)Generate formatted Markdown output

Scoring Dimensions (20 pts each, 100 total):

DimensionSourceLogic
Advance/Decline Ratiostock_kline 5-dayAverage advancing stock ratio
Limit Up/Down Ratiostock_kline latestLimit up / (up + down + 1)
Turnover Trendstock_kline 5-dayRecent 5d vs prior 5d, volume expansion/contraction
Sector Rotationsector_industry_dailyAdvancing sector ratio
Consecutive Trendstock_kline 5-dayConsecutive up/down days

Sentiment Mapping: >=75 Optimistic / >=60 Mildly Bullish / >=40 Neutral / >=25 Mildly Bearish / <25 Pessimistic

Run:

python tools/market_trend.py
python tools/market_trend.py --days 10

tools/watchlist_report.py — Watchlist Report Tool

Personalized daily report for user-watched stocks: daily performance, 5-day change, related news.

Core Functions:

FunctionDescription
get_watchlist_report(ts_codes, trade_date=None)Get watchlist report as structured data
format_watchlist_report(ts_codes, trade_date=None)Generate formatted Markdown output

Report Content:

ModuleDescription
Daily PerformanceClose price, change %, turnover
5-Day ChangeCumulative change over 5 trading days
Related NewsSearch news by stock name (max 3 per stock)

Watchlist Config: Edit tools/watchlist_config.json to set default watchlist.

Run:

python tools/watchlist_report.py --ts_codes 600519.SH,300750.SZ
python tools/watchlist_report.py # Use default from watchlist_config.json

tools/daily_digest.py — Daily Report Generator (Enhanced)

Generates complete daily market briefing by integrating all 6 modules.

Core Functions:

FunctionDescription
generate_daily_digest(trade_date=None, watchlist=None)Generate complete daily report (Markdown)

Report Structure:

SectionModuleSource
1Market Overviewmarket_overview.py
2Trend Assessmentmarket_trend.py
3Sector Rotationsector_ranking.py + sector_rotation.py
4Market Anomaliesabnormal_detector.py
5Important Newsnews_stock_linker.py
6Watchlist Report (optional)watchlist_report.py

Run:

python tools/daily_digest.py
python tools/daily_digest.py --trade_date 20260801
python tools/daily_digest.py --watchlist 600519.SH,300750.SZ

5.12 Tool Function Mapping

Existing langgraph_getdata/New tools/Description
query_market_data_day_k.pystock_query.pyStock K-line query
query_industry_index_market.pysector_query.pySector quote query
query_industry_component_list.pysector_query.pySector constituents
query_concept_dc_day.pysector_query.pyConcept sector quotes
query_concept_dc_stock.pysector_query.pyConcept sector constituents
query_fin_account.pyfinancial_query.pyFinancial statement query (Done)
(None)news_query.pyNews query (New)
(None)stock_fundamental.pyFundamental indicators (Done)
(None)stock_valuation.pyValuation percentile (Done)
(None)stock_technical.pyTechnical indicators (Done)
(None)stock_sector_mapping.pyStock-sector mapping (Done)
(None)sector_financial_agg.pySector financial aggregation (Done)
(None)news_stock_linker.pyNews-stock correlation (Done)
(None)financial_score.pyFinancial health scoring (Done)
(None)sector_data.pySector data utilities (Done)
(None)market_overview.pyMarket overview tool (Done)
(None)abnormal_detector.pyAnomaly detection tool (Done)
(None)market_trend.pyTrend assessment tool (Done)
(None)watchlist_report.pyWatchlist report tool (Done)
(None)daily_digest.pyDaily report generator (Done)

5.13 Dependencies

pip install agentscope>=2.0.3 fastapi uvicorn

About

Built on professional finance knowledge, it provides stock diagnostics, sector index analysis, investment Q&A and news insights to help investors capture market opportunities efficiently.

Resources

Stars

5 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Repository files navigation

FinAssistant Logo

FinAssistant — AI-Powered Financial Analysis

RAG Retrieval & Agent System for China A-Share Market

BackgroundFeaturesData AssetsImplementationTools

中文 | English


1. Background

The China A-share market has diverse data dimensions and massive information volumes. Retail investors and small-to-medium institutions struggle to efficiently integrate stock quotes, sector rotation, financial statements, and market news for comprehensive analysis. This project aims to build a financial RAG retrieval and agent system based on collected A-share data assets, enabling users to perform professional financial analysis through natural language conversations.

Core Objectives

  • Lower Analysis Barriers: Replace manual data queries, indicator calculations, and report writing with natural language
  • Multi-dimensional Data Correlation: Connect stocks, sectors, financials, and news for a panoramic view
  • Agent Collaboration: Multiple specialized agents working together, covering the full workflow from data queries to research reports

Tech Stack

LayerTechnology
Agent FrameworkAgentScope 2.0 (Multi-Agent Orchestration)
Data StorageMySQL (Structured Query) + Milvus (Vector Retrieval)
Data CollectionPython + akshare + DrissionPage
LLMQwen / GPT / Claude
Embeddingtext-embedding-v3 / BGE
FrontendStreamlit / Gradio

2. Feature Modules

Six intelligent agent modules planned based on existing data assets:


2.1 Stock Analysis Agent

Data Support: Daily stock quotes + Company info + Financial statements

Core Features:

FeatureDescriptionImplementation
Fundamental ScoreAuto-score (0-100) based on ROE, gross margin, debt ratio, cash flowExtract key fields from 3 statements, weighted calculation
Valuation PercentilePE/PB/PCF percentile in 1-year history, determine over/undervaluedCalculate percentile on daily PE/PB series
Technical IndicatorsMA(5/10/20/60), MACD, RSI, Bollinger Bands, KDJReal-time calculation based on OHLCV data
Trading SignalsGolden/Dead cross, MA breakout, RSI overbought/oversoldTechnical indicator crossover detection
Stock Profile ReportComprehensive fundamental + technical + valuation + sector reportLLM aggregates analysis results into text

Example Queries:

"How is Pudong Bank's cash flow situation this quarter?"
"What is Ping An Bank's current valuation percentile?"
"Analyze Kweichow Moutai's technical trend and give trading advice"
"Generate a stock profile report for CATL"

To-Do:

  • tools/stock_fundamental.py — Fundamental indicator calculator (Done)
  • tools/stock_valuation.py — Valuation percentile analyzer (Done)
  • tools/stock_technical.py — Technical indicator calculator (Done)
  • tools/stock_analysis.py — Comprehensive stock analysis report (Done)
  • agents/stock_agent.py — Stock analysis agent (Done)

Agent Demo:

$ python agents/stock_agent.py
============================================================
FinAssistant — 金融智能体
============================================================
输入股票代码或问题开始分析,输入 'quit' 退出
============================================================
你: 帮我分析贵州茅台的技术面走势,给出操作建议
FinAssistant:
[调用工具: reset_tools]
[完成] 结果: The currently activated tool group(s): stock-technical.
[调用工具: calc_technical_summary]
[完成] 结果: === 600519.SH 技术指标分析 (2026-07-17) ===
收盘价: 1253.0
【移动平均线 MA】
MA5: 1237.78
MA10: 1217.11
MA20: 1204.07
MA60: 1263.65
均线趋势: 多头排列
【MACD】
DIF: -0.2443
DEA: -11.3353
MACD柱: 22.182
信号: 金叉
【RSI】
RSI(6): 92.76
RSI(12): 68.8
RSI(24): 48.73
RSI(6)信号: 超买
【布林带 BOLL】
上轨: 1252.21
中轨: 1204.07
下轨: 1155.92
【KDJ】
K: 84.3
D: 79.2
J: 94.49
信号: 金叉
【综合研判】
当前信号: MA多头排列, MACD金叉, RSI超买, KDJ金叉
### 贵州茅台(600519.SH)技术面分析与操作建议
#### 一、核心技术指标摘要(近120天)
| 指标类型 | 关键数据 | 信号解读 |
|---------|---------|---------|
| **均线系统** | MA5:1237.78, MA10:1217.11, MA20:1204.07, MA60:1263.65 | 短期均线多头排列,股价略低于MA60(1263.65),中期趋势依然向上 |
| **MACD** | DIF:-0.24, DEA:-11.34, MACD柱:22.18 | 低位金叉形成,空头趋势减弱,短期反弹信号明确 |
| **RSI** | RSI(6):92.76, RSI(12):68.80, RSI(24):48.73 | 短期RSI严重超买(>90),警惕回调风险 |
| **布林带** | 上轨:1252.21, 中轨:1204.07, 下轨:1155.92 | 股价突破上轨,处于强势区间,但短期乖离率偏大 |
| **KDJ** | K:84.30, D:79.20, J:94.49 | 高位金叉,短期上涨动能充足,但J线接近超买区 |
#### 二、综合研判
技术面呈现**强趋势与短期超买并存**的格局:
1. **多头趋势明确**:均线多头排列、MACD低位金叉、KDJ金叉共同构成中期上涨信号
2. **短期回调风险**:RSI超买、股价突破布林上轨提示短期涨幅过大,存在技术性回调需求
#### 三、操作建议
1. **持仓投资者**:
- 继续持有为主,可将MA20(1204.07)作为止损线
- 若股价回落至MA5-MA10区间(1217-1238)可适当加仓
- 短期若冲高至MA60(1263.65)遇阻,可考虑部分止盈
2. **观望投资者**:
- 等待回调至关键支撑位(MA20:1204或布林中轨:1204)再考虑进场
- 若股价直接突破MA60并站稳,可小仓位追涨
⚠️ **风险提示**:技术分析仅供参考,不构成投资建议。市场存在不确定性,需结合自身风险承受能力决策。

2.2 Sector Rotation Analysis Agent

Data Support: Industry/Concept sector daily quotes (90 industry + 374 concept) + Constituent stocks

Core Features:

FeatureDescriptionImplementation
Sector RankingRank by pct_chg, volume change, capital flowAggregate sector daily_index
Rotation TrendSectors with consecutive top N-day gains marked as "hot"Sliding window rank change analysis
Sector ComparisonMulti-sector price curves overlayExtract multiple sector close series
Constituent DistributionAdvance/decline count, limit up/down, median changeLink constituent daily data
Capital FlowVolume change trend, determine inflow/outflowVolume QoQ change analysis
Sector CorrelationConstituent stock overlap between two sectorsSet intersection/union ratio

Example Queries:

"Which industry sectors had the highest gains this week?"
"How has the semiconductor sector performed this month? Is capital flowing in or out?"
"How high is the overlap between AI and robotics concept constituents?"
"Which sectors had limit-down waves today?"

To-Do:

  • tools/sector_ranking.py — Sector ranking tool (Done)
  • tools/sector_rotation.py — Rotation trend identifier (Done)
  • tools/sector_compare.py — Sector comparison tool (Done)
  • tools/sector_detail.py — Sector deep analysis tool (Done)
  • agents/sector_agent.py — Sector analysis agent (Done)

Agent Demo:

$ python agents/sector_agent.py
============================================================
FinAssistant — 板块轮动分析智能体
============================================================
输入板块相关问题开始分析,输入 'quit' 退出
示例:
- 最近一周涨幅最大的行业板块有哪些?
- 半导体板块最近一个月资金是在流入还是流出?
- AI概念和机器人概念的成分股重叠度有多高?
- 今天哪些板块出现了跌停潮?
============================================================
你: 最近一周涨幅最大的行业板块有哪些?
FinAssistant:
[调用工具: get_sector_ranking]
[完成] 结果: === 行业板块涨跌幅排名 (2026-07-17) ===
Top 10:
排名 板块名称 涨跌幅(%) 成交额(亿)
1 通信设备 +5.23 312.45
2 半导体 +4.87 528.91
3 消费电子 +3.65 287.33
...
[调用工具: get_sector_top_gainers]
[完成] 结果: === 连续3天上涨的行业板块 ===
板块名称 连涨天数 累计涨幅(%)
半导体 3 +8.92
通信设备 3 +7.56
...
综合来看,最近一周涨幅最大的行业板块主要集中在科技领域:
1. **通信设备** (+5.23%) — 5G建设持续推进,板块领涨
2. **半导体** (+4.87%) — 国产替代逻辑强化,资金持续流入
3. **消费电子** (+3.65%) — 新品发布预期带动板块走强
其中半导体和通信设备已连续3天上涨,短期动能较强。
⚠️ 风险提示:板块轮动较快,追高需谨慎。以上分析仅供参考,不构成投资建议。

2.3 Cross-Data Correlation Analysis Agent

Data Support: Quotes + Constituents + Financial statements + News (Full data cross-correlation)

Core Features:

FeatureDescriptionImplementation
Stock→Sector MappingQuery which sectors a stock belongs to, recent performanceReverse lookup in constituent data
Sector→Financial AggregationAverage ROE, median PE, total revenue for sector constituentsLink constituent codes to financial statements
News→Quote CorrelationCompanies/sectors mentioned in news, link to recent price trendsNER entity recognition + code matching
Industry ChainInfer upstream/downstream relationships via concept overlapConstituent set similarity clustering
Leader EffectTop N stocks by market cap vs sector overall performanceMarket-cap weighted vs equal-weight index

Example Queries:

"Which concept sectors does BYD belong to? How are they performing?"
"What's the average PE and ROE for the semiconductor sector?"
"Any recent news about solar power? How are related sectors trending?"
"Find the top 5 stocks most correlated with CATL"

To-Do:

  • tools/stock_sector_mapping.py — Stock-sector mapping tool (Done)
  • tools/sector_financial_agg.py — Sector financial aggregation (Done)
  • tools/news_stock_linker.py — News-quote correlation tool (Done)
  • agents/correlation_agent.py — Correlation analysis agent (Done)

2.4 Financial Q&A Agent (RAG)

Data Support: Financial statements (4,593 stocks × multi-period) + Vector database (Milvus)

Core Features:

FeatureDescriptionImplementation
NL Financial Query"Which companies have gross margin > 50%" → SQL/Vector searchVectorize financial fields + structured query
Cross-stock ComparisonHorizontal comparison of financial indicators for same-industry companiesGroup by industry + indicator comparison
Multi-period TrendVertical comparison of same company across periodsTime series analysis + trend detection
Anomaly AlertCash flow plunge, receivables surge, goodwill impairmentThreshold/QoQ change detection
Financial Health ScoreComprehensive solvency, profitability, growth, operational abilityDuPont analysis system + weighted scoring

Example Queries:

"Which banks have positive operating cash flow for the past year?"
"Compare CATL and BYD's debt ratio trends"
"Which companies had gross margin drop > 10% last quarter?"
"Give me a DuPont analysis for Kweichow Moutai"
"Find companies with ROE > 20% for 3 consecutive years"

To-Do:

  • tools/financial_query.py — Financial data query tool (Done)
  • tools/financial_compare.py — Financial comparison tool (Done)
  • tools/financial_anomaly.py — Anomaly detection tool (Done)
  • tools/financial_score.py — Financial health scoring tool (Done)
  • agents/financial_agent.py — Financial Q&A agent (Done)
  • rag/financial_embedding.py — Financial statement vectorization

2.5 Daily Market Report Agent

Data Support: Full data (Quotes + Sectors + News + Financials)

Core Features:

FeatureDescriptionImplementation
Market OverviewMajor index changes, volume, advance/decline statsAggregate all market stock data
Sector Rotation SummaryTop gainers/losers, capital inflow/outflow Top5Sector ranking tool output
Anomaly DetectionLimit up/down, volume breakout, abnormal volatilityFilter conditions
News SummaryMarket-related important news, linked sectorsNews filtering + LLM summary
Watchlist ReportUser's watched stocks daily performance, announcementsPersonalized filtering
Trend AssessmentBased on recent N-day data, market sentiment judgmentMulti-indicator synthesis

Example Queries:

"Generate today's market morning briefing"
"Which stocks hit limit up today? Which sectors do they belong to?"
"How has market sentiment been this week?"
"How are my watchlist stocks performing today?"

To-Do:

  • tools/market_overview.py — Market overview tool (Done)
  • tools/abnormal_detector.py — Anomaly detection tool (Done)
  • tools/market_trend.py — Trend assessment tool (Done)
  • tools/watchlist_report.py — Watchlist report tool (Done)
  • tools/daily_digest.py — Daily report generator (Done, integrates all 6 modules)
  • agents/daily_report_agent.py — Daily report agent (Done)

2.6 Research Report Generation Agent

Data Support: Full data + LLM generation capabilities

Core Features:

FeatureDescriptionImplementation
Stock Deep ReportComprehensive fundamental + technical + valuation + industry positionCall previous tools + LLM long-text generation
Industry ResearchSector trends, constituent financials, industry chain analysisSector tools + Financial tools + LLM
Comparative Report2-3 same-industry companies multi-dimensional comparisonComparison tools + LLM
Event Impact AnalysisNews/policy impact on related sectors and stocksNews correlation + Historical analogy + LLM
Portfolio SuggestionRecommend sector/stock allocation based on risk preferenceOptimization algorithm + LLM

Example Queries:

"Write a deep research report on the semiconductor industry"
"Compare BYD, CATL, and LONGi Green Energy with a comparative analysis"
"Which A-share sectors are most affected by Fed rate hikes?"
"I prefer conservative investing, recommend some sector allocation plans"

To-Do:

  • tools/report_generator.py — Report generation tool (LLM + templates)
  • templates/ — Report templates (stock/industry/comparison/event)
  • agents/report_agent.py — Report generation agent
  • agents/portfolio_agent.py — Portfolio optimization agent

3. Data Assets

3.1 Data Overview

Data TypeVolumeSourceTime Range
SH Stock Daily Quotes2,308 stocksSina Finance (akshare)2026-01-01 ~ Present
SZ Stock Daily Quotes2,895 stocksSina Finance (akshare)2026-01-01 ~ Present
SH Company Info2,308 (Main 1,699 + STAR 609)SSE (akshare)-
SZ Company Info2,895SZSE (akshare)-
SH Financial Statements2,308 stocksSina Finance (akshare)Recent 3 years
SZ Financial Statements2,895 stocksSina Finance (akshare)Recent 3 years
Industry Sector Quotes90 sectorsTonghuashun (akshare)2026-01-01 ~ Present
Concept Sector Quotes374 sectorsTonghuashun (akshare)2026-01-01 ~ Present
Industry Constituents90 sectorsTonghuashun (DrissionPage)-
Concept Constituents374 sectorsTonghuashun (DrissionPage)-
Financial News-Tonghuashun 7x242026-01-01 ~ Present

3.2 MySQL Table Schema

Data is stored in Alibaba Cloud RDS MySQL with two databases: market_data (quotes/financials) and stock_news (news).

market_data.company_info — Company Basic Info

CREATETABLEcompany_info (
id INT AUTO_INCREMENT PRIMARY KEY COMMENT 'Auto-increment ID',
ts_code VARCHAR(20) NOT NULL COMMENT 'Stock code with suffix, e.g., 600000.SH',
symbol VARCHAR(10) NOT NULL COMMENT 'Stock code (numeric only)',
stock_name VARCHAR(50) COMMENT 'Stock short name',
full_name VARCHAR(100) COMMENT 'Company full name',
industry VARCHAR(50) COMMENT 'Industry, e.g., J Finance',
list_date VARCHAR(20) COMMENT 'Listing date, format YYYY-MM-DD',
market VARCHAR(5) COMMENT 'Market, SH=Shanghai SZ=Shenzhen',
updated_at VARCHAR(30) COMMENT 'Data update time',
UNIQUE KEY uk_ts_code (ts_code)
)

market_data.stock_kline — Stock Daily K-line

CREATETABLEstock_kline (
id BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT 'Auto-increment ID',
ts_code VARCHAR(20) NOT NULL COMMENT 'Stock code with suffix',
symbol VARCHAR(10) NOT NULL COMMENT 'Stock code (numeric only)',
trade_date VARCHAR(20) NOT NULL COMMENT 'Trade date, format YYYY-MM-DD',
open DOUBLE COMMENT 'Open price (CNY)',
close DOUBLE COMMENT 'Close price (CNY)',
high DOUBLE COMMENT 'High price (CNY)',
low DOUBLE COMMENT 'Low price (CNY)',
pre_close DOUBLE COMMENT 'Previous close (CNY)',
change_data DOUBLE COMMENT 'Price change (CNY)',
pct_chg DOUBLE COMMENT 'Change percentage (%)',
volume DOUBLE COMMENT 'Volume (shares)',
amount DOUBLE COMMENT 'Turnover (CNY)',
pe DOUBLE COMMENT 'P/E ratio',
pb DOUBLE COMMENT 'P/B ratio',
total_mv DOUBLE COMMENT 'Total market cap (100M CNY)',
total_share DOUBLE COMMENT 'Total shares',
float_share DOUBLE COMMENT 'Float shares',
circ_mv DOUBLE COMMENT 'Circulating market cap (100M CNY)',
ln_pctchg DOUBLE COMMENT 'Log return',
pe_ttm DOUBLE COMMENT 'P/E ratio (TTM)',
pe_static DOUBLE COMMENT 'Static P/E ratio',
pcf DOUBLE COMMENT 'Price-to-Cash-Flow ratio',
UNIQUE KEY uk_code_date (ts_code, trade_date),
KEY idx_trade_date (trade_date),
KEY idx_symbol (symbol)
)

market_data.stock_financial — Financial Statements

CREATETABLEstock_financial (
id BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT 'Auto-increment ID',
ts_code VARCHAR(20) NOT NULL COMMENT 'Stock code with suffix',
symbol VARCHAR(10) NOT NULL COMMENT 'Stock code (numeric only)',
statement_type VARCHAR(20) NOT NULL COMMENT 'Statement type: income/balance/cashflow',
report_date VARCHAR(20) NOT NULL COMMENT 'Report date, e.g., 20260331',
report_data JSON COMMENT 'Complete statement data (JSON)',
UNIQUE KEY uk_code_type_date (ts_code, statement_type, report_date),
KEY idx_symbol (symbol),
KEY idx_report_date (report_date),
KEY idx_statement_type (statement_type)
)

Financial fields vary significantly across industries (banking vs manufacturing), hence JSON storage for complete statement data.

market_data.sector_industry_daily / sector_concept_daily — Sector Daily K-line

CREATETABLEsector_industry_daily (
id BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT 'Auto-increment ID',
sector_name VARCHAR(50) NOT NULL COMMENT 'Sector name',
sector_code VARCHAR(20) NOT NULL COMMENT 'Sector code',
trade_date VARCHAR(20) NOT NULL COMMENT 'Trade date',
open DOUBLE COMMENT 'Open',
high DOUBLE COMMENT 'High',
low DOUBLE COMMENT 'Low',
close DOUBLE COMMENT 'Close',
vol DOUBLE COMMENT 'Volume',
amount DOUBLE COMMENT 'Turnover',
pct_chg DOUBLE COMMENT 'Change (%)',
change_data DOUBLE COMMENT 'Point change',
pct_change DOUBLE COMMENT 'Change (backup)',
turnover_rate DOUBLE COMMENT 'Turnover rate',
UNIQUE KEY uk_code_date (sector_code, trade_date),
KEY idx_trade_date (trade_date),
KEY idx_sector_name (sector_name)
)

market_data.sector_industry_cons / sector_concept_cons — Sector Constituents

CREATETABLEsector_industry_cons (
id BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT 'Auto-increment ID',
sector_name VARCHAR(50) NOT NULL COMMENT 'Sector name',
sector_code VARCHAR(20) NOT NULL COMMENT 'Sector code',
stock_code VARCHAR(10) NOT NULL COMMENT 'Stock code',
stock_name VARCHAR(50) COMMENT 'Stock name',
UNIQUE KEY uk_sector_stock (sector_code, stock_code),
KEY idx_sector_name (sector_name),
KEY idx_stock_code (stock_code)
)

stock_news.news_em — Eastmoney 7x24 News

CREATETABLEnews_em (
id INT AUTO_INCREMENT PRIMARY KEY COMMENT 'Auto-increment ID',
title VARCHAR(500) NOT NULL COMMENT 'News title',
digest TEXT COMMENT 'News digest',
publish_time VARCHAR(30) COMMENT 'Publish time',
url VARCHAR(500) COMMENT 'News URL',
crawl_time VARCHAR(30) COMMENT 'Crawl time',
UNIQUE KEY uk_title_time (title, publish_time)
)

stock_news.news_ths — Tonghuashun Financial News

CREATETABLEnews_ths (
id INT AUTO_INCREMENT PRIMARY KEY COMMENT 'Auto-increment ID',
news_id VARCHAR(20) NOT NULL COMMENT 'News ID',
title VARCHAR(500) NOT NULL COMMENT 'News title',
digest TEXT COMMENT 'News digest',
url VARCHAR(500) COMMENT 'News URL',
tags VARCHAR(500) COMMENT 'Tags (comma separated)',
ctime_str VARCHAR(30) COMMENT 'Publish time',
source VARCHAR(100) COMMENT 'Source',
crawl_time VARCHAR(30) COMMENT 'Crawl time',
UNIQUE KEY uk_news_id (news_id),
KEY idx_ctime (ctime_str)
)

3.3 Data Import Scripts

ScriptTarget TableDescription
import_company_info_to_mysql.pymarket_data.company_infoSH/SZ company info
import_kline_to_mysql.pymarket_data.stock_klineStock daily K-line (560K+ rows)
import_financial_to_mysql.pymarket_data.stock_financialFinancial statements (170K+ rows)
import_sector_to_mysql.pymarket_data.sector_*_dailySector daily K-line
import_sector_cons_to_mysql.pymarket_data.sector_*_consSector constituents
import_news_em_to_mysql.pystock_news.news_emEastmoney news
import_news_ths_to_mysql.pystock_news.news_thsTonghuashun news

3.4 Data Collection Scripts

ScriptPurposeSource
crawl_sh_stock_data.pySH stock quotes + company infoSina Finance / SSE
crawl_sz_stock_data.pySZ stock quotes + company infoSina Finance / SZSE
crawl_financial_reports.pyFinancial statementsSina Finance
crawl_sector_data.pySector daily quotes (Industry + Concept)Tonghuashun (akshare)
crawl_sector_cons.pySector constituentsSina Finance (akshare)
crawl_sector_cons_ths.pySector constituents (backup)Tonghuashun (DrissionPage)
crawl_news_ths.pyFinancial newsTonghuashun 7x24 API
crawl_news_em.pyEastmoney 7x24 news (scheduled)Eastmoney (akshare)

3.5 Known Issues

IssueDescription
Eastmoney API Blockedpush2his.eastmoney.com completely unavailable
Tonghuashun IP BlockedFrequent crawling triggers Nginx 403 block
Inconsistent Sector SourcesQuotes from THS, constituents partially from Sina, names may not match
SH Company Missing IndustrySSE API doesn't provide industry field

4. AgentScope 2.0 Implementation

4.1 Architecture

User Query → FastAPI → Agent (system_prompt + model + toolkit + middlewares)
↓
Toolkit
├── ToolGroup("Stock Analysis") → tools/stock_query.py + skills/stock-analysis/
├── ToolGroup("Sector Analysis") → tools/sector_query.py + skills/sector-rotation/
├── ToolGroup("Financial Q&A") → tools/financial_query.py + skills/financial-qa/
├── ToolGroup("Daily Report") → tools/news_query.py + skills/daily-report/
└── ToolGroup("Research Report") → tools/indicators.py + skills/research-report/

4.2 Directory Structure

FinAssistant/
├── config.py # Global config (paths, model, API Key)
├── main.py # FastAPI service entry
├── main_agent.py # Single agent script (no server, direct chat)
├── core/
│ ├── agent_setup.py # Agent + Toolkit initialization
│ └── middleware.py # Financial scenario middleware
├── tools/ # Tool functions
│ ├── __init__.py
│ ├── stock_query.py # Stock quote/company info query
│ ├── sector_query.py # Sector quote/constituent query
│ ├── financial_query.py # Financial statement query & analysis
│ ├── news_query.py # News query
│ └── indicators.py # Technical/fundamental indicator calculation
├── skills/ # Skill documents (SKILL.md)
│ ├── stock-analysis/SKILL.md
│ ├── sector-rotation/SKILL.md
│ ├── financial-qa/SKILL.md
│ ├── daily-report/SKILL.md
│ └── research-report/SKILL.md
├── data/ # Existing data (don't modify)
└── data_to_mysql_and_milvus/ # Existing crawler scripts (don't modify)

4.3 Implementation Steps

Step 1: config.py

Global configuration for data paths, model config, API keys.

Step 2: tools/ Tool Functions

Each function is async def, returns ToolChunk. Docstring is the tool description — LLM decides when to call based on docstring.

Step 3: skills/SKILL.md Skill Documents

Each skill directory has a SKILL.md with trigger conditions, dependent tools, and execution flow.

Step 4: core/middleware.py Middleware

MiddlewarePurpose
InputValidationMiddlewareFilter non-financial queries
ToolCallAuditMiddlewareLog tool calls to traces/
PerformanceMonitorMiddlewareMonitor inference rounds, latency, tokens
ContextEnrichmentMiddlewareInject current date, trading day context

Step 5: core/agent_setup.py Agent Initialization

Assemble model, tools, toolkit, and agent with middleware.

Step 6: main.py Service Entry

FastAPI service with OpenAI-compatible /v1/chat/completions endpoint.


5. Implemented Tools

tools/stock_fundamental.py — Fundamental Indicator Calculator

Calculates fundamental indicators from MySQL market_data.stock_financial table.

Core Functions:

FunctionDescription
calc_fundamental_indicators(ts_code, report_date=None)Calculate single-period indicators
calc_fundamental_trend(ts_code, periods=4)Calculate recent N-period trend
get_financial_data(ts_code, report_date=None)Get raw statement data
get_report_dates(ts_code, limit=8)Get report date list

Calculated Indicators:

IndicatorFormulaData Source
ROENet Profit / Equity × 100%Income + Balance Sheet
Gross Margin(Revenue - COGS) / Revenue × 100%Income Statement
Net MarginNet Profit / Revenue × 100%Income Statement
Debt RatioTotal Liabilities / Total Assets × 100%Balance Sheet
Cash Flow / Net ProfitOperating Cash Flow / Net ProfitCash Flow + Income
Revenue YoY Growth(Current - Prior Year) /Prior Year
Net Profit YoY Growth(Current - Prior Year) /Prior Year
Revenue QoQ Growth(Current Q - Prior Q) /Prior Q
Net Profit QoQ Growth(Current Q - Prior Q) /Prior Q

Special Handling:

  • Auto bank detection: Via balance sheet fields (loans, deposits)
  • Bank field mapping: Revenue = Net Interest Income + Fee Income; COGS = Interest Expense + Fee Expense
  • YoY calculation: Cumulative values vs same quarter last year (2026Q1 vs 2025Q1)
  • QoQ calculation: Single-quarter values (Q4 = Annual - 9-month cumulative)

Usage:

fromtools.stock_fundamentalimportcalc_fundamental_indicators, calc_fundamental_trend# Single periodresult=calc_fundamental_indicators('600519.SH')
print(result['ROE'], result['毛利率'], result['营收同比增长率'])
# Trend (recent 4 periods)trend=calc_fundamental_trend('600519.SH', periods=4)
fortintrend['trend']:
print(t['report_date'], t['ROE'], t['营收同比增长率'])

tools/stock_valuation.py — Valuation Percentile Analyzer

Calculates PE/PB/PCF percentile in 1-year history from market_data.stock_kline table.

Core Functions:

FunctionDescription
calc_valuation_percentile(ts_code, days=365)Calculate valuation percentile, return structured data
calc_valuation_summary(ts_code, days=365)Generate formatted valuation summary
get_valuation_history(ts_code, days=365)Get N-day valuation history
get_latest_valuation(ts_code)Get latest day valuation data

Valuation Indicators:

IndicatorDescriptionSource
PE_TTMPrice-to-Earnings (Trailing Twelve Months)stock_kline.pe_ttm
PBPrice-to-Bookstock_kline.pb
PCFPrice-to-Cash-Flowstock_kline.pcf

Percentile Rules:

PercentileLevelMeaning
< 20%UndervaluedAt historical low, potentially undervalued
20% - 40%Below AverageBelow historical median
40% - 60%FairAt historical median range
60% - 80%Above AverageAbove historical median
> 80%OvervaluedAt historical high, potentially overvalued

Usage:

fromtools.stock_valuationimportcalc_valuation_percentile, calc_valuation_summary# Get structured dataresult=calc_valuation_percentile('600519.SH')
print(f"PE_TTM: {result['pe_ttm']}, Percentile: {result['pe_ttm_percentile']}%, {result['pe_ttm_level']}")
# Get formatted summaryprint(calc_valuation_summary('600519.SH'))

tools/stock_technical.py — Technical Indicator Calculator

Calculates MA/MACD/RSI/BOLL/KDJ indicators from MySQL market_data.stock_kline table.

Core Functions:

FunctionDescription
calc_technical_indicators(ts_code, days=120)Calculate all technical indicators
calc_technical_summary(ts_code, days=120)Generate formatted summary
get_kline_data(ts_code, days=120)Get K-line data from MySQL

Technical Indicators:

IndicatorFormulaUsage
MA(5/10/20/60)Average of last N closing pricesTrend: Price above MA = bullish; MA crossover = buy/sell signal
MACDDIF = EMA(12) - EMA(26); DEA = EMA(DIF,9); Histogram = (DIF-DEA)×2Golden cross (DIF>DEA) = buy; Dead cross = sell
RSI(6/12/24)RS = Avg Gain / Avg Loss; RSI = 100 - 100/(1+RS)>80 = overbought; <20 = oversold
BOLL(20,2)Upper = MA+2σ; Middle = MA; Lower = MA-2σTouch upper = overbought; Touch lower = oversold
KDJ(9,3,3)RSV, K = 2/3K+1/3RSV, D = 2/3D+1/3K, J = 3K-2DK>80 = overbought; K<20 = oversold; K/D crossover

Signal Interpretation:

SignalMAMACDRSIBOLLKDJ
BullishMA5>MA10>MA20 (Bull alignment)DIF>DEA, Histogram>0RSI<20 (Oversold)Price bounces off lower bandK/D golden cross in oversold zone
BearishMA5<MA10<MA20 (Bear alignment)DIF<DEA, Histogram<0RSI>80 (Overbought)Price falls from upper bandK/D dead cross in overbought zone

Multi-indicator Confirmation:

Buy signals (need 2-3):

  • Price above MA20, MA bullish alignment (MA5>MA10>MA20)
  • MACD golden cross (DIF crosses above DEA)
  • RSI rebounds from oversold (<20 → >20)
  • Price bounces off Bollinger lower band
  • KDJ golden cross in oversold zone

Sell signals (need 2-3):

  • Price below MA20, MA bearish alignment (MA5<MA10<MA20)
  • MACD dead cross (DIF crosses below DEA)
  • RSI enters overbought (>80) then falls
  • Price falls from Bollinger upper band
  • KDJ dead cross in overbought zone

Usage:

fromtools.stock_technicalimportcalc_technical_indicators, calc_technical_summary# Get structured dataresult=calc_technical_indicators('600519.SH')
print(f"Close: {result['close']}, MA5: {result['ma5']}, MACD: {result['macd_signal']}")
# Get formatted summaryprint(calc_technical_summary('600519.SH'))

5.5 Sector Analysis Tools

tools/sector_ranking.py — Sector Ranking Tool

Calculates sector rankings from MySQL sector_industry_daily / sector_concept_daily tables.

Core Functions:

FunctionDescription
get_sector_ranking(sector_type, trade_date, top_n, sort_by)Sector ranking by pct_chg/amount/volume
get_sector_top_gainers(sector_type, days, top_n)Sectors with consecutive N-day gains
get_sector_top_losers(sector_type, days, top_n)Sectors with consecutive N-day losses
get_sector_summary(sector_type, trade_date)Market overview (advance/decline, limit up/down)

Usage:

fromtools.sector_rankingimportget_sector_ranking, get_sector_top_gainers, get_sector_summary# Top 10 industry sectors by pct_chgprint(get_sector_ranking(sector_type='industry', top_n=10))
# Sectors rising for 3 consecutive daysprint(get_sector_top_gainers(sector_type='industry', days=3))
# Industry sector market overviewprint(get_sector_summary(sector_type='industry'))

tools/sector_rotation.py — Rotation Trend Identifier

Analyzes sector momentum and capital rotation direction through short-term vs medium-term performance comparison.

Core Functions:

FunctionDescription
get_sector_momentum(sector_type, short_days, long_days, top_n)Momentum analysis — short vs medium term, momentum score
get_sector_rotation(sector_type, short_days, long_days, top_n)Rotation identification — capital inflow/outflow sectors
get_sector_strength(sector_type, days, top_n)Strength ranking — composite score of gains, up-days, volume
get_hot_cold_sectors(sector_type, days)Hot/cold classification — hot/warm/flat/cold categories

Usage:

fromtools.sector_rotationimportget_sector_momentum, get_sector_rotation, get_hot_cold_sectors# Industry sector momentum (3-day short vs 10-day medium)print(get_sector_momentum(sector_type='industry', short_days=3, long_days=10))
# Sector rotation (capital inflow/outflow)print(get_sector_rotation(sector_type='industry'))
# Hot/cold sector classificationprint(get_hot_cold_sectors(sector_type='industry', days=5))

tools/sector_compare.py — Sector Comparison Tool

Multi-sector price curve overlay comparison with normalization and ASCII trend charts.

Core Functions:

FunctionDescription
compare_sectors(sector_names, sector_type, days)Multi-sector cumulative return comparison (table + ASCII chart)
compare_sector_trend(sector_names, sector_type, days)Trend strength comparison with conclusion

Usage:

fromtools.sector_compareimportcompare_sectors, compare_sector_trend# Compare Baijiu vs Power vs Banks over 20 daysprint(compare_sectors(['白酒', '电力', '银行'], sector_type='industry', days=20))
# Trend strength comparison with conclusionprint(compare_sector_trend(['白酒', '电力', '银行', '证券'], days=20))

tools/sector_detail.py — Sector Deep Analysis Tool

Links constituent stock data to provide internal sector structure analysis.

Core Functions:

FunctionDescription
get_constituent_distribution(sector_name, sector_type, trade_date)Constituent distribution — advance/decline, limit up/down, median change, top/bottom 5
get_sector_money_flow(sector_name, sector_type, days)Capital flow analysis — volume trend, price-volume coordination, inflow/outflow
get_sector_correlation(sector_name1, sector_name2, sector_type)Sector correlation — Jaccard coefficient, overlapping constituents

Usage:

fromtools.sector_detailimportget_constituent_distribution, get_sector_money_flow, get_sector_correlation# Baijiu sector constituent distributionprint(get_constituent_distribution('白酒', sector_type='industry'))
# Power sector capital flow analysisprint(get_sector_money_flow('电力', sector_type='industry', days=10))
# Baijiu vs Beer sector correlationprint(get_sector_correlation('白酒', '啤酒', sector_type='industry'))

tools/news_stock_linker.py — News-Stock Linker

Links news headlines to mentioned companies/sectors and correlates with their recent price trends.

Core Functions:

FunctionDescription
find_news_by_keyword(keyword, limit)Search news by keyword (title/digest fuzzy match)
search_news_with_market(keyword, limit, days_before, days_after)Search news and auto-correlate with matched stocks/sectors price trends

Usage Example:

fromtools.news_stock_linkerimportfind_news_by_keyword, search_news_with_market# Search news by keywordprint(find_news_by_keyword('半导体', limit=5))
# Search news and correlate with market dataprint(search_news_with_market('贵州茅台', limit=3, days_before=3, days_after=3))

5.6 Sector Analysis Agent

agents/sector_agent.py — Sector Analysis Agent

Integrates sector ranking, rotation, comparison, and deep analysis tool groups for sector rotation analysis.

Tool Group Structure:

Tool GroupToolsDescription
sector-rankingget_sector_ranking / get_sector_top_gainers / get_sector_top_losers / get_sector_summarySector ranking
sector-rotationget_sector_momentum / get_sector_rotation / get_sector_strength / get_hot_cold_sectorsRotation analysis
sector-comparecompare_sectors / compare_sector_trendSector comparison
sector-detailget_constituent_distribution / get_sector_money_flow / get_sector_correlationDeep analysis

Run:

python agents/sector_agent.py

5.7 Correlation Analysis Agent

agents/correlation_agent.py — Correlation Analysis Agent

Integrates stock-sector mapping, sector financial aggregation, and news-market correlation tool groups for cross-data analysis.

Tool Group Structure:

Tool GroupToolsDescription
stock-sectorfind_stock_sectorsStock-sector mapping
sector-financeget_sector_financial_agg / get_sector_valuation_statsSector financial aggregation, valuation distribution
news-marketfind_news_by_keyword / search_news_with_marketNews search, news-market correlation

Run:

python agents/correlation_agent.py

5.8 Financial Health Scoring Tool

tools/financial_score.py — Financial Health Scoring Tool

Computes a four-dimension composite financial health score (0-100) with rating (Excellent/Good/Fair/Poor).

Scoring Dimensions:

DimensionWeightIndicators
Profitability30%ROE(40%) + Gross Margin(30%) + Net Margin(30%)
Growth25%Revenue YoY Growth(50%) + Net Profit YoY Growth(50%)
Safety25%Debt Ratio(40%) + Cash Flow/NP(35%) + AR Ratio(25%)
Quality20%Deducted NP Ratio(50%) + Cash Flow Consistency(50%)

Anomaly Deduction: HIGH -5pts, MEDIUM -2pts, max -15pts.

Core Functions:

FunctionDescription
calc_financial_score(ts_code, report_date=None)Calculate single stock financial health score
format_financial_score(ts_code, report_date=None)Generate formatted Markdown output
score_sector(sector_name, sector_type, top_n)Batch score sector constituents

Run:

python tools/financial_score.py --ts_code 600519.SH
python tools/financial_score.py --sector 白酒 --top_n 10
python tools/financial_score.py --ts_codes 600519.SH,300750.SZ,601318.SH

5.9 Financial Q&A Agent

agents/financial_agent.py — Financial Q&A Agent

Integrates fundamental indicators, trend analysis, comparison, anomaly detection, financial scoring, and batch screening tool groups for complex financial Q&A.

Tool Group Structure:

Tool GroupToolsDescription
fundamentalcalc_fundamental_indicators / calc_fundamental_trend / get_financial_data / get_report_datesFinancial indicator calculation
comparecompare_companies / compare_periodsFinancial comparison and trends
score-anomalyformat_financial_score / calc_financial_score / detect_anomaliesScoring and anomaly detection
screeningscreen_cashflow_positive_stocks / screen_margin_decline_stocks / screen_roe_stocksBatch screening
queryquery_financial_dataFinancial data query

Example Queries:

"Which banks have positive operating cash flow for the past year?"
"Compare CATL and BYD's debt ratio trends"
"Which companies had gross margin drop > 10% last quarter?"
"Give me a DuPont analysis for Kweichow Moutai"
"Find companies with ROE > 20% for 3 consecutive years"

Run:

python agents/financial_agent.py

5.10 Daily Market Report Agent

agents/daily_report_agent.py — Daily Market Report Agent

Integrates market overview, trend assessment, sector rotation, anomaly detection, news correlation, and watchlist report tool groups for natural language Q&A on daily market briefings.

Tool Group Structure:

Tool GroupToolsDescription
market-overviewget_market_overview / format_market_overviewMarket overview
market-trendanalyze_market_trend / format_market_trendTrend assessment
sector-analysisget_sector_ranking / get_sector_rotation / get_hot_cold_sectors etc. (8 tools)Sector analysis
abnormal-detectiondetect_abnormal / format_abnormalAnomaly detection
newsfind_news_by_keyword / search_news_with_marketNews search
watchlistget_watchlist_report / format_watchlist_reportWatchlist report
daily-digestgenerate_daily_digestOne-click daily report

Example Queries:

"Generate today's market morning briefing"
"Which stocks hit limit up today? Which sectors do they belong to?"
"How has market sentiment been this week?"
"Which sectors are seeing capital inflow?"
"What important news is there today?"
"How are my watchlist stocks performing?"

Run:

python agents/daily_report_agent.py

5.11 Daily Market Report Tools

tools/market_overview.py — Market Overview Tool

Aggregates all market stock data to compute daily market overview (advance/decline counts, limit up/down, turnover, etc.).

Core Functions:

FunctionDescription
get_market_overview(trade_date=None)Get market overview as structured data
format_market_overview(trade_date=None)Generate formatted Markdown output

Output Metrics:

MetricDescription
Advance/DeclineUp/down/flat counts and percentages
Limit Up/DownMain board >=9.9%, ChiNext/STAR >=19.9%
Total TurnoverMarket-wide turnover (100M CNY)
Avg/Median ChangeOverall market change level
Market SentimentStrong rally/Bullish/Neutral/Bearish/Weak decline

Run:

python tools/market_overview.py
python tools/market_overview.py --trade_date 20260801

tools/abnormal_detector.py — Anomaly Detection Tool

Detects daily market anomalies: limit up/down stocks, volume breakouts, abnormal price movements, sector anomalies.

Core Functions:

FunctionDescription
detect_abnormal(trade_date=None)Detect anomalies, return structured data
format_abnormal(trade_date=None)Generate formatted Markdown output

Detection Types:

TypeCondition
Limit Up/DownMain board >=9.9%, ChiNext/STAR >=19.9%
Volume BreakoutVolume ratio >3 AND gain >3% (ratio = current vol / 20-day avg vol)
Price Surge
Sector Anomaly

Run:

python tools/abnormal_detector.py
python tools/abnormal_detector.py --trade_date 20260801

tools/market_trend.py — Trend Assessment Tool

Multi-dimensional market sentiment analysis based on recent N-day data.

Core Functions:

FunctionDescription
analyze_market_trend(days=5)Analyze market trend, return structured data
format_market_trend(days=5)Generate formatted Markdown output

Scoring Dimensions (20 pts each, 100 total):

DimensionSourceLogic
Advance/Decline Ratiostock_kline 5-dayAverage advancing stock ratio
Limit Up/Down Ratiostock_kline latestLimit up / (up + down + 1)
Turnover Trendstock_kline 5-dayRecent 5d vs prior 5d, volume expansion/contraction
Sector Rotationsector_industry_dailyAdvancing sector ratio
Consecutive Trendstock_kline 5-dayConsecutive up/down days

Sentiment Mapping: >=75 Optimistic / >=60 Mildly Bullish / >=40 Neutral / >=25 Mildly Bearish / <25 Pessimistic

Run:

python tools/market_trend.py
python tools/market_trend.py --days 10

tools/watchlist_report.py — Watchlist Report Tool

Personalized daily report for user-watched stocks: daily performance, 5-day change, related news.

Core Functions:

FunctionDescription
get_watchlist_report(ts_codes, trade_date=None)Get watchlist report as structured data
format_watchlist_report(ts_codes, trade_date=None)Generate formatted Markdown output

Report Content:

ModuleDescription
Daily PerformanceClose price, change %, turnover
5-Day ChangeCumulative change over 5 trading days
Related NewsSearch news by stock name (max 3 per stock)

Watchlist Config: Edit tools/watchlist_config.json to set default watchlist.

Run:

python tools/watchlist_report.py --ts_codes 600519.SH,300750.SZ
python tools/watchlist_report.py # Use default from watchlist_config.json

tools/daily_digest.py — Daily Report Generator (Enhanced)

Generates complete daily market briefing by integrating all 6 modules.

Core Functions:

FunctionDescription
generate_daily_digest(trade_date=None, watchlist=None)Generate complete daily report (Markdown)

Report Structure:

SectionModuleSource
1Market Overviewmarket_overview.py
2Trend Assessmentmarket_trend.py
3Sector Rotationsector_ranking.py + sector_rotation.py
4Market Anomaliesabnormal_detector.py
5Important Newsnews_stock_linker.py
6Watchlist Report (optional)watchlist_report.py

Run:

python tools/daily_digest.py
python tools/daily_digest.py --trade_date 20260801
python tools/daily_digest.py --watchlist 600519.SH,300750.SZ

5.12 Tool Function Mapping

Existing langgraph_getdata/New tools/Description
query_market_data_day_k.pystock_query.pyStock K-line query
query_industry_index_market.pysector_query.pySector quote query
query_industry_component_list.pysector_query.pySector constituents
query_concept_dc_day.pysector_query.pyConcept sector quotes
query_concept_dc_stock.pysector_query.pyConcept sector constituents
query_fin_account.pyfinancial_query.pyFinancial statement query (Done)
(None)news_query.pyNews query (New)
(None)stock_fundamental.pyFundamental indicators (Done)
(None)stock_valuation.pyValuation percentile (Done)
(None)stock_technical.pyTechnical indicators (Done)
(None)stock_sector_mapping.pyStock-sector mapping (Done)
(None)sector_financial_agg.pySector financial aggregation (Done)
(None)news_stock_linker.pyNews-stock correlation (Done)
(None)financial_score.pyFinancial health scoring (Done)
(None)sector_data.pySector data utilities (Done)
(None)market_overview.pyMarket overview tool (Done)
(None)abnormal_detector.pyAnomaly detection tool (Done)
(None)market_trend.pyTrend assessment tool (Done)
(None)watchlist_report.pyWatchlist report tool (Done)
(None)daily_digest.pyDaily report generator (Done)

5.13 Dependencies

pip install agentscope>=2.0.3 fastapi uvicorn

About

Built on professional finance knowledge, it provides stock diagnostics, sector index analysis, investment Q&A and news insights to help investors capture market opportunities efficiently.

Resources

Stars

5 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

FinAssistant Logo

FinAssistant — AI-Powered Financial Analysis

RAG Retrieval & Agent System for China A-Share Market

BackgroundFeaturesData AssetsImplementationTools

中文 | English


1. Background

The China A-share market has diverse data dimensions and massive information volumes. Retail investors and small-to-medium institutions struggle to efficiently integrate stock quotes, sector rotation, financial statements, and market news for comprehensive analysis. This project aims to build a financial RAG retrieval and agent system based on collected A-share data assets, enabling users to perform professional financial analysis through natural language conversations.

Core Objectives

  • Lower Analysis Barriers: Replace manual data queries, indicator calculations, and report writing with natural language
  • Multi-dimensional Data Correlation: Connect stocks, sectors, financials, and news for a panoramic view
  • Agent Collaboration: Multiple specialized agents working together, covering the full workflow from data queries to research reports

Tech Stack

LayerTechnology
Agent FrameworkAgentScope 2.0 (Multi-Agent Orchestration)
Data StorageMySQL (Structured Query) + Milvus (Vector Retrieval)
Data CollectionPython + akshare + DrissionPage
LLMQwen / GPT / Claude
Embeddingtext-embedding-v3 / BGE
FrontendStreamlit / Gradio

2. Feature Modules

Six intelligent agent modules planned based on existing data assets:


2.1 Stock Analysis Agent

Data Support: Daily stock quotes + Company info + Financial statements

Core Features:

FeatureDescriptionImplementation
Fundamental ScoreAuto-score (0-100) based on ROE, gross margin, debt ratio, cash flowExtract key fields from 3 statements, weighted calculation
Valuation PercentilePE/PB/PCF percentile in 1-year history, determine over/undervaluedCalculate percentile on daily PE/PB series
Technical IndicatorsMA(5/10/20/60), MACD, RSI, Bollinger Bands, KDJReal-time calculation based on OHLCV data
Trading SignalsGolden/Dead cross, MA breakout, RSI overbought/oversoldTechnical indicator crossover detection
Stock Profile ReportComprehensive fundamental + technical + valuation + sector reportLLM aggregates analysis results into text

Example Queries:

"How is Pudong Bank's cash flow situation this quarter?"
"What is Ping An Bank's current valuation percentile?"
"Analyze Kweichow Moutai's technical trend and give trading advice"
"Generate a stock profile report for CATL"

To-Do:

  • tools/stock_fundamental.py — Fundamental indicator calculator (Done)
  • tools/stock_valuation.py — Valuation percentile analyzer (Done)
  • tools/stock_technical.py — Technical indicator calculator (Done)
  • tools/stock_analysis.py — Comprehensive stock analysis report (Done)
  • agents/stock_agent.py — Stock analysis agent (Done)

Agent Demo:

$ python agents/stock_agent.py
============================================================
FinAssistant — 金融智能体
============================================================
输入股票代码或问题开始分析,输入 'quit' 退出
============================================================
你: 帮我分析贵州茅台的技术面走势,给出操作建议
FinAssistant:
[调用工具: reset_tools]
[完成] 结果: The currently activated tool group(s): stock-technical.
[调用工具: calc_technical_summary]
[完成] 结果: === 600519.SH 技术指标分析 (2026-07-17) ===
收盘价: 1253.0
【移动平均线 MA】
MA5: 1237.78
MA10: 1217.11
MA20: 1204.07
MA60: 1263.65
均线趋势: 多头排列
【MACD】
DIF: -0.2443
DEA: -11.3353
MACD柱: 22.182
信号: 金叉
【RSI】
RSI(6): 92.76
RSI(12): 68.8
RSI(24): 48.73
RSI(6)信号: 超买
【布林带 BOLL】
上轨: 1252.21
中轨: 1204.07
下轨: 1155.92
【KDJ】
K: 84.3
D: 79.2
J: 94.49
信号: 金叉
【综合研判】
当前信号: MA多头排列, MACD金叉, RSI超买, KDJ金叉
### 贵州茅台(600519.SH)技术面分析与操作建议
#### 一、核心技术指标摘要(近120天)
| 指标类型 | 关键数据 | 信号解读 |
|---------|---------|---------|
| **均线系统** | MA5:1237.78, MA10:1217.11, MA20:1204.07, MA60:1263.65 | 短期均线多头排列,股价略低于MA60(1263.65),中期趋势依然向上 |
| **MACD** | DIF:-0.24, DEA:-11.34, MACD柱:22.18 | 低位金叉形成,空头趋势减弱,短期反弹信号明确 |
| **RSI** | RSI(6):92.76, RSI(12):68.80, RSI(24):48.73 | 短期RSI严重超买(>90),警惕回调风险 |
| **布林带** | 上轨:1252.21, 中轨:1204.07, 下轨:1155.92 | 股价突破上轨,处于强势区间,但短期乖离率偏大 |
| **KDJ** | K:84.30, D:79.20, J:94.49 | 高位金叉,短期上涨动能充足,但J线接近超买区 |
#### 二、综合研判
技术面呈现**强趋势与短期超买并存**的格局:
1. **多头趋势明确**:均线多头排列、MACD低位金叉、KDJ金叉共同构成中期上涨信号
2. **短期回调风险**:RSI超买、股价突破布林上轨提示短期涨幅过大,存在技术性回调需求
#### 三、操作建议
1. **持仓投资者**:
- 继续持有为主,可将MA20(1204.07)作为止损线
- 若股价回落至MA5-MA10区间(1217-1238)可适当加仓
- 短期若冲高至MA60(1263.65)遇阻,可考虑部分止盈
2. **观望投资者**:
- 等待回调至关键支撑位(MA20:1204或布林中轨:1204)再考虑进场
- 若股价直接突破MA60并站稳,可小仓位追涨
⚠️ **风险提示**:技术分析仅供参考,不构成投资建议。市场存在不确定性,需结合自身风险承受能力决策。

2.2 Sector Rotation Analysis Agent

Data Support: Industry/Concept sector daily quotes (90 industry + 374 concept) + Constituent stocks

Core Features:

FeatureDescriptionImplementation
Sector RankingRank by pct_chg, volume change, capital flowAggregate sector daily_index
Rotation TrendSectors with consecutive top N-day gains marked as "hot"Sliding window rank change analysis
Sector ComparisonMulti-sector price curves overlayExtract multiple sector close series
Constituent DistributionAdvance/decline count, limit up/down, median changeLink constituent daily data
Capital FlowVolume change trend, determine inflow/outflowVolume QoQ change analysis
Sector CorrelationConstituent stock overlap between two sectorsSet intersection/union ratio

Example Queries:

"Which industry sectors had the highest gains this week?"
"How has the semiconductor sector performed this month? Is capital flowing in or out?"
"How high is the overlap between AI and robotics concept constituents?"
"Which sectors had limit-down waves today?"

To-Do:

  • tools/sector_ranking.py — Sector ranking tool (Done)
  • tools/sector_rotation.py — Rotation trend identifier (Done)
  • tools/sector_compare.py — Sector comparison tool (Done)
  • tools/sector_detail.py — Sector deep analysis tool (Done)
  • agents/sector_agent.py — Sector analysis agent (Done)

Agent Demo:

$ python agents/sector_agent.py
============================================================
FinAssistant — 板块轮动分析智能体
============================================================
输入板块相关问题开始分析,输入 'quit' 退出
示例:
- 最近一周涨幅最大的行业板块有哪些?
- 半导体板块最近一个月资金是在流入还是流出?
- AI概念和机器人概念的成分股重叠度有多高?
- 今天哪些板块出现了跌停潮?
============================================================
你: 最近一周涨幅最大的行业板块有哪些?
FinAssistant:
[调用工具: get_sector_ranking]
[完成] 结果: === 行业板块涨跌幅排名 (2026-07-17) ===
Top 10:
排名 板块名称 涨跌幅(%) 成交额(亿)
1 通信设备 +5.23 312.45
2 半导体 +4.87 528.91
3 消费电子 +3.65 287.33
...
[调用工具: get_sector_top_gainers]
[完成] 结果: === 连续3天上涨的行业板块 ===
板块名称 连涨天数 累计涨幅(%)
半导体 3 +8.92
通信设备 3 +7.56
...
综合来看,最近一周涨幅最大的行业板块主要集中在科技领域:
1. **通信设备** (+5.23%) — 5G建设持续推进,板块领涨
2. **半导体** (+4.87%) — 国产替代逻辑强化,资金持续流入
3. **消费电子** (+3.65%) — 新品发布预期带动板块走强
其中半导体和通信设备已连续3天上涨,短期动能较强。
⚠️ 风险提示:板块轮动较快,追高需谨慎。以上分析仅供参考,不构成投资建议。

2.3 Cross-Data Correlation Analysis Agent

Data Support: Quotes + Constituents + Financial statements + News (Full data cross-correlation)

Core Features:

FeatureDescriptionImplementation
Stock→Sector MappingQuery which sectors a stock belongs to, recent performanceReverse lookup in constituent data
Sector→Financial AggregationAverage ROE, median PE, total revenue for sector constituentsLink constituent codes to financial statements
News→Quote CorrelationCompanies/sectors mentioned in news, link to recent price trendsNER entity recognition + code matching
Industry ChainInfer upstream/downstream relationships via concept overlapConstituent set similarity clustering
Leader EffectTop N stocks by market cap vs sector overall performanceMarket-cap weighted vs equal-weight index

Example Queries:

"Which concept sectors does BYD belong to? How are they performing?"
"What's the average PE and ROE for the semiconductor sector?"
"Any recent news about solar power? How are related sectors trending?"
"Find the top 5 stocks most correlated with CATL"

To-Do:

  • tools/stock_sector_mapping.py — Stock-sector mapping tool (Done)
  • tools/sector_financial_agg.py — Sector financial aggregation (Done)
  • tools/news_stock_linker.py — News-quote correlation tool (Done)
  • agents/correlation_agent.py — Correlation analysis agent (Done)

2.4 Financial Q&A Agent (RAG)

Data Support: Financial statements (4,593 stocks × multi-period) + Vector database (Milvus)

Core Features:

FeatureDescriptionImplementation
NL Financial Query"Which companies have gross margin > 50%" → SQL/Vector searchVectorize financial fields + structured query
Cross-stock ComparisonHorizontal comparison of financial indicators for same-industry companiesGroup by industry + indicator comparison
Multi-period TrendVertical comparison of same company across periodsTime series analysis + trend detection
Anomaly AlertCash flow plunge, receivables surge, goodwill impairmentThreshold/QoQ change detection
Financial Health ScoreComprehensive solvency, profitability, growth, operational abilityDuPont analysis system + weighted scoring

Example Queries:

"Which banks have positive operating cash flow for the past year?"
"Compare CATL and BYD's debt ratio trends"
"Which companies had gross margin drop > 10% last quarter?"
"Give me a DuPont analysis for Kweichow Moutai"
"Find companies with ROE > 20% for 3 consecutive years"

To-Do:

  • tools/financial_query.py — Financial data query tool (Done)
  • tools/financial_compare.py — Financial comparison tool (Done)
  • tools/financial_anomaly.py — Anomaly detection tool (Done)
  • tools/financial_score.py — Financial health scoring tool (Done)
  • agents/financial_agent.py — Financial Q&A agent (Done)
  • rag/financial_embedding.py — Financial statement vectorization

2.5 Daily Market Report Agent

Data Support: Full data (Quotes + Sectors + News + Financials)

Core Features:

FeatureDescriptionImplementation
Market OverviewMajor index changes, volume, advance/decline statsAggregate all market stock data
Sector Rotation SummaryTop gainers/losers, capital inflow/outflow Top5Sector ranking tool output
Anomaly DetectionLimit up/down, volume breakout, abnormal volatilityFilter conditions
News SummaryMarket-related important news, linked sectorsNews filtering + LLM summary
Watchlist ReportUser's watched stocks daily performance, announcementsPersonalized filtering
Trend AssessmentBased on recent N-day data, market sentiment judgmentMulti-indicator synthesis

Example Queries:

"Generate today's market morning briefing"
"Which stocks hit limit up today? Which sectors do they belong to?"
"How has market sentiment been this week?"
"How are my watchlist stocks performing today?"

To-Do:

  • tools/market_overview.py — Market overview tool (Done)
  • tools/abnormal_detector.py — Anomaly detection tool (Done)
  • tools/market_trend.py — Trend assessment tool (Done)
  • tools/watchlist_report.py — Watchlist report tool (Done)
  • tools/daily_digest.py — Daily report generator (Done, integrates all 6 modules)
  • agents/daily_report_agent.py — Daily report agent (Done)

2.6 Research Report Generation Agent

Data Support: Full data + LLM generation capabilities

Core Features:

FeatureDescriptionImplementation
Stock Deep ReportComprehensive fundamental + technical + valuation + industry positionCall previous tools + LLM long-text generation
Industry ResearchSector trends, constituent financials, industry chain analysisSector tools + Financial tools + LLM
Comparative Report2-3 same-industry companies multi-dimensional comparisonComparison tools + LLM
Event Impact AnalysisNews/policy impact on related sectors and stocksNews correlation + Historical analogy + LLM
Portfolio SuggestionRecommend sector/stock allocation based on risk preferenceOptimization algorithm + LLM

Example Queries:

"Write a deep research report on the semiconductor industry"
"Compare BYD, CATL, and LONGi Green Energy with a comparative analysis"
"Which A-share sectors are most affected by Fed rate hikes?"
"I prefer conservative investing, recommend some sector allocation plans"

To-Do:

  • tools/report_generator.py — Report generation tool (LLM + templates)
  • templates/ — Report templates (stock/industry/comparison/event)
  • agents/report_agent.py — Report generation agent
  • agents/portfolio_agent.py — Portfolio optimization agent

3. Data Assets

3.1 Data Overview

Data TypeVolumeSourceTime Range
SH Stock Daily Quotes2,308 stocksSina Finance (akshare)2026-01-01 ~ Present
SZ Stock Daily Quotes2,895 stocksSina Finance (akshare)2026-01-01 ~ Present
SH Company Info2,308 (Main 1,699 + STAR 609)SSE (akshare)-
SZ Company Info2,895SZSE (akshare)-
SH Financial Statements2,308 stocksSina Finance (akshare)Recent 3 years
SZ Financial Statements2,895 stocksSina Finance (akshare)Recent 3 years
Industry Sector Quotes90 sectorsTonghuashun (akshare)2026-01-01 ~ Present
Concept Sector Quotes374 sectorsTonghuashun (akshare)2026-01-01 ~ Present
Industry Constituents90 sectorsTonghuashun (DrissionPage)-
Concept Constituents374 sectorsTonghuashun (DrissionPage)-
Financial News-Tonghuashun 7x242026-01-01 ~ Present

3.2 MySQL Table Schema

Data is stored in Alibaba Cloud RDS MySQL with two databases: market_data (quotes/financials) and stock_news (news).

market_data.company_info — Company Basic Info

CREATETABLEcompany_info (
id INT AUTO_INCREMENT PRIMARY KEY COMMENT 'Auto-increment ID',
ts_code VARCHAR(20) NOT NULL COMMENT 'Stock code with suffix, e.g., 600000.SH',
symbol VARCHAR(10) NOT NULL COMMENT 'Stock code (numeric only)',
stock_name VARCHAR(50) COMMENT 'Stock short name',
full_name VARCHAR(100) COMMENT 'Company full name',
industry VARCHAR(50) COMMENT 'Industry, e.g., J Finance',
list_date VARCHAR(20) COMMENT 'Listing date, format YYYY-MM-DD',
market VARCHAR(5) COMMENT 'Market, SH=Shanghai SZ=Shenzhen',
updated_at VARCHAR(30) COMMENT 'Data update time',
UNIQUE KEY uk_ts_code (ts_code)
)

market_data.stock_kline — Stock Daily K-line

CREATETABLEstock_kline (
id BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT 'Auto-increment ID',
ts_code VARCHAR(20) NOT NULL COMMENT 'Stock code with suffix',
symbol VARCHAR(10) NOT NULL COMMENT 'Stock code (numeric only)',
trade_date VARCHAR(20) NOT NULL COMMENT 'Trade date, format YYYY-MM-DD',
open DOUBLE COMMENT 'Open price (CNY)',
close DOUBLE COMMENT 'Close price (CNY)',
high DOUBLE COMMENT 'High price (CNY)',
low DOUBLE COMMENT 'Low price (CNY)',
pre_close DOUBLE COMMENT 'Previous close (CNY)',
change_data DOUBLE COMMENT 'Price change (CNY)',
pct_chg DOUBLE COMMENT 'Change percentage (%)',
volume DOUBLE COMMENT 'Volume (shares)',
amount DOUBLE COMMENT 'Turnover (CNY)',
pe DOUBLE COMMENT 'P/E ratio',
pb DOUBLE COMMENT 'P/B ratio',
total_mv DOUBLE COMMENT 'Total market cap (100M CNY)',
total_share DOUBLE COMMENT 'Total shares',
float_share DOUBLE COMMENT 'Float shares',
circ_mv DOUBLE COMMENT 'Circulating market cap (100M CNY)',
ln_pctchg DOUBLE COMMENT 'Log return',
pe_ttm DOUBLE COMMENT 'P/E ratio (TTM)',
pe_static DOUBLE COMMENT 'Static P/E ratio',
pcf DOUBLE COMMENT 'Price-to-Cash-Flow ratio',
UNIQUE KEY uk_code_date (ts_code, trade_date),
KEY idx_trade_date (trade_date),
KEY idx_symbol (symbol)
)

market_data.stock_financial — Financial Statements

CREATETABLEstock_financial (
id BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT 'Auto-increment ID',
ts_code VARCHAR(20) NOT NULL COMMENT 'Stock code with suffix',
symbol VARCHAR(10) NOT NULL COMMENT 'Stock code (numeric only)',
statement_type VARCHAR(20) NOT NULL COMMENT 'Statement type: income/balance/cashflow',
report_date VARCHAR(20) NOT NULL COMMENT 'Report date, e.g., 20260331',
report_data JSON COMMENT 'Complete statement data (JSON)',
UNIQUE KEY uk_code_type_date (ts_code, statement_type, report_date),
KEY idx_symbol (symbol),
KEY idx_report_date (report_date),
KEY idx_statement_type (statement_type)
)

Financial fields vary significantly across industries (banking vs manufacturing), hence JSON storage for complete statement data.

market_data.sector_industry_daily / sector_concept_daily — Sector Daily K-line

CREATETABLEsector_industry_daily (
id BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT 'Auto-increment ID',
sector_name VARCHAR(50) NOT NULL COMMENT 'Sector name',
sector_code VARCHAR(20) NOT NULL COMMENT 'Sector code',
trade_date VARCHAR(20) NOT NULL COMMENT 'Trade date',
open DOUBLE COMMENT 'Open',
high DOUBLE COMMENT 'High',
low DOUBLE COMMENT 'Low',
close DOUBLE COMMENT 'Close',
vol DOUBLE COMMENT 'Volume',
amount DOUBLE COMMENT 'Turnover',
pct_chg DOUBLE COMMENT 'Change (%)',
change_data DOUBLE COMMENT 'Point change',
pct_change DOUBLE COMMENT 'Change (backup)',
turnover_rate DOUBLE COMMENT 'Turnover rate',
UNIQUE KEY uk_code_date (sector_code, trade_date),
KEY idx_trade_date (trade_date),
KEY idx_sector_name (sector_name)
)

market_data.sector_industry_cons / sector_concept_cons — Sector Constituents

CREATETABLEsector_industry_cons (
id BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT 'Auto-increment ID',
sector_name VARCHAR(50) NOT NULL COMMENT 'Sector name',
sector_code VARCHAR(20) NOT NULL COMMENT 'Sector code',
stock_code VARCHAR(10) NOT NULL COMMENT 'Stock code',
stock_name VARCHAR(50) COMMENT 'Stock name',
UNIQUE KEY uk_sector_stock (sector_code, stock_code),
KEY idx_sector_name (sector_name),
KEY idx_stock_code (stock_code)
)

stock_news.news_em — Eastmoney 7x24 News

CREATETABLEnews_em (
id INT AUTO_INCREMENT PRIMARY KEY COMMENT 'Auto-increment ID',
title VARCHAR(500) NOT NULL COMMENT 'News title',
digest TEXT COMMENT 'News digest',
publish_time VARCHAR(30) COMMENT 'Publish time',
url VARCHAR(500) COMMENT 'News URL',
crawl_time VARCHAR(30) COMMENT 'Crawl time',
UNIQUE KEY uk_title_time (title, publish_time)
)

stock_news.news_ths — Tonghuashun Financial News

CREATETABLEnews_ths (
id INT AUTO_INCREMENT PRIMARY KEY COMMENT 'Auto-increment ID',
news_id VARCHAR(20) NOT NULL COMMENT 'News ID',
title VARCHAR(500) NOT NULL COMMENT 'News title',
digest TEXT COMMENT 'News digest',
url VARCHAR(500) COMMENT 'News URL',
tags VARCHAR(500) COMMENT 'Tags (comma separated)',
ctime_str VARCHAR(30) COMMENT 'Publish time',
source VARCHAR(100) COMMENT 'Source',
crawl_time VARCHAR(30) COMMENT 'Crawl time',
UNIQUE KEY uk_news_id (news_id),
KEY idx_ctime (ctime_str)
)

3.3 Data Import Scripts

ScriptTarget TableDescription
import_company_info_to_mysql.pymarket_data.company_infoSH/SZ company info
import_kline_to_mysql.pymarket_data.stock_klineStock daily K-line (560K+ rows)
import_financial_to_mysql.pymarket_data.stock_financialFinancial statements (170K+ rows)
import_sector_to_mysql.pymarket_data.sector_*_dailySector daily K-line
import_sector_cons_to_mysql.pymarket_data.sector_*_consSector constituents
import_news_em_to_mysql.pystock_news.news_emEastmoney news
import_news_ths_to_mysql.pystock_news.news_thsTonghuashun news

3.4 Data Collection Scripts

ScriptPurposeSource
crawl_sh_stock_data.pySH stock quotes + company infoSina Finance / SSE
crawl_sz_stock_data.pySZ stock quotes + company infoSina Finance / SZSE
crawl_financial_reports.pyFinancial statementsSina Finance
crawl_sector_data.pySector daily quotes (Industry + Concept)Tonghuashun (akshare)
crawl_sector_cons.pySector constituentsSina Finance (akshare)
crawl_sector_cons_ths.pySector constituents (backup)Tonghuashun (DrissionPage)
crawl_news_ths.pyFinancial newsTonghuashun 7x24 API
crawl_news_em.pyEastmoney 7x24 news (scheduled)Eastmoney (akshare)

3.5 Known Issues

IssueDescription
Eastmoney API Blockedpush2his.eastmoney.com completely unavailable
Tonghuashun IP BlockedFrequent crawling triggers Nginx 403 block
Inconsistent Sector SourcesQuotes from THS, constituents partially from Sina, names may not match
SH Company Missing IndustrySSE API doesn't provide industry field

4. AgentScope 2.0 Implementation

4.1 Architecture

User Query → FastAPI → Agent (system_prompt + model + toolkit + middlewares)
↓
Toolkit
├── ToolGroup("Stock Analysis") → tools/stock_query.py + skills/stock-analysis/
├── ToolGroup("Sector Analysis") → tools/sector_query.py + skills/sector-rotation/
├── ToolGroup("Financial Q&A") → tools/financial_query.py + skills/financial-qa/
├── ToolGroup("Daily Report") → tools/news_query.py + skills/daily-report/
└── ToolGroup("Research Report") → tools/indicators.py + skills/research-report/

4.2 Directory Structure

FinAssistant/
├── config.py # Global config (paths, model, API Key)
├── main.py # FastAPI service entry
├── main_agent.py # Single agent script (no server, direct chat)
├── core/
│ ├── agent_setup.py # Agent + Toolkit initialization
│ └── middleware.py # Financial scenario middleware
├── tools/ # Tool functions
│ ├── __init__.py
│ ├── stock_query.py # Stock quote/company info query
│ ├── sector_query.py # Sector quote/constituent query
│ ├── financial_query.py # Financial statement query & analysis
│ ├── news_query.py # News query
│ └── indicators.py # Technical/fundamental indicator calculation
├── skills/ # Skill documents (SKILL.md)
│ ├── stock-analysis/SKILL.md
│ ├── sector-rotation/SKILL.md
│ ├── financial-qa/SKILL.md
│ ├── daily-report/SKILL.md
│ └── research-report/SKILL.md
├── data/ # Existing data (don't modify)
└── data_to_mysql_and_milvus/ # Existing crawler scripts (don't modify)

4.3 Implementation Steps

Step 1: config.py

Global configuration for data paths, model config, API keys.

Step 2: tools/ Tool Functions

Each function is async def, returns ToolChunk. Docstring is the tool description — LLM decides when to call based on docstring.

Step 3: skills/SKILL.md Skill Documents

Each skill directory has a SKILL.md with trigger conditions, dependent tools, and execution flow.

Step 4: core/middleware.py Middleware

MiddlewarePurpose
InputValidationMiddlewareFilter non-financial queries
ToolCallAuditMiddlewareLog tool calls to traces/
PerformanceMonitorMiddlewareMonitor inference rounds, latency, tokens
ContextEnrichmentMiddlewareInject current date, trading day context

Step 5: core/agent_setup.py Agent Initialization

Assemble model, tools, toolkit, and agent with middleware.

Step 6: main.py Service Entry

FastAPI service with OpenAI-compatible /v1/chat/completions endpoint.


5. Implemented Tools

tools/stock_fundamental.py — Fundamental Indicator Calculator

Calculates fundamental indicators from MySQL market_data.stock_financial table.

Core Functions:

FunctionDescription
calc_fundamental_indicators(ts_code, report_date=None)Calculate single-period indicators
calc_fundamental_trend(ts_code, periods=4)Calculate recent N-period trend
get_financial_data(ts_code, report_date=None)Get raw statement data
get_report_dates(ts_code, limit=8)Get report date list

Calculated Indicators:

IndicatorFormulaData Source
ROENet Profit / Equity × 100%Income + Balance Sheet
Gross Margin(Revenue - COGS) / Revenue × 100%Income Statement
Net MarginNet Profit / Revenue × 100%Income Statement
Debt RatioTotal Liabilities / Total Assets × 100%Balance Sheet
Cash Flow / Net ProfitOperating Cash Flow / Net ProfitCash Flow + Income
Revenue YoY Growth(Current - Prior Year) /Prior Year
Net Profit YoY Growth(Current - Prior Year) /Prior Year
Revenue QoQ Growth(Current Q - Prior Q) /Prior Q
Net Profit QoQ Growth(Current Q - Prior Q) /Prior Q

Special Handling:

  • Auto bank detection: Via balance sheet fields (loans, deposits)
  • Bank field mapping: Revenue = Net Interest Income + Fee Income; COGS = Interest Expense + Fee Expense
  • YoY calculation: Cumulative values vs same quarter last year (2026Q1 vs 2025Q1)
  • QoQ calculation: Single-quarter values (Q4 = Annual - 9-month cumulative)

Usage:

fromtools.stock_fundamentalimportcalc_fundamental_indicators, calc_fundamental_trend# Single periodresult=calc_fundamental_indicators('600519.SH')
print(result['ROE'], result['毛利率'], result['营收同比增长率'])
# Trend (recent 4 periods)trend=calc_fundamental_trend('600519.SH', periods=4)
fortintrend['trend']:
print(t['report_date'], t['ROE'], t['营收同比增长率'])

tools/stock_valuation.py — Valuation Percentile Analyzer

Calculates PE/PB/PCF percentile in 1-year history from market_data.stock_kline table.

Core Functions:

FunctionDescription
calc_valuation_percentile(ts_code, days=365)Calculate valuation percentile, return structured data
calc_valuation_summary(ts_code, days=365)Generate formatted valuation summary
get_valuation_history(ts_code, days=365)Get N-day valuation history
get_latest_valuation(ts_code)Get latest day valuation data

Valuation Indicators:

IndicatorDescriptionSource
PE_TTMPrice-to-Earnings (Trailing Twelve Months)stock_kline.pe_ttm
PBPrice-to-Bookstock_kline.pb
PCFPrice-to-Cash-Flowstock_kline.pcf

Percentile Rules:

PercentileLevelMeaning
< 20%UndervaluedAt historical low, potentially undervalued
20% - 40%Below AverageBelow historical median
40% - 60%FairAt historical median range
60% - 80%Above AverageAbove historical median
> 80%OvervaluedAt historical high, potentially overvalued

Usage:

fromtools.stock_valuationimportcalc_valuation_percentile, calc_valuation_summary# Get structured dataresult=calc_valuation_percentile('600519.SH')
print(f"PE_TTM: {result['pe_ttm']}, Percentile: {result['pe_ttm_percentile']}%, {result['pe_ttm_level']}")
# Get formatted summaryprint(calc_valuation_summary('600519.SH'))

tools/stock_technical.py — Technical Indicator Calculator

Calculates MA/MACD/RSI/BOLL/KDJ indicators from MySQL market_data.stock_kline table.

Core Functions:

FunctionDescription
calc_technical_indicators(ts_code, days=120)Calculate all technical indicators
calc_technical_summary(ts_code, days=120)Generate formatted summary
get_kline_data(ts_code, days=120)Get K-line data from MySQL

Technical Indicators:

IndicatorFormulaUsage
MA(5/10/20/60)Average of last N closing pricesTrend: Price above MA = bullish; MA crossover = buy/sell signal
MACDDIF = EMA(12) - EMA(26); DEA = EMA(DIF,9); Histogram = (DIF-DEA)×2Golden cross (DIF>DEA) = buy; Dead cross = sell
RSI(6/12/24)RS = Avg Gain / Avg Loss; RSI = 100 - 100/(1+RS)>80 = overbought; <20 = oversold
BOLL(20,2)Upper = MA+2σ; Middle = MA; Lower = MA-2σTouch upper = overbought; Touch lower = oversold
KDJ(9,3,3)RSV, K = 2/3K+1/3RSV, D = 2/3D+1/3K, J = 3K-2DK>80 = overbought; K<20 = oversold; K/D crossover

Signal Interpretation:

SignalMAMACDRSIBOLLKDJ
BullishMA5>MA10>MA20 (Bull alignment)DIF>DEA, Histogram>0RSI<20 (Oversold)Price bounces off lower bandK/D golden cross in oversold zone
BearishMA5<MA10<MA20 (Bear alignment)DIF<DEA, Histogram<0RSI>80 (Overbought)Price falls from upper bandK/D dead cross in overbought zone

Multi-indicator Confirmation:

Buy signals (need 2-3):

  • Price above MA20, MA bullish alignment (MA5>MA10>MA20)
  • MACD golden cross (DIF crosses above DEA)
  • RSI rebounds from oversold (<20 → >20)
  • Price bounces off Bollinger lower band
  • KDJ golden cross in oversold zone

Sell signals (need 2-3):

  • Price below MA20, MA bearish alignment (MA5<MA10<MA20)
  • MACD dead cross (DIF crosses below DEA)
  • RSI enters overbought (>80) then falls
  • Price falls from Bollinger upper band
  • KDJ dead cross in overbought zone

Usage:

fromtools.stock_technicalimportcalc_technical_indicators, calc_technical_summary# Get structured dataresult=calc_technical_indicators('600519.SH')
print(f"Close: {result['close']}, MA5: {result['ma5']}, MACD: {result['macd_signal']}")
# Get formatted summaryprint(calc_technical_summary('600519.SH'))

5.5 Sector Analysis Tools

tools/sector_ranking.py — Sector Ranking Tool

Calculates sector rankings from MySQL sector_industry_daily / sector_concept_daily tables.

Core Functions:

FunctionDescription
get_sector_ranking(sector_type, trade_date, top_n, sort_by)Sector ranking by pct_chg/amount/volume
get_sector_top_gainers(sector_type, days, top_n)Sectors with consecutive N-day gains
get_sector_top_losers(sector_type, days, top_n)Sectors with consecutive N-day losses
get_sector_summary(sector_type, trade_date)Market overview (advance/decline, limit up/down)

Usage:

fromtools.sector_rankingimportget_sector_ranking, get_sector_top_gainers, get_sector_summary# Top 10 industry sectors by pct_chgprint(get_sector_ranking(sector_type='industry', top_n=10))
# Sectors rising for 3 consecutive daysprint(get_sector_top_gainers(sector_type='industry', days=3))
# Industry sector market overviewprint(get_sector_summary(sector_type='industry'))

tools/sector_rotation.py — Rotation Trend Identifier

Analyzes sector momentum and capital rotation direction through short-term vs medium-term performance comparison.

Core Functions:

FunctionDescription
get_sector_momentum(sector_type, short_days, long_days, top_n)Momentum analysis — short vs medium term, momentum score
get_sector_rotation(sector_type, short_days, long_days, top_n)Rotation identification — capital inflow/outflow sectors
get_sector_strength(sector_type, days, top_n)Strength ranking — composite score of gains, up-days, volume
get_hot_cold_sectors(sector_type, days)Hot/cold classification — hot/warm/flat/cold categories

Usage:

fromtools.sector_rotationimportget_sector_momentum, get_sector_rotation, get_hot_cold_sectors# Industry sector momentum (3-day short vs 10-day medium)print(get_sector_momentum(sector_type='industry', short_days=3, long_days=10))
# Sector rotation (capital inflow/outflow)print(get_sector_rotation(sector_type='industry'))
# Hot/cold sector classificationprint(get_hot_cold_sectors(sector_type='industry', days=5))

tools/sector_compare.py — Sector Comparison Tool

Multi-sector price curve overlay comparison with normalization and ASCII trend charts.

Core Functions:

FunctionDescription
compare_sectors(sector_names, sector_type, days)Multi-sector cumulative return comparison (table + ASCII chart)
compare_sector_trend(sector_names, sector_type, days)Trend strength comparison with conclusion

Usage:

fromtools.sector_compareimportcompare_sectors, compare_sector_trend# Compare Baijiu vs Power vs Banks over 20 daysprint(compare_sectors(['白酒', '电力', '银行'], sector_type='industry', days=20))
# Trend strength comparison with conclusionprint(compare_sector_trend(['白酒', '电力', '银行', '证券'], days=20))

tools/sector_detail.py — Sector Deep Analysis Tool

Links constituent stock data to provide internal sector structure analysis.

Core Functions:

FunctionDescription
get_constituent_distribution(sector_name, sector_type, trade_date)Constituent distribution — advance/decline, limit up/down, median change, top/bottom 5
get_sector_money_flow(sector_name, sector_type, days)Capital flow analysis — volume trend, price-volume coordination, inflow/outflow
get_sector_correlation(sector_name1, sector_name2, sector_type)Sector correlation — Jaccard coefficient, overlapping constituents

Usage:

fromtools.sector_detailimportget_constituent_distribution, get_sector_money_flow, get_sector_correlation# Baijiu sector constituent distributionprint(get_constituent_distribution('白酒', sector_type='industry'))
# Power sector capital flow analysisprint(get_sector_money_flow('电力', sector_type='industry', days=10))
# Baijiu vs Beer sector correlationprint(get_sector_correlation('白酒', '啤酒', sector_type='industry'))

tools/news_stock_linker.py — News-Stock Linker

Links news headlines to mentioned companies/sectors and correlates with their recent price trends.

Core Functions:

FunctionDescription
find_news_by_keyword(keyword, limit)Search news by keyword (title/digest fuzzy match)
search_news_with_market(keyword, limit, days_before, days_after)Search news and auto-correlate with matched stocks/sectors price trends

Usage Example:

fromtools.news_stock_linkerimportfind_news_by_keyword, search_news_with_market# Search news by keywordprint(find_news_by_keyword('半导体', limit=5))
# Search news and correlate with market dataprint(search_news_with_market('贵州茅台', limit=3, days_before=3, days_after=3))

5.6 Sector Analysis Agent

agents/sector_agent.py — Sector Analysis Agent

Integrates sector ranking, rotation, comparison, and deep analysis tool groups for sector rotation analysis.

Tool Group Structure:

Tool GroupToolsDescription
sector-rankingget_sector_ranking / get_sector_top_gainers / get_sector_top_losers / get_sector_summarySector ranking
sector-rotationget_sector_momentum / get_sector_rotation / get_sector_strength / get_hot_cold_sectorsRotation analysis
sector-comparecompare_sectors / compare_sector_trendSector comparison
sector-detailget_constituent_distribution / get_sector_money_flow / get_sector_correlationDeep analysis

Run:

python agents/sector_agent.py

5.7 Correlation Analysis Agent

agents/correlation_agent.py — Correlation Analysis Agent

Integrates stock-sector mapping, sector financial aggregation, and news-market correlation tool groups for cross-data analysis.

Tool Group Structure:

Tool GroupToolsDescription
stock-sectorfind_stock_sectorsStock-sector mapping
sector-financeget_sector_financial_agg / get_sector_valuation_statsSector financial aggregation, valuation distribution
news-marketfind_news_by_keyword / search_news_with_marketNews search, news-market correlation

Run:

python agents/correlation_agent.py

5.8 Financial Health Scoring Tool

tools/financial_score.py — Financial Health Scoring Tool

Computes a four-dimension composite financial health score (0-100) with rating (Excellent/Good/Fair/Poor).

Scoring Dimensions:

DimensionWeightIndicators
Profitability30%ROE(40%) + Gross Margin(30%) + Net Margin(30%)
Growth25%Revenue YoY Growth(50%) + Net Profit YoY Growth(50%)
Safety25%Debt Ratio(40%) + Cash Flow/NP(35%) + AR Ratio(25%)
Quality20%Deducted NP Ratio(50%) + Cash Flow Consistency(50%)

Anomaly Deduction: HIGH -5pts, MEDIUM -2pts, max -15pts.

Core Functions:

FunctionDescription
calc_financial_score(ts_code, report_date=None)Calculate single stock financial health score
format_financial_score(ts_code, report_date=None)Generate formatted Markdown output
score_sector(sector_name, sector_type, top_n)Batch score sector constituents

Run:

python tools/financial_score.py --ts_code 600519.SH
python tools/financial_score.py --sector 白酒 --top_n 10
python tools/financial_score.py --ts_codes 600519.SH,300750.SZ,601318.SH

5.9 Financial Q&A Agent

agents/financial_agent.py — Financial Q&A Agent

Integrates fundamental indicators, trend analysis, comparison, anomaly detection, financial scoring, and batch screening tool groups for complex financial Q&A.

Tool Group Structure:

Tool GroupToolsDescription
fundamentalcalc_fundamental_indicators / calc_fundamental_trend / get_financial_data / get_report_datesFinancial indicator calculation
comparecompare_companies / compare_periodsFinancial comparison and trends
score-anomalyformat_financial_score / calc_financial_score / detect_anomaliesScoring and anomaly detection
screeningscreen_cashflow_positive_stocks / screen_margin_decline_stocks / screen_roe_stocksBatch screening
queryquery_financial_dataFinancial data query

Example Queries:

"Which banks have positive operating cash flow for the past year?"
"Compare CATL and BYD's debt ratio trends"
"Which companies had gross margin drop > 10% last quarter?"
"Give me a DuPont analysis for Kweichow Moutai"
"Find companies with ROE > 20% for 3 consecutive years"

Run:

python agents/financial_agent.py

5.10 Daily Market Report Agent

agents/daily_report_agent.py — Daily Market Report Agent

Integrates market overview, trend assessment, sector rotation, anomaly detection, news correlation, and watchlist report tool groups for natural language Q&A on daily market briefings.

Tool Group Structure:

Tool GroupToolsDescription
market-overviewget_market_overview / format_market_overviewMarket overview
market-trendanalyze_market_trend / format_market_trendTrend assessment
sector-analysisget_sector_ranking / get_sector_rotation / get_hot_cold_sectors etc. (8 tools)Sector analysis
abnormal-detectiondetect_abnormal / format_abnormalAnomaly detection
newsfind_news_by_keyword / search_news_with_marketNews search
watchlistget_watchlist_report / format_watchlist_reportWatchlist report
daily-digestgenerate_daily_digestOne-click daily report

Example Queries:

"Generate today's market morning briefing"
"Which stocks hit limit up today? Which sectors do they belong to?"
"How has market sentiment been this week?"
"Which sectors are seeing capital inflow?"
"What important news is there today?"
"How are my watchlist stocks performing?"

Run:

python agents/daily_report_agent.py

5.11 Daily Market Report Tools

tools/market_overview.py — Market Overview Tool

Aggregates all market stock data to compute daily market overview (advance/decline counts, limit up/down, turnover, etc.).

Core Functions:

FunctionDescription
get_market_overview(trade_date=None)Get market overview as structured data
format_market_overview(trade_date=None)Generate formatted Markdown output

Output Metrics:

MetricDescription
Advance/DeclineUp/down/flat counts and percentages
Limit Up/DownMain board >=9.9%, ChiNext/STAR >=19.9%
Total TurnoverMarket-wide turnover (100M CNY)
Avg/Median ChangeOverall market change level
Market SentimentStrong rally/Bullish/Neutral/Bearish/Weak decline

Run:

python tools/market_overview.py
python tools/market_overview.py --trade_date 20260801

tools/abnormal_detector.py — Anomaly Detection Tool

Detects daily market anomalies: limit up/down stocks, volume breakouts, abnormal price movements, sector anomalies.

Core Functions:

FunctionDescription
detect_abnormal(trade_date=None)Detect anomalies, return structured data
format_abnormal(trade_date=None)Generate formatted Markdown output

Detection Types:

TypeCondition
Limit Up/DownMain board >=9.9%, ChiNext/STAR >=19.9%
Volume BreakoutVolume ratio >3 AND gain >3% (ratio = current vol / 20-day avg vol)
Price Surge
Sector Anomaly

Run:

python tools/abnormal_detector.py
python tools/abnormal_detector.py --trade_date 20260801

tools/market_trend.py — Trend Assessment Tool

Multi-dimensional market sentiment analysis based on recent N-day data.

Core Functions:

FunctionDescription
analyze_market_trend(days=5)Analyze market trend, return structured data
format_market_trend(days=5)Generate formatted Markdown output

Scoring Dimensions (20 pts each, 100 total):

DimensionSourceLogic
Advance/Decline Ratiostock_kline 5-dayAverage advancing stock ratio
Limit Up/Down Ratiostock_kline latestLimit up / (up + down + 1)
Turnover Trendstock_kline 5-dayRecent 5d vs prior 5d, volume expansion/contraction
Sector Rotationsector_industry_dailyAdvancing sector ratio
Consecutive Trendstock_kline 5-dayConsecutive up/down days

Sentiment Mapping: >=75 Optimistic / >=60 Mildly Bullish / >=40 Neutral / >=25 Mildly Bearish / <25 Pessimistic

Run:

python tools/market_trend.py
python tools/market_trend.py --days 10

tools/watchlist_report.py — Watchlist Report Tool

Personalized daily report for user-watched stocks: daily performance, 5-day change, related news.

Core Functions:

FunctionDescription
get_watchlist_report(ts_codes, trade_date=None)Get watchlist report as structured data
format_watchlist_report(ts_codes, trade_date=None)Generate formatted Markdown output

Report Content:

ModuleDescription
Daily PerformanceClose price, change %, turnover
5-Day ChangeCumulative change over 5 trading days
Related NewsSearch news by stock name (max 3 per stock)

Watchlist Config: Edit tools/watchlist_config.json to set default watchlist.

Run:

python tools/watchlist_report.py --ts_codes 600519.SH,300750.SZ
python tools/watchlist_report.py # Use default from watchlist_config.json

tools/daily_digest.py — Daily Report Generator (Enhanced)

Generates complete daily market briefing by integrating all 6 modules.

Core Functions:

FunctionDescription
generate_daily_digest(trade_date=None, watchlist=None)Generate complete daily report (Markdown)

Report Structure:

SectionModuleSource
1Market Overviewmarket_overview.py
2Trend Assessmentmarket_trend.py
3Sector Rotationsector_ranking.py + sector_rotation.py
4Market Anomaliesabnormal_detector.py
5Important Newsnews_stock_linker.py
6Watchlist Report (optional)watchlist_report.py

Run:

python tools/daily_digest.py
python tools/daily_digest.py --trade_date 20260801
python tools/daily_digest.py --watchlist 600519.SH,300750.SZ

5.12 Tool Function Mapping

Existing langgraph_getdata/New tools/Description
query_market_data_day_k.pystock_query.pyStock K-line query
query_industry_index_market.pysector_query.pySector quote query
query_industry_component_list.pysector_query.pySector constituents
query_concept_dc_day.pysector_query.pyConcept sector quotes
query_concept_dc_stock.pysector_query.pyConcept sector constituents
query_fin_account.pyfinancial_query.pyFinancial statement query (Done)
(None)news_query.pyNews query (New)
(None)stock_fundamental.pyFundamental indicators (Done)
(None)stock_valuation.pyValuation percentile (Done)
(None)stock_technical.pyTechnical indicators (Done)
(None)stock_sector_mapping.pyStock-sector mapping (Done)
(None)sector_financial_agg.pySector financial aggregation (Done)
(None)news_stock_linker.pyNews-stock correlation (Done)
(None)financial_score.pyFinancial health scoring (Done)
(None)sector_data.pySector data utilities (Done)
(None)market_overview.pyMarket overview tool (Done)
(None)abnormal_detector.pyAnomaly detection tool (Done)
(None)market_trend.pyTrend assessment tool (Done)
(None)watchlist_report.pyWatchlist report tool (Done)
(None)daily_digest.pyDaily report generator (Done)

5.13 Dependencies

pip install agentscope>=2.0.3 fastapi uvicorn

About

Built on professional finance knowledge, it provides stock diagnostics, sector index analysis, investment Q&A and news insights to help investors capture market opportunities efficiently.

Resources

Stars

5 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

FinAssistant Logo

FinAssistant — AI-Powered Financial Analysis

RAG Retrieval & Agent System for China A-Share Market

BackgroundFeaturesData AssetsImplementationTools

中文 | English


1. Background

The China A-share market has diverse data dimensions and massive information volumes. Retail investors and small-to-medium institutions struggle to efficiently integrate stock quotes, sector rotation, financial statements, and market news for comprehensive analysis. This project aims to build a financial RAG retrieval and agent system based on collected A-share data assets, enabling users to perform professional financial analysis through natural language conversations.

Core Objectives

  • Lower Analysis Barriers: Replace manual data queries, indicator calculations, and report writing with natural language
  • Multi-dimensional Data Correlation: Connect stocks, sectors, financials, and news for a panoramic view
  • Agent Collaboration: Multiple specialized agents working together, covering the full workflow from data queries to research reports

Tech Stack

LayerTechnology
Agent FrameworkAgentScope 2.0 (Multi-Agent Orchestration)
Data StorageMySQL (Structured Query) + Milvus (Vector Retrieval)
Data CollectionPython + akshare + DrissionPage
LLMQwen / GPT / Claude
Embeddingtext-embedding-v3 / BGE
FrontendStreamlit / Gradio

2. Feature Modules

Six intelligent agent modules planned based on existing data assets:


2.1 Stock Analysis Agent

Data Support: Daily stock quotes + Company info + Financial statements

Core Features:

FeatureDescriptionImplementation
Fundamental ScoreAuto-score (0-100) based on ROE, gross margin, debt ratio, cash flowExtract key fields from 3 statements, weighted calculation
Valuation PercentilePE/PB/PCF percentile in 1-year history, determine over/undervaluedCalculate percentile on daily PE/PB series
Technical IndicatorsMA(5/10/20/60), MACD, RSI, Bollinger Bands, KDJReal-time calculation based on OHLCV data
Trading SignalsGolden/Dead cross, MA breakout, RSI overbought/oversoldTechnical indicator crossover detection
Stock Profile ReportComprehensive fundamental + technical + valuation + sector reportLLM aggregates analysis results into text

Example Queries:

"How is Pudong Bank's cash flow situation this quarter?"
"What is Ping An Bank's current valuation percentile?"
"Analyze Kweichow Moutai's technical trend and give trading advice"
"Generate a stock profile report for CATL"

To-Do:

  • tools/stock_fundamental.py — Fundamental indicator calculator (Done)
  • tools/stock_valuation.py — Valuation percentile analyzer (Done)
  • tools/stock_technical.py — Technical indicator calculator (Done)
  • tools/stock_analysis.py — Comprehensive stock analysis report (Done)
  • agents/stock_agent.py — Stock analysis agent (Done)

Agent Demo:

$ python agents/stock_agent.py
============================================================
FinAssistant — 金融智能体
============================================================
输入股票代码或问题开始分析,输入 'quit' 退出
============================================================
你: 帮我分析贵州茅台的技术面走势,给出操作建议
FinAssistant:
[调用工具: reset_tools]
[完成] 结果: The currently activated tool group(s): stock-technical.
[调用工具: calc_technical_summary]
[完成] 结果: === 600519.SH 技术指标分析 (2026-07-17) ===
收盘价: 1253.0
【移动平均线 MA】
MA5: 1237.78
MA10: 1217.11
MA20: 1204.07
MA60: 1263.65
均线趋势: 多头排列
【MACD】
DIF: -0.2443
DEA: -11.3353
MACD柱: 22.182
信号: 金叉
【RSI】
RSI(6): 92.76
RSI(12): 68.8
RSI(24): 48.73
RSI(6)信号: 超买
【布林带 BOLL】
上轨: 1252.21
中轨: 1204.07
下轨: 1155.92
【KDJ】
K: 84.3
D: 79.2
J: 94.49
信号: 金叉
【综合研判】
当前信号: MA多头排列, MACD金叉, RSI超买, KDJ金叉
### 贵州茅台(600519.SH)技术面分析与操作建议
#### 一、核心技术指标摘要(近120天)
| 指标类型 | 关键数据 | 信号解读 |
|---------|---------|---------|
| **均线系统** | MA5:1237.78, MA10:1217.11, MA20:1204.07, MA60:1263.65 | 短期均线多头排列,股价略低于MA60(1263.65),中期趋势依然向上 |
| **MACD** | DIF:-0.24, DEA:-11.34, MACD柱:22.18 | 低位金叉形成,空头趋势减弱,短期反弹信号明确 |
| **RSI** | RSI(6):92.76, RSI(12):68.80, RSI(24):48.73 | 短期RSI严重超买(>90),警惕回调风险 |
| **布林带** | 上轨:1252.21, 中轨:1204.07, 下轨:1155.92 | 股价突破上轨,处于强势区间,但短期乖离率偏大 |
| **KDJ** | K:84.30, D:79.20, J:94.49 | 高位金叉,短期上涨动能充足,但J线接近超买区 |
#### 二、综合研判
技术面呈现**强趋势与短期超买并存**的格局:
1. **多头趋势明确**:均线多头排列、MACD低位金叉、KDJ金叉共同构成中期上涨信号
2. **短期回调风险**:RSI超买、股价突破布林上轨提示短期涨幅过大,存在技术性回调需求
#### 三、操作建议
1. **持仓投资者**:
- 继续持有为主,可将MA20(1204.07)作为止损线
- 若股价回落至MA5-MA10区间(1217-1238)可适当加仓
- 短期若冲高至MA60(1263.65)遇阻,可考虑部分止盈
2. **观望投资者**:
- 等待回调至关键支撑位(MA20:1204或布林中轨:1204)再考虑进场
- 若股价直接突破MA60并站稳,可小仓位追涨
⚠️ **风险提示**:技术分析仅供参考,不构成投资建议。市场存在不确定性,需结合自身风险承受能力决策。

2.2 Sector Rotation Analysis Agent

Data Support: Industry/Concept sector daily quotes (90 industry + 374 concept) + Constituent stocks

Core Features:

FeatureDescriptionImplementation
Sector RankingRank by pct_chg, volume change, capital flowAggregate sector daily_index
Rotation TrendSectors with consecutive top N-day gains marked as "hot"Sliding window rank change analysis
Sector ComparisonMulti-sector price curves overlayExtract multiple sector close series
Constituent DistributionAdvance/decline count, limit up/down, median changeLink constituent daily data
Capital FlowVolume change trend, determine inflow/outflowVolume QoQ change analysis
Sector CorrelationConstituent stock overlap between two sectorsSet intersection/union ratio

Example Queries:

"Which industry sectors had the highest gains this week?"
"How has the semiconductor sector performed this month? Is capital flowing in or out?"
"How high is the overlap between AI and robotics concept constituents?"
"Which sectors had limit-down waves today?"

To-Do:

  • tools/sector_ranking.py — Sector ranking tool (Done)
  • tools/sector_rotation.py — Rotation trend identifier (Done)
  • tools/sector_compare.py — Sector comparison tool (Done)
  • tools/sector_detail.py — Sector deep analysis tool (Done)
  • agents/sector_agent.py — Sector analysis agent (Done)

Agent Demo:

$ python agents/sector_agent.py
============================================================
FinAssistant — 板块轮动分析智能体
============================================================
输入板块相关问题开始分析,输入 'quit' 退出
示例:
- 最近一周涨幅最大的行业板块有哪些?
- 半导体板块最近一个月资金是在流入还是流出?
- AI概念和机器人概念的成分股重叠度有多高?
- 今天哪些板块出现了跌停潮?
============================================================
你: 最近一周涨幅最大的行业板块有哪些?
FinAssistant:
[调用工具: get_sector_ranking]
[完成] 结果: === 行业板块涨跌幅排名 (2026-07-17) ===
Top 10:
排名 板块名称 涨跌幅(%) 成交额(亿)
1 通信设备 +5.23 312.45
2 半导体 +4.87 528.91
3 消费电子 +3.65 287.33
...
[调用工具: get_sector_top_gainers]
[完成] 结果: === 连续3天上涨的行业板块 ===
板块名称 连涨天数 累计涨幅(%)
半导体 3 +8.92
通信设备 3 +7.56
...
综合来看,最近一周涨幅最大的行业板块主要集中在科技领域:
1. **通信设备** (+5.23%) — 5G建设持续推进,板块领涨
2. **半导体** (+4.87%) — 国产替代逻辑强化,资金持续流入
3. **消费电子** (+3.65%) — 新品发布预期带动板块走强
其中半导体和通信设备已连续3天上涨,短期动能较强。
⚠️ 风险提示:板块轮动较快,追高需谨慎。以上分析仅供参考,不构成投资建议。

2.3 Cross-Data Correlation Analysis Agent

Data Support: Quotes + Constituents + Financial statements + News (Full data cross-correlation)

Core Features:

FeatureDescriptionImplementation
Stock→Sector MappingQuery which sectors a stock belongs to, recent performanceReverse lookup in constituent data
Sector→Financial AggregationAverage ROE, median PE, total revenue for sector constituentsLink constituent codes to financial statements
News→Quote CorrelationCompanies/sectors mentioned in news, link to recent price trendsNER entity recognition + code matching
Industry ChainInfer upstream/downstream relationships via concept overlapConstituent set similarity clustering
Leader EffectTop N stocks by market cap vs sector overall performanceMarket-cap weighted vs equal-weight index

Example Queries:

"Which concept sectors does BYD belong to? How are they performing?"
"What's the average PE and ROE for the semiconductor sector?"
"Any recent news about solar power? How are related sectors trending?"
"Find the top 5 stocks most correlated with CATL"

To-Do:

  • tools/stock_sector_mapping.py — Stock-sector mapping tool (Done)
  • tools/sector_financial_agg.py — Sector financial aggregation (Done)
  • tools/news_stock_linker.py — News-quote correlation tool (Done)
  • agents/correlation_agent.py — Correlation analysis agent (Done)

2.4 Financial Q&A Agent (RAG)

Data Support: Financial statements (4,593 stocks × multi-period) + Vector database (Milvus)

Core Features:

FeatureDescriptionImplementation
NL Financial Query"Which companies have gross margin > 50%" → SQL/Vector searchVectorize financial fields + structured query
Cross-stock ComparisonHorizontal comparison of financial indicators for same-industry companiesGroup by industry + indicator comparison
Multi-period TrendVertical comparison of same company across periodsTime series analysis + trend detection
Anomaly AlertCash flow plunge, receivables surge, goodwill impairmentThreshold/QoQ change detection
Financial Health ScoreComprehensive solvency, profitability, growth, operational abilityDuPont analysis system + weighted scoring

Example Queries:

"Which banks have positive operating cash flow for the past year?"
"Compare CATL and BYD's debt ratio trends"
"Which companies had gross margin drop > 10% last quarter?"
"Give me a DuPont analysis for Kweichow Moutai"
"Find companies with ROE > 20% for 3 consecutive years"

To-Do:

  • tools/financial_query.py — Financial data query tool (Done)
  • tools/financial_compare.py — Financial comparison tool (Done)
  • tools/financial_anomaly.py — Anomaly detection tool (Done)
  • tools/financial_score.py — Financial health scoring tool (Done)
  • agents/financial_agent.py — Financial Q&A agent (Done)
  • rag/financial_embedding.py — Financial statement vectorization

2.5 Daily Market Report Agent

Data Support: Full data (Quotes + Sectors + News + Financials)

Core Features:

FeatureDescriptionImplementation
Market OverviewMajor index changes, volume, advance/decline statsAggregate all market stock data
Sector Rotation SummaryTop gainers/losers, capital inflow/outflow Top5Sector ranking tool output
Anomaly DetectionLimit up/down, volume breakout, abnormal volatilityFilter conditions
News SummaryMarket-related important news, linked sectorsNews filtering + LLM summary
Watchlist ReportUser's watched stocks daily performance, announcementsPersonalized filtering
Trend AssessmentBased on recent N-day data, market sentiment judgmentMulti-indicator synthesis

Example Queries:

"Generate today's market morning briefing"
"Which stocks hit limit up today? Which sectors do they belong to?"
"How has market sentiment been this week?"
"How are my watchlist stocks performing today?"

To-Do:

  • tools/market_overview.py — Market overview tool (Done)
  • tools/abnormal_detector.py — Anomaly detection tool (Done)
  • tools/market_trend.py — Trend assessment tool (Done)
  • tools/watchlist_report.py — Watchlist report tool (Done)
  • tools/daily_digest.py — Daily report generator (Done, integrates all 6 modules)
  • agents/daily_report_agent.py — Daily report agent (Done)

2.6 Research Report Generation Agent

Data Support: Full data + LLM generation capabilities

Core Features:

FeatureDescriptionImplementation
Stock Deep ReportComprehensive fundamental + technical + valuation + industry positionCall previous tools + LLM long-text generation
Industry ResearchSector trends, constituent financials, industry chain analysisSector tools + Financial tools + LLM
Comparative Report2-3 same-industry companies multi-dimensional comparisonComparison tools + LLM
Event Impact AnalysisNews/policy impact on related sectors and stocksNews correlation + Historical analogy + LLM
Portfolio SuggestionRecommend sector/stock allocation based on risk preferenceOptimization algorithm + LLM

Example Queries:

"Write a deep research report on the semiconductor industry"
"Compare BYD, CATL, and LONGi Green Energy with a comparative analysis"
"Which A-share sectors are most affected by Fed rate hikes?"
"I prefer conservative investing, recommend some sector allocation plans"

To-Do:

  • tools/report_generator.py — Report generation tool (LLM + templates)
  • templates/ — Report templates (stock/industry/comparison/event)
  • agents/report_agent.py — Report generation agent
  • agents/portfolio_agent.py — Portfolio optimization agent

3. Data Assets

3.1 Data Overview

Data TypeVolumeSourceTime Range
SH Stock Daily Quotes2,308 stocksSina Finance (akshare)2026-01-01 ~ Present
SZ Stock Daily Quotes2,895 stocksSina Finance (akshare)2026-01-01 ~ Present
SH Company Info2,308 (Main 1,699 + STAR 609)SSE (akshare)-
SZ Company Info2,895SZSE (akshare)-
SH Financial Statements2,308 stocksSina Finance (akshare)Recent 3 years
SZ Financial Statements2,895 stocksSina Finance (akshare)Recent 3 years
Industry Sector Quotes90 sectorsTonghuashun (akshare)2026-01-01 ~ Present
Concept Sector Quotes374 sectorsTonghuashun (akshare)2026-01-01 ~ Present
Industry Constituents90 sectorsTonghuashun (DrissionPage)-
Concept Constituents374 sectorsTonghuashun (DrissionPage)-
Financial News-Tonghuashun 7x242026-01-01 ~ Present

3.2 MySQL Table Schema

Data is stored in Alibaba Cloud RDS MySQL with two databases: market_data (quotes/financials) and stock_news (news).

market_data.company_info — Company Basic Info

CREATETABLEcompany_info (
id INT AUTO_INCREMENT PRIMARY KEY COMMENT 'Auto-increment ID',
ts_code VARCHAR(20) NOT NULL COMMENT 'Stock code with suffix, e.g., 600000.SH',
symbol VARCHAR(10) NOT NULL COMMENT 'Stock code (numeric only)',
stock_name VARCHAR(50) COMMENT 'Stock short name',
full_name VARCHAR(100) COMMENT 'Company full name',
industry VARCHAR(50) COMMENT 'Industry, e.g., J Finance',
list_date VARCHAR(20) COMMENT 'Listing date, format YYYY-MM-DD',
market VARCHAR(5) COMMENT 'Market, SH=Shanghai SZ=Shenzhen',
updated_at VARCHAR(30) COMMENT 'Data update time',
UNIQUE KEY uk_ts_code (ts_code)
)

market_data.stock_kline — Stock Daily K-line

CREATETABLEstock_kline (
id BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT 'Auto-increment ID',
ts_code VARCHAR(20) NOT NULL COMMENT 'Stock code with suffix',
symbol VARCHAR(10) NOT NULL COMMENT 'Stock code (numeric only)',
trade_date VARCHAR(20) NOT NULL COMMENT 'Trade date, format YYYY-MM-DD',
open DOUBLE COMMENT 'Open price (CNY)',
close DOUBLE COMMENT 'Close price (CNY)',
high DOUBLE COMMENT 'High price (CNY)',
low DOUBLE COMMENT 'Low price (CNY)',
pre_close DOUBLE COMMENT 'Previous close (CNY)',
change_data DOUBLE COMMENT 'Price change (CNY)',
pct_chg DOUBLE COMMENT 'Change percentage (%)',
volume DOUBLE COMMENT 'Volume (shares)',
amount DOUBLE COMMENT 'Turnover (CNY)',
pe DOUBLE COMMENT 'P/E ratio',
pb DOUBLE COMMENT 'P/B ratio',
total_mv DOUBLE COMMENT 'Total market cap (100M CNY)',
total_share DOUBLE COMMENT 'Total shares',
float_share DOUBLE COMMENT 'Float shares',
circ_mv DOUBLE COMMENT 'Circulating market cap (100M CNY)',
ln_pctchg DOUBLE COMMENT 'Log return',
pe_ttm DOUBLE COMMENT 'P/E ratio (TTM)',
pe_static DOUBLE COMMENT 'Static P/E ratio',
pcf DOUBLE COMMENT 'Price-to-Cash-Flow ratio',
UNIQUE KEY uk_code_date (ts_code, trade_date),
KEY idx_trade_date (trade_date),
KEY idx_symbol (symbol)
)

market_data.stock_financial — Financial Statements

CREATETABLEstock_financial (
id BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT 'Auto-increment ID',
ts_code VARCHAR(20) NOT NULL COMMENT 'Stock code with suffix',
symbol VARCHAR(10) NOT NULL COMMENT 'Stock code (numeric only)',
statement_type VARCHAR(20) NOT NULL COMMENT 'Statement type: income/balance/cashflow',
report_date VARCHAR(20) NOT NULL COMMENT 'Report date, e.g., 20260331',
report_data JSON COMMENT 'Complete statement data (JSON)',
UNIQUE KEY uk_code_type_date (ts_code, statement_type, report_date),
KEY idx_symbol (symbol),
KEY idx_report_date (report_date),
KEY idx_statement_type (statement_type)
)

Financial fields vary significantly across industries (banking vs manufacturing), hence JSON storage for complete statement data.

market_data.sector_industry_daily / sector_concept_daily — Sector Daily K-line

CREATETABLEsector_industry_daily (
id BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT 'Auto-increment ID',
sector_name VARCHAR(50) NOT NULL COMMENT 'Sector name',
sector_code VARCHAR(20) NOT NULL COMMENT 'Sector code',
trade_date VARCHAR(20) NOT NULL COMMENT 'Trade date',
open DOUBLE COMMENT 'Open',
high DOUBLE COMMENT 'High',
low DOUBLE COMMENT 'Low',
close DOUBLE COMMENT 'Close',
vol DOUBLE COMMENT 'Volume',
amount DOUBLE COMMENT 'Turnover',
pct_chg DOUBLE COMMENT 'Change (%)',
change_data DOUBLE COMMENT 'Point change',
pct_change DOUBLE COMMENT 'Change (backup)',
turnover_rate DOUBLE COMMENT 'Turnover rate',
UNIQUE KEY uk_code_date (sector_code, trade_date),
KEY idx_trade_date (trade_date),
KEY idx_sector_name (sector_name)
)

market_data.sector_industry_cons / sector_concept_cons — Sector Constituents

CREATETABLEsector_industry_cons (
id BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT 'Auto-increment ID',
sector_name VARCHAR(50) NOT NULL COMMENT 'Sector name',
sector_code VARCHAR(20) NOT NULL COMMENT 'Sector code',
stock_code VARCHAR(10) NOT NULL COMMENT 'Stock code',
stock_name VARCHAR(50) COMMENT 'Stock name',
UNIQUE KEY uk_sector_stock (sector_code, stock_code),
KEY idx_sector_name (sector_name),
KEY idx_stock_code (stock_code)
)

stock_news.news_em — Eastmoney 7x24 News

CREATETABLEnews_em (
id INT AUTO_INCREMENT PRIMARY KEY COMMENT 'Auto-increment ID',
title VARCHAR(500) NOT NULL COMMENT 'News title',
digest TEXT COMMENT 'News digest',
publish_time VARCHAR(30) COMMENT 'Publish time',
url VARCHAR(500) COMMENT 'News URL',
crawl_time VARCHAR(30) COMMENT 'Crawl time',
UNIQUE KEY uk_title_time (title, publish_time)
)

stock_news.news_ths — Tonghuashun Financial News

CREATETABLEnews_ths (
id INT AUTO_INCREMENT PRIMARY KEY COMMENT 'Auto-increment ID',
news_id VARCHAR(20) NOT NULL COMMENT 'News ID',
title VARCHAR(500) NOT NULL COMMENT 'News title',
digest TEXT COMMENT 'News digest',
url VARCHAR(500) COMMENT 'News URL',
tags VARCHAR(500) COMMENT 'Tags (comma separated)',
ctime_str VARCHAR(30) COMMENT 'Publish time',
source VARCHAR(100) COMMENT 'Source',
crawl_time VARCHAR(30) COMMENT 'Crawl time',
UNIQUE KEY uk_news_id (news_id),
KEY idx_ctime (ctime_str)
)

3.3 Data Import Scripts

ScriptTarget TableDescription
import_company_info_to_mysql.pymarket_data.company_infoSH/SZ company info
import_kline_to_mysql.pymarket_data.stock_klineStock daily K-line (560K+ rows)
import_financial_to_mysql.pymarket_data.stock_financialFinancial statements (170K+ rows)
import_sector_to_mysql.pymarket_data.sector_*_dailySector daily K-line
import_sector_cons_to_mysql.pymarket_data.sector_*_consSector constituents
import_news_em_to_mysql.pystock_news.news_emEastmoney news
import_news_ths_to_mysql.pystock_news.news_thsTonghuashun news

3.4 Data Collection Scripts

ScriptPurposeSource
crawl_sh_stock_data.pySH stock quotes + company infoSina Finance / SSE
crawl_sz_stock_data.pySZ stock quotes + company infoSina Finance / SZSE
crawl_financial_reports.pyFinancial statementsSina Finance
crawl_sector_data.pySector daily quotes (Industry + Concept)Tonghuashun (akshare)
crawl_sector_cons.pySector constituentsSina Finance (akshare)
crawl_sector_cons_ths.pySector constituents (backup)Tonghuashun (DrissionPage)
crawl_news_ths.pyFinancial newsTonghuashun 7x24 API
crawl_news_em.pyEastmoney 7x24 news (scheduled)Eastmoney (akshare)

3.5 Known Issues

IssueDescription
Eastmoney API Blockedpush2his.eastmoney.com completely unavailable
Tonghuashun IP BlockedFrequent crawling triggers Nginx 403 block
Inconsistent Sector SourcesQuotes from THS, constituents partially from Sina, names may not match
SH Company Missing IndustrySSE API doesn't provide industry field

4. AgentScope 2.0 Implementation

4.1 Architecture

User Query → FastAPI → Agent (system_prompt + model + toolkit + middlewares)
↓
Toolkit
├── ToolGroup("Stock Analysis") → tools/stock_query.py + skills/stock-analysis/
├── ToolGroup("Sector Analysis") → tools/sector_query.py + skills/sector-rotation/
├── ToolGroup("Financial Q&A") → tools/financial_query.py + skills/financial-qa/
├── ToolGroup("Daily Report") → tools/news_query.py + skills/daily-report/
└── ToolGroup("Research Report") → tools/indicators.py + skills/research-report/

4.2 Directory Structure

FinAssistant/
├── config.py # Global config (paths, model, API Key)
├── main.py # FastAPI service entry
├── main_agent.py # Single agent script (no server, direct chat)
├── core/
│ ├── agent_setup.py # Agent + Toolkit initialization
│ └── middleware.py # Financial scenario middleware
├── tools/ # Tool functions
│ ├── __init__.py
│ ├── stock_query.py # Stock quote/company info query
│ ├── sector_query.py # Sector quote/constituent query
│ ├── financial_query.py # Financial statement query & analysis
│ ├── news_query.py # News query
│ └── indicators.py # Technical/fundamental indicator calculation
├── skills/ # Skill documents (SKILL.md)
│ ├── stock-analysis/SKILL.md
│ ├── sector-rotation/SKILL.md
│ ├── financial-qa/SKILL.md
│ ├── daily-report/SKILL.md
│ └── research-report/SKILL.md
├── data/ # Existing data (don't modify)
└── data_to_mysql_and_milvus/ # Existing crawler scripts (don't modify)

4.3 Implementation Steps

Step 1: config.py

Global configuration for data paths, model config, API keys.

Step 2: tools/ Tool Functions

Each function is async def, returns ToolChunk. Docstring is the tool description — LLM decides when to call based on docstring.

Step 3: skills/SKILL.md Skill Documents

Each skill directory has a SKILL.md with trigger conditions, dependent tools, and execution flow.

Step 4: core/middleware.py Middleware

MiddlewarePurpose
InputValidationMiddlewareFilter non-financial queries
ToolCallAuditMiddlewareLog tool calls to traces/
PerformanceMonitorMiddlewareMonitor inference rounds, latency, tokens
ContextEnrichmentMiddlewareInject current date, trading day context

Step 5: core/agent_setup.py Agent Initialization

Assemble model, tools, toolkit, and agent with middleware.

Step 6: main.py Service Entry

FastAPI service with OpenAI-compatible /v1/chat/completions endpoint.


5. Implemented Tools

tools/stock_fundamental.py — Fundamental Indicator Calculator

Calculates fundamental indicators from MySQL market_data.stock_financial table.

Core Functions:

FunctionDescription
calc_fundamental_indicators(ts_code, report_date=None)Calculate single-period indicators
calc_fundamental_trend(ts_code, periods=4)Calculate recent N-period trend
get_financial_data(ts_code, report_date=None)Get raw statement data
get_report_dates(ts_code, limit=8)Get report date list

Calculated Indicators:

IndicatorFormulaData Source
ROENet Profit / Equity × 100%Income + Balance Sheet
Gross Margin(Revenue - COGS) / Revenue × 100%Income Statement
Net MarginNet Profit / Revenue × 100%Income Statement
Debt RatioTotal Liabilities / Total Assets × 100%Balance Sheet
Cash Flow / Net ProfitOperating Cash Flow / Net ProfitCash Flow + Income
Revenue YoY Growth(Current - Prior Year) /Prior Year
Net Profit YoY Growth(Current - Prior Year) /Prior Year
Revenue QoQ Growth(Current Q - Prior Q) /Prior Q
Net Profit QoQ Growth(Current Q - Prior Q) /Prior Q

Special Handling:

  • Auto bank detection: Via balance sheet fields (loans, deposits)
  • Bank field mapping: Revenue = Net Interest Income + Fee Income; COGS = Interest Expense + Fee Expense
  • YoY calculation: Cumulative values vs same quarter last year (2026Q1 vs 2025Q1)
  • QoQ calculation: Single-quarter values (Q4 = Annual - 9-month cumulative)

Usage:

fromtools.stock_fundamentalimportcalc_fundamental_indicators, calc_fundamental_trend# Single periodresult=calc_fundamental_indicators('600519.SH')
print(result['ROE'], result['毛利率'], result['营收同比增长率'])
# Trend (recent 4 periods)trend=calc_fundamental_trend('600519.SH', periods=4)
fortintrend['trend']:
print(t['report_date'], t['ROE'], t['营收同比增长率'])

tools/stock_valuation.py — Valuation Percentile Analyzer

Calculates PE/PB/PCF percentile in 1-year history from market_data.stock_kline table.

Core Functions:

FunctionDescription
calc_valuation_percentile(ts_code, days=365)Calculate valuation percentile, return structured data
calc_valuation_summary(ts_code, days=365)Generate formatted valuation summary
get_valuation_history(ts_code, days=365)Get N-day valuation history
get_latest_valuation(ts_code)Get latest day valuation data

Valuation Indicators:

IndicatorDescriptionSource
PE_TTMPrice-to-Earnings (Trailing Twelve Months)stock_kline.pe_ttm
PBPrice-to-Bookstock_kline.pb
PCFPrice-to-Cash-Flowstock_kline.pcf

Percentile Rules:

PercentileLevelMeaning
< 20%UndervaluedAt historical low, potentially undervalued
20% - 40%Below AverageBelow historical median
40% - 60%FairAt historical median range
60% - 80%Above AverageAbove historical median
> 80%OvervaluedAt historical high, potentially overvalued

Usage:

fromtools.stock_valuationimportcalc_valuation_percentile, calc_valuation_summary# Get structured dataresult=calc_valuation_percentile('600519.SH')
print(f"PE_TTM: {result['pe_ttm']}, Percentile: {result['pe_ttm_percentile']}%, {result['pe_ttm_level']}")
# Get formatted summaryprint(calc_valuation_summary('600519.SH'))

tools/stock_technical.py — Technical Indicator Calculator

Calculates MA/MACD/RSI/BOLL/KDJ indicators from MySQL market_data.stock_kline table.

Core Functions:

FunctionDescription
calc_technical_indicators(ts_code, days=120)Calculate all technical indicators
calc_technical_summary(ts_code, days=120)Generate formatted summary
get_kline_data(ts_code, days=120)Get K-line data from MySQL

Technical Indicators:

IndicatorFormulaUsage
MA(5/10/20/60)Average of last N closing pricesTrend: Price above MA = bullish; MA crossover = buy/sell signal
MACDDIF = EMA(12) - EMA(26); DEA = EMA(DIF,9); Histogram = (DIF-DEA)×2Golden cross (DIF>DEA) = buy; Dead cross = sell
RSI(6/12/24)RS = Avg Gain / Avg Loss; RSI = 100 - 100/(1+RS)>80 = overbought; <20 = oversold
BOLL(20,2)Upper = MA+2σ; Middle = MA; Lower = MA-2σTouch upper = overbought; Touch lower = oversold
KDJ(9,3,3)RSV, K = 2/3K+1/3RSV, D = 2/3D+1/3K, J = 3K-2DK>80 = overbought; K<20 = oversold; K/D crossover

Signal Interpretation:

SignalMAMACDRSIBOLLKDJ
BullishMA5>MA10>MA20 (Bull alignment)DIF>DEA, Histogram>0RSI<20 (Oversold)Price bounces off lower bandK/D golden cross in oversold zone
BearishMA5<MA10<MA20 (Bear alignment)DIF<DEA, Histogram<0RSI>80 (Overbought)Price falls from upper bandK/D dead cross in overbought zone

Multi-indicator Confirmation:

Buy signals (need 2-3):

  • Price above MA20, MA bullish alignment (MA5>MA10>MA20)
  • MACD golden cross (DIF crosses above DEA)
  • RSI rebounds from oversold (<20 → >20)
  • Price bounces off Bollinger lower band
  • KDJ golden cross in oversold zone

Sell signals (need 2-3):

  • Price below MA20, MA bearish alignment (MA5<MA10<MA20)
  • MACD dead cross (DIF crosses below DEA)
  • RSI enters overbought (>80) then falls
  • Price falls from Bollinger upper band
  • KDJ dead cross in overbought zone

Usage:

fromtools.stock_technicalimportcalc_technical_indicators, calc_technical_summary# Get structured dataresult=calc_technical_indicators('600519.SH')
print(f"Close: {result['close']}, MA5: {result['ma5']}, MACD: {result['macd_signal']}")
# Get formatted summaryprint(calc_technical_summary('600519.SH'))

5.5 Sector Analysis Tools

tools/sector_ranking.py — Sector Ranking Tool

Calculates sector rankings from MySQL sector_industry_daily / sector_concept_daily tables.

Core Functions:

FunctionDescription
get_sector_ranking(sector_type, trade_date, top_n, sort_by)Sector ranking by pct_chg/amount/volume
get_sector_top_gainers(sector_type, days, top_n)Sectors with consecutive N-day gains
get_sector_top_losers(sector_type, days, top_n)Sectors with consecutive N-day losses
get_sector_summary(sector_type, trade_date)Market overview (advance/decline, limit up/down)

Usage:

fromtools.sector_rankingimportget_sector_ranking, get_sector_top_gainers, get_sector_summary# Top 10 industry sectors by pct_chgprint(get_sector_ranking(sector_type='industry', top_n=10))
# Sectors rising for 3 consecutive daysprint(get_sector_top_gainers(sector_type='industry', days=3))
# Industry sector market overviewprint(get_sector_summary(sector_type='industry'))

tools/sector_rotation.py — Rotation Trend Identifier

Analyzes sector momentum and capital rotation direction through short-term vs medium-term performance comparison.

Core Functions:

FunctionDescription
get_sector_momentum(sector_type, short_days, long_days, top_n)Momentum analysis — short vs medium term, momentum score
get_sector_rotation(sector_type, short_days, long_days, top_n)Rotation identification — capital inflow/outflow sectors
get_sector_strength(sector_type, days, top_n)Strength ranking — composite score of gains, up-days, volume
get_hot_cold_sectors(sector_type, days)Hot/cold classification — hot/warm/flat/cold categories

Usage:

fromtools.sector_rotationimportget_sector_momentum, get_sector_rotation, get_hot_cold_sectors# Industry sector momentum (3-day short vs 10-day medium)print(get_sector_momentum(sector_type='industry', short_days=3, long_days=10))
# Sector rotation (capital inflow/outflow)print(get_sector_rotation(sector_type='industry'))
# Hot/cold sector classificationprint(get_hot_cold_sectors(sector_type='industry', days=5))

tools/sector_compare.py — Sector Comparison Tool

Multi-sector price curve overlay comparison with normalization and ASCII trend charts.

Core Functions:

FunctionDescription
compare_sectors(sector_names, sector_type, days)Multi-sector cumulative return comparison (table + ASCII chart)
compare_sector_trend(sector_names, sector_type, days)Trend strength comparison with conclusion

Usage:

fromtools.sector_compareimportcompare_sectors, compare_sector_trend# Compare Baijiu vs Power vs Banks over 20 daysprint(compare_sectors(['白酒', '电力', '银行'], sector_type='industry', days=20))
# Trend strength comparison with conclusionprint(compare_sector_trend(['白酒', '电力', '银行', '证券'], days=20))

tools/sector_detail.py — Sector Deep Analysis Tool

Links constituent stock data to provide internal sector structure analysis.

Core Functions:

FunctionDescription
get_constituent_distribution(sector_name, sector_type, trade_date)Constituent distribution — advance/decline, limit up/down, median change, top/bottom 5
get_sector_money_flow(sector_name, sector_type, days)Capital flow analysis — volume trend, price-volume coordination, inflow/outflow
get_sector_correlation(sector_name1, sector_name2, sector_type)Sector correlation — Jaccard coefficient, overlapping constituents

Usage:

fromtools.sector_detailimportget_constituent_distribution, get_sector_money_flow, get_sector_correlation# Baijiu sector constituent distributionprint(get_constituent_distribution('白酒', sector_type='industry'))
# Power sector capital flow analysisprint(get_sector_money_flow('电力', sector_type='industry', days=10))
# Baijiu vs Beer sector correlationprint(get_sector_correlation('白酒', '啤酒', sector_type='industry'))

tools/news_stock_linker.py — News-Stock Linker

Links news headlines to mentioned companies/sectors and correlates with their recent price trends.

Core Functions:

FunctionDescription
find_news_by_keyword(keyword, limit)Search news by keyword (title/digest fuzzy match)
search_news_with_market(keyword, limit, days_before, days_after)Search news and auto-correlate with matched stocks/sectors price trends

Usage Example:

fromtools.news_stock_linkerimportfind_news_by_keyword, search_news_with_market# Search news by keywordprint(find_news_by_keyword('半导体', limit=5))
# Search news and correlate with market dataprint(search_news_with_market('贵州茅台', limit=3, days_before=3, days_after=3))

5.6 Sector Analysis Agent

agents/sector_agent.py — Sector Analysis Agent

Integrates sector ranking, rotation, comparison, and deep analysis tool groups for sector rotation analysis.

Tool Group Structure:

Tool GroupToolsDescription
sector-rankingget_sector_ranking / get_sector_top_gainers / get_sector_top_losers / get_sector_summarySector ranking
sector-rotationget_sector_momentum / get_sector_rotation / get_sector_strength / get_hot_cold_sectorsRotation analysis
sector-comparecompare_sectors / compare_sector_trendSector comparison
sector-detailget_constituent_distribution / get_sector_money_flow / get_sector_correlationDeep analysis

Run:

python agents/sector_agent.py

5.7 Correlation Analysis Agent

agents/correlation_agent.py — Correlation Analysis Agent

Integrates stock-sector mapping, sector financial aggregation, and news-market correlation tool groups for cross-data analysis.

Tool Group Structure:

Tool GroupToolsDescription
stock-sectorfind_stock_sectorsStock-sector mapping
sector-financeget_sector_financial_agg / get_sector_valuation_statsSector financial aggregation, valuation distribution
news-marketfind_news_by_keyword / search_news_with_marketNews search, news-market correlation

Run:

python agents/correlation_agent.py

5.8 Financial Health Scoring Tool

tools/financial_score.py — Financial Health Scoring Tool

Computes a four-dimension composite financial health score (0-100) with rating (Excellent/Good/Fair/Poor).

Scoring Dimensions:

DimensionWeightIndicators
Profitability30%ROE(40%) + Gross Margin(30%) + Net Margin(30%)
Growth25%Revenue YoY Growth(50%) + Net Profit YoY Growth(50%)
Safety25%Debt Ratio(40%) + Cash Flow/NP(35%) + AR Ratio(25%)
Quality20%Deducted NP Ratio(50%) + Cash Flow Consistency(50%)

Anomaly Deduction: HIGH -5pts, MEDIUM -2pts, max -15pts.

Core Functions:

FunctionDescription
calc_financial_score(ts_code, report_date=None)Calculate single stock financial health score
format_financial_score(ts_code, report_date=None)Generate formatted Markdown output
score_sector(sector_name, sector_type, top_n)Batch score sector constituents

Run:

python tools/financial_score.py --ts_code 600519.SH
python tools/financial_score.py --sector 白酒 --top_n 10
python tools/financial_score.py --ts_codes 600519.SH,300750.SZ,601318.SH

5.9 Financial Q&A Agent

agents/financial_agent.py — Financial Q&A Agent

Integrates fundamental indicators, trend analysis, comparison, anomaly detection, financial scoring, and batch screening tool groups for complex financial Q&A.

Tool Group Structure:

Tool GroupToolsDescription
fundamentalcalc_fundamental_indicators / calc_fundamental_trend / get_financial_data / get_report_datesFinancial indicator calculation
comparecompare_companies / compare_periodsFinancial comparison and trends
score-anomalyformat_financial_score / calc_financial_score / detect_anomaliesScoring and anomaly detection
screeningscreen_cashflow_positive_stocks / screen_margin_decline_stocks / screen_roe_stocksBatch screening
queryquery_financial_dataFinancial data query

Example Queries:

"Which banks have positive operating cash flow for the past year?"
"Compare CATL and BYD's debt ratio trends"
"Which companies had gross margin drop > 10% last quarter?"
"Give me a DuPont analysis for Kweichow Moutai"
"Find companies with ROE > 20% for 3 consecutive years"

Run:

python agents/financial_agent.py

5.10 Daily Market Report Agent

agents/daily_report_agent.py — Daily Market Report Agent

Integrates market overview, trend assessment, sector rotation, anomaly detection, news correlation, and watchlist report tool groups for natural language Q&A on daily market briefings.

Tool Group Structure:

Tool GroupToolsDescription
market-overviewget_market_overview / format_market_overviewMarket overview
market-trendanalyze_market_trend / format_market_trendTrend assessment
sector-analysisget_sector_ranking / get_sector_rotation / get_hot_cold_sectors etc. (8 tools)Sector analysis
abnormal-detectiondetect_abnormal / format_abnormalAnomaly detection
newsfind_news_by_keyword / search_news_with_marketNews search
watchlistget_watchlist_report / format_watchlist_reportWatchlist report
daily-digestgenerate_daily_digestOne-click daily report

Example Queries:

"Generate today's market morning briefing"
"Which stocks hit limit up today? Which sectors do they belong to?"
"How has market sentiment been this week?"
"Which sectors are seeing capital inflow?"
"What important news is there today?"
"How are my watchlist stocks performing?"

Run:

python agents/daily_report_agent.py

5.11 Daily Market Report Tools

tools/market_overview.py — Market Overview Tool

Aggregates all market stock data to compute daily market overview (advance/decline counts, limit up/down, turnover, etc.).

Core Functions:

FunctionDescription
get_market_overview(trade_date=None)Get market overview as structured data
format_market_overview(trade_date=None)Generate formatted Markdown output

Output Metrics:

MetricDescription
Advance/DeclineUp/down/flat counts and percentages
Limit Up/DownMain board >=9.9%, ChiNext/STAR >=19.9%
Total TurnoverMarket-wide turnover (100M CNY)
Avg/Median ChangeOverall market change level
Market SentimentStrong rally/Bullish/Neutral/Bearish/Weak decline

Run:

python tools/market_overview.py
python tools/market_overview.py --trade_date 20260801

tools/abnormal_detector.py — Anomaly Detection Tool

Detects daily market anomalies: limit up/down stocks, volume breakouts, abnormal price movements, sector anomalies.

Core Functions:

FunctionDescription
detect_abnormal(trade_date=None)Detect anomalies, return structured data
format_abnormal(trade_date=None)Generate formatted Markdown output

Detection Types:

TypeCondition
Limit Up/DownMain board >=9.9%, ChiNext/STAR >=19.9%
Volume BreakoutVolume ratio >3 AND gain >3% (ratio = current vol / 20-day avg vol)
Price Surge
Sector Anomaly

Run:

python tools/abnormal_detector.py
python tools/abnormal_detector.py --trade_date 20260801

tools/market_trend.py — Trend Assessment Tool

Multi-dimensional market sentiment analysis based on recent N-day data.

Core Functions:

FunctionDescription
analyze_market_trend(days=5)Analyze market trend, return structured data
format_market_trend(days=5)Generate formatted Markdown output

Scoring Dimensions (20 pts each, 100 total):

DimensionSourceLogic
Advance/Decline Ratiostock_kline 5-dayAverage advancing stock ratio
Limit Up/Down Ratiostock_kline latestLimit up / (up + down + 1)
Turnover Trendstock_kline 5-dayRecent 5d vs prior 5d, volume expansion/contraction
Sector Rotationsector_industry_dailyAdvancing sector ratio
Consecutive Trendstock_kline 5-dayConsecutive up/down days

Sentiment Mapping: >=75 Optimistic / >=60 Mildly Bullish / >=40 Neutral / >=25 Mildly Bearish / <25 Pessimistic

Run:

python tools/market_trend.py
python tools/market_trend.py --days 10

tools/watchlist_report.py — Watchlist Report Tool

Personalized daily report for user-watched stocks: daily performance, 5-day change, related news.

Core Functions:

FunctionDescription
get_watchlist_report(ts_codes, trade_date=None)Get watchlist report as structured data
format_watchlist_report(ts_codes, trade_date=None)Generate formatted Markdown output

Report Content:

ModuleDescription
Daily PerformanceClose price, change %, turnover
5-Day ChangeCumulative change over 5 trading days
Related NewsSearch news by stock name (max 3 per stock)

Watchlist Config: Edit tools/watchlist_config.json to set default watchlist.

Run:

python tools/watchlist_report.py --ts_codes 600519.SH,300750.SZ
python tools/watchlist_report.py # Use default from watchlist_config.json

tools/daily_digest.py — Daily Report Generator (Enhanced)

Generates complete daily market briefing by integrating all 6 modules.

Core Functions:

FunctionDescription
generate_daily_digest(trade_date=None, watchlist=None)Generate complete daily report (Markdown)

Report Structure:

SectionModuleSource
1Market Overviewmarket_overview.py
2Trend Assessmentmarket_trend.py
3Sector Rotationsector_ranking.py + sector_rotation.py
4Market Anomaliesabnormal_detector.py
5Important Newsnews_stock_linker.py
6Watchlist Report (optional)watchlist_report.py

Run:

python tools/daily_digest.py
python tools/daily_digest.py --trade_date 20260801
python tools/daily_digest.py --watchlist 600519.SH,300750.SZ

5.12 Tool Function Mapping

Existing langgraph_getdata/New tools/Description
query_market_data_day_k.pystock_query.pyStock K-line query
query_industry_index_market.pysector_query.pySector quote query
query_industry_component_list.pysector_query.pySector constituents
query_concept_dc_day.pysector_query.pyConcept sector quotes
query_concept_dc_stock.pysector_query.pyConcept sector constituents
query_fin_account.pyfinancial_query.pyFinancial statement query (Done)
(None)news_query.pyNews query (New)
(None)stock_fundamental.pyFundamental indicators (Done)
(None)stock_valuation.pyValuation percentile (Done)
(None)stock_technical.pyTechnical indicators (Done)
(None)stock_sector_mapping.pyStock-sector mapping (Done)
(None)sector_financial_agg.pySector financial aggregation (Done)
(None)news_stock_linker.pyNews-stock correlation (Done)
(None)financial_score.pyFinancial health scoring (Done)
(None)sector_data.pySector data utilities (Done)
(None)market_overview.pyMarket overview tool (Done)
(None)abnormal_detector.pyAnomaly detection tool (Done)
(None)market_trend.pyTrend assessment tool (Done)
(None)watchlist_report.pyWatchlist report tool (Done)
(None)daily_digest.pyDaily report generator (Done)

5.13 Dependencies

pip install agentscope>=2.0.3 fastapi uvicorn

About

Built on professional finance knowledge, it provides stock diagnostics, sector index analysis, investment Q&A and news insights to help investors capture market opportunities efficiently.

Resources

Stars

5 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Repository files navigation

FinAssistant Logo

FinAssistant — AI-Powered Financial Analysis

RAG Retrieval & Agent System for China A-Share Market

BackgroundFeaturesData AssetsImplementationTools

中文 | English


1. Background

The China A-share market has diverse data dimensions and massive information volumes. Retail investors and small-to-medium institutions struggle to efficiently integrate stock quotes, sector rotation, financial statements, and market news for comprehensive analysis. This project aims to build a financial RAG retrieval and agent system based on collected A-share data assets, enabling users to perform professional financial analysis through natural language conversations.

Core Objectives

  • Lower Analysis Barriers: Replace manual data queries, indicator calculations, and report writing with natural language
  • Multi-dimensional Data Correlation: Connect stocks, sectors, financials, and news for a panoramic view
  • Agent Collaboration: Multiple specialized agents working together, covering the full workflow from data queries to research reports

Tech Stack

LayerTechnology
Agent FrameworkAgentScope 2.0 (Multi-Agent Orchestration)
Data StorageMySQL (Structured Query) + Milvus (Vector Retrieval)
Data CollectionPython + akshare + DrissionPage
LLMQwen / GPT / Claude
Embeddingtext-embedding-v3 / BGE
FrontendStreamlit / Gradio

2. Feature Modules

Six intelligent agent modules planned based on existing data assets:


2.1 Stock Analysis Agent

Data Support: Daily stock quotes + Company info + Financial statements

Core Features:

FeatureDescriptionImplementation
Fundamental ScoreAuto-score (0-100) based on ROE, gross margin, debt ratio, cash flowExtract key fields from 3 statements, weighted calculation
Valuation PercentilePE/PB/PCF percentile in 1-year history, determine over/undervaluedCalculate percentile on daily PE/PB series
Technical IndicatorsMA(5/10/20/60), MACD, RSI, Bollinger Bands, KDJReal-time calculation based on OHLCV data
Trading SignalsGolden/Dead cross, MA breakout, RSI overbought/oversoldTechnical indicator crossover detection
Stock Profile ReportComprehensive fundamental + technical + valuation + sector reportLLM aggregates analysis results into text

Example Queries:

"How is Pudong Bank's cash flow situation this quarter?"
"What is Ping An Bank's current valuation percentile?"
"Analyze Kweichow Moutai's technical trend and give trading advice"
"Generate a stock profile report for CATL"

To-Do:

  • tools/stock_fundamental.py — Fundamental indicator calculator (Done)
  • tools/stock_valuation.py — Valuation percentile analyzer (Done)
  • tools/stock_technical.py — Technical indicator calculator (Done)
  • tools/stock_analysis.py — Comprehensive stock analysis report (Done)
  • agents/stock_agent.py — Stock analysis agent (Done)

Agent Demo:

$ python agents/stock_agent.py
============================================================
FinAssistant — 金融智能体
============================================================
输入股票代码或问题开始分析,输入 'quit' 退出
============================================================
你: 帮我分析贵州茅台的技术面走势,给出操作建议
FinAssistant:
[调用工具: reset_tools]
[完成] 结果: The currently activated tool group(s): stock-technical.
[调用工具: calc_technical_summary]
[完成] 结果: === 600519.SH 技术指标分析 (2026-07-17) ===
收盘价: 1253.0
【移动平均线 MA】
MA5: 1237.78
MA10: 1217.11
MA20: 1204.07
MA60: 1263.65
均线趋势: 多头排列
【MACD】
DIF: -0.2443
DEA: -11.3353
MACD柱: 22.182
信号: 金叉
【RSI】
RSI(6): 92.76
RSI(12): 68.8
RSI(24): 48.73
RSI(6)信号: 超买
【布林带 BOLL】
上轨: 1252.21
中轨: 1204.07
下轨: 1155.92
【KDJ】
K: 84.3
D: 79.2
J: 94.49
信号: 金叉
【综合研判】
当前信号: MA多头排列, MACD金叉, RSI超买, KDJ金叉
### 贵州茅台(600519.SH)技术面分析与操作建议
#### 一、核心技术指标摘要(近120天)
| 指标类型 | 关键数据 | 信号解读 |
|---------|---------|---------|
| **均线系统** | MA5:1237.78, MA10:1217.11, MA20:1204.07, MA60:1263.65 | 短期均线多头排列,股价略低于MA60(1263.65),中期趋势依然向上 |
| **MACD** | DIF:-0.24, DEA:-11.34, MACD柱:22.18 | 低位金叉形成,空头趋势减弱,短期反弹信号明确 |
| **RSI** | RSI(6):92.76, RSI(12):68.80, RSI(24):48.73 | 短期RSI严重超买(>90),警惕回调风险 |
| **布林带** | 上轨:1252.21, 中轨:1204.07, 下轨:1155.92 | 股价突破上轨,处于强势区间,但短期乖离率偏大 |
| **KDJ** | K:84.30, D:79.20, J:94.49 | 高位金叉,短期上涨动能充足,但J线接近超买区 |
#### 二、综合研判
技术面呈现**强趋势与短期超买并存**的格局:
1. **多头趋势明确**:均线多头排列、MACD低位金叉、KDJ金叉共同构成中期上涨信号
2. **短期回调风险**:RSI超买、股价突破布林上轨提示短期涨幅过大,存在技术性回调需求
#### 三、操作建议
1. **持仓投资者**:
- 继续持有为主,可将MA20(1204.07)作为止损线
- 若股价回落至MA5-MA10区间(1217-1238)可适当加仓
- 短期若冲高至MA60(1263.65)遇阻,可考虑部分止盈
2. **观望投资者**:
- 等待回调至关键支撑位(MA20:1204或布林中轨:1204)再考虑进场
- 若股价直接突破MA60并站稳,可小仓位追涨
⚠️ **风险提示**:技术分析仅供参考,不构成投资建议。市场存在不确定性,需结合自身风险承受能力决策。

2.2 Sector Rotation Analysis Agent

Data Support: Industry/Concept sector daily quotes (90 industry + 374 concept) + Constituent stocks

Core Features:

FeatureDescriptionImplementation
Sector RankingRank by pct_chg, volume change, capital flowAggregate sector daily_index
Rotation TrendSectors with consecutive top N-day gains marked as "hot"Sliding window rank change analysis
Sector ComparisonMulti-sector price curves overlayExtract multiple sector close series
Constituent DistributionAdvance/decline count, limit up/down, median changeLink constituent daily data
Capital FlowVolume change trend, determine inflow/outflowVolume QoQ change analysis
Sector CorrelationConstituent stock overlap between two sectorsSet intersection/union ratio

Example Queries:

"Which industry sectors had the highest gains this week?"
"How has the semiconductor sector performed this month? Is capital flowing in or out?"
"How high is the overlap between AI and robotics concept constituents?"
"Which sectors had limit-down waves today?"

To-Do:

  • tools/sector_ranking.py — Sector ranking tool (Done)
  • tools/sector_rotation.py — Rotation trend identifier (Done)
  • tools/sector_compare.py — Sector comparison tool (Done)
  • tools/sector_detail.py — Sector deep analysis tool (Done)
  • agents/sector_agent.py — Sector analysis agent (Done)

Agent Demo:

$ python agents/sector_agent.py
============================================================
FinAssistant — 板块轮动分析智能体
============================================================
输入板块相关问题开始分析,输入 'quit' 退出
示例:
- 最近一周涨幅最大的行业板块有哪些?
- 半导体板块最近一个月资金是在流入还是流出?
- AI概念和机器人概念的成分股重叠度有多高?
- 今天哪些板块出现了跌停潮?
============================================================
你: 最近一周涨幅最大的行业板块有哪些?
FinAssistant:
[调用工具: get_sector_ranking]
[完成] 结果: === 行业板块涨跌幅排名 (2026-07-17) ===
Top 10:
排名 板块名称 涨跌幅(%) 成交额(亿)
1 通信设备 +5.23 312.45
2 半导体 +4.87 528.91
3 消费电子 +3.65 287.33
...
[调用工具: get_sector_top_gainers]
[完成] 结果: === 连续3天上涨的行业板块 ===
板块名称 连涨天数 累计涨幅(%)
半导体 3 +8.92
通信设备 3 +7.56
...
综合来看,最近一周涨幅最大的行业板块主要集中在科技领域:
1. **通信设备** (+5.23%) — 5G建设持续推进,板块领涨
2. **半导体** (+4.87%) — 国产替代逻辑强化,资金持续流入
3. **消费电子** (+3.65%) — 新品发布预期带动板块走强
其中半导体和通信设备已连续3天上涨,短期动能较强。
⚠️ 风险提示:板块轮动较快,追高需谨慎。以上分析仅供参考,不构成投资建议。

2.3 Cross-Data Correlation Analysis Agent

Data Support: Quotes + Constituents + Financial statements + News (Full data cross-correlation)

Core Features:

FeatureDescriptionImplementation
Stock→Sector MappingQuery which sectors a stock belongs to, recent performanceReverse lookup in constituent data
Sector→Financial AggregationAverage ROE, median PE, total revenue for sector constituentsLink constituent codes to financial statements
News→Quote CorrelationCompanies/sectors mentioned in news, link to recent price trendsNER entity recognition + code matching
Industry ChainInfer upstream/downstream relationships via concept overlapConstituent set similarity clustering
Leader EffectTop N stocks by market cap vs sector overall performanceMarket-cap weighted vs equal-weight index

Example Queries:

"Which concept sectors does BYD belong to? How are they performing?"
"What's the average PE and ROE for the semiconductor sector?"
"Any recent news about solar power? How are related sectors trending?"
"Find the top 5 stocks most correlated with CATL"

To-Do:

  • tools/stock_sector_mapping.py — Stock-sector mapping tool (Done)
  • tools/sector_financial_agg.py — Sector financial aggregation (Done)
  • tools/news_stock_linker.py — News-quote correlation tool (Done)
  • agents/correlation_agent.py — Correlation analysis agent (Done)

2.4 Financial Q&A Agent (RAG)

Data Support: Financial statements (4,593 stocks × multi-period) + Vector database (Milvus)

Core Features:

FeatureDescriptionImplementation
NL Financial Query"Which companies have gross margin > 50%" → SQL/Vector searchVectorize financial fields + structured query
Cross-stock ComparisonHorizontal comparison of financial indicators for same-industry companiesGroup by industry + indicator comparison
Multi-period TrendVertical comparison of same company across periodsTime series analysis + trend detection
Anomaly AlertCash flow plunge, receivables surge, goodwill impairmentThreshold/QoQ change detection
Financial Health ScoreComprehensive solvency, profitability, growth, operational abilityDuPont analysis system + weighted scoring

Example Queries:

"Which banks have positive operating cash flow for the past year?"
"Compare CATL and BYD's debt ratio trends"
"Which companies had gross margin drop > 10% last quarter?"
"Give me a DuPont analysis for Kweichow Moutai"
"Find companies with ROE > 20% for 3 consecutive years"

To-Do:

  • tools/financial_query.py — Financial data query tool (Done)
  • tools/financial_compare.py — Financial comparison tool (Done)
  • tools/financial_anomaly.py — Anomaly detection tool (Done)
  • tools/financial_score.py — Financial health scoring tool (Done)
  • agents/financial_agent.py — Financial Q&A agent (Done)
  • rag/financial_embedding.py — Financial statement vectorization

2.5 Daily Market Report Agent

Data Support: Full data (Quotes + Sectors + News + Financials)

Core Features:

FeatureDescriptionImplementation
Market OverviewMajor index changes, volume, advance/decline statsAggregate all market stock data
Sector Rotation SummaryTop gainers/losers, capital inflow/outflow Top5Sector ranking tool output
Anomaly DetectionLimit up/down, volume breakout, abnormal volatilityFilter conditions
News SummaryMarket-related important news, linked sectorsNews filtering + LLM summary
Watchlist ReportUser's watched stocks daily performance, announcementsPersonalized filtering
Trend AssessmentBased on recent N-day data, market sentiment judgmentMulti-indicator synthesis

Example Queries:

"Generate today's market morning briefing"
"Which stocks hit limit up today? Which sectors do they belong to?"
"How has market sentiment been this week?"
"How are my watchlist stocks performing today?"

To-Do:

  • tools/market_overview.py — Market overview tool (Done)
  • tools/abnormal_detector.py — Anomaly detection tool (Done)
  • tools/market_trend.py — Trend assessment tool (Done)
  • tools/watchlist_report.py — Watchlist report tool (Done)
  • tools/daily_digest.py — Daily report generator (Done, integrates all 6 modules)
  • agents/daily_report_agent.py — Daily report agent (Done)

2.6 Research Report Generation Agent

Data Support: Full data + LLM generation capabilities

Core Features:

FeatureDescriptionImplementation
Stock Deep ReportComprehensive fundamental + technical + valuation + industry positionCall previous tools + LLM long-text generation
Industry ResearchSector trends, constituent financials, industry chain analysisSector tools + Financial tools + LLM
Comparative Report2-3 same-industry companies multi-dimensional comparisonComparison tools + LLM
Event Impact AnalysisNews/policy impact on related sectors and stocksNews correlation + Historical analogy + LLM
Portfolio SuggestionRecommend sector/stock allocation based on risk preferenceOptimization algorithm + LLM

Example Queries:

"Write a deep research report on the semiconductor industry"
"Compare BYD, CATL, and LONGi Green Energy with a comparative analysis"
"Which A-share sectors are most affected by Fed rate hikes?"
"I prefer conservative investing, recommend some sector allocation plans"

To-Do:

  • tools/report_generator.py — Report generation tool (LLM + templates)
  • templates/ — Report templates (stock/industry/comparison/event)
  • agents/report_agent.py — Report generation agent
  • agents/portfolio_agent.py — Portfolio optimization agent

3. Data Assets

3.1 Data Overview

Data TypeVolumeSourceTime Range
SH Stock Daily Quotes2,308 stocksSina Finance (akshare)2026-01-01 ~ Present
SZ Stock Daily Quotes2,895 stocksSina Finance (akshare)2026-01-01 ~ Present
SH Company Info2,308 (Main 1,699 + STAR 609)SSE (akshare)-
SZ Company Info2,895SZSE (akshare)-
SH Financial Statements2,308 stocksSina Finance (akshare)Recent 3 years
SZ Financial Statements2,895 stocksSina Finance (akshare)Recent 3 years
Industry Sector Quotes90 sectorsTonghuashun (akshare)2026-01-01 ~ Present
Concept Sector Quotes374 sectorsTonghuashun (akshare)2026-01-01 ~ Present
Industry Constituents90 sectorsTonghuashun (DrissionPage)-
Concept Constituents374 sectorsTonghuashun (DrissionPage)-
Financial News-Tonghuashun 7x242026-01-01 ~ Present

3.2 MySQL Table Schema

Data is stored in Alibaba Cloud RDS MySQL with two databases: market_data (quotes/financials) and stock_news (news).

market_data.company_info — Company Basic Info

CREATETABLEcompany_info (
id INT AUTO_INCREMENT PRIMARY KEY COMMENT 'Auto-increment ID',
ts_code VARCHAR(20) NOT NULL COMMENT 'Stock code with suffix, e.g., 600000.SH',
symbol VARCHAR(10) NOT NULL COMMENT 'Stock code (numeric only)',
stock_name VARCHAR(50) COMMENT 'Stock short name',
full_name VARCHAR(100) COMMENT 'Company full name',
industry VARCHAR(50) COMMENT 'Industry, e.g., J Finance',
list_date VARCHAR(20) COMMENT 'Listing date, format YYYY-MM-DD',
market VARCHAR(5) COMMENT 'Market, SH=Shanghai SZ=Shenzhen',
updated_at VARCHAR(30) COMMENT 'Data update time',
UNIQUE KEY uk_ts_code (ts_code)
)

market_data.stock_kline — Stock Daily K-line

CREATETABLEstock_kline (
id BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT 'Auto-increment ID',
ts_code VARCHAR(20) NOT NULL COMMENT 'Stock code with suffix',
symbol VARCHAR(10) NOT NULL COMMENT 'Stock code (numeric only)',
trade_date VARCHAR(20) NOT NULL COMMENT 'Trade date, format YYYY-MM-DD',
open DOUBLE COMMENT 'Open price (CNY)',
close DOUBLE COMMENT 'Close price (CNY)',
high DOUBLE COMMENT 'High price (CNY)',
low DOUBLE COMMENT 'Low price (CNY)',
pre_close DOUBLE COMMENT 'Previous close (CNY)',
change_data DOUBLE COMMENT 'Price change (CNY)',
pct_chg DOUBLE COMMENT 'Change percentage (%)',
volume DOUBLE COMMENT 'Volume (shares)',
amount DOUBLE COMMENT 'Turnover (CNY)',
pe DOUBLE COMMENT 'P/E ratio',
pb DOUBLE COMMENT 'P/B ratio',
total_mv DOUBLE COMMENT 'Total market cap (100M CNY)',
total_share DOUBLE COMMENT 'Total shares',
float_share DOUBLE COMMENT 'Float shares',
circ_mv DOUBLE COMMENT 'Circulating market cap (100M CNY)',
ln_pctchg DOUBLE COMMENT 'Log return',
pe_ttm DOUBLE COMMENT 'P/E ratio (TTM)',
pe_static DOUBLE COMMENT 'Static P/E ratio',
pcf DOUBLE COMMENT 'Price-to-Cash-Flow ratio',
UNIQUE KEY uk_code_date (ts_code, trade_date),
KEY idx_trade_date (trade_date),
KEY idx_symbol (symbol)
)

market_data.stock_financial — Financial Statements

CREATETABLEstock_financial (
id BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT 'Auto-increment ID',
ts_code VARCHAR(20) NOT NULL COMMENT 'Stock code with suffix',
symbol VARCHAR(10) NOT NULL COMMENT 'Stock code (numeric only)',
statement_type VARCHAR(20) NOT NULL COMMENT 'Statement type: income/balance/cashflow',
report_date VARCHAR(20) NOT NULL COMMENT 'Report date, e.g., 20260331',
report_data JSON COMMENT 'Complete statement data (JSON)',
UNIQUE KEY uk_code_type_date (ts_code, statement_type, report_date),
KEY idx_symbol (symbol),
KEY idx_report_date (report_date),
KEY idx_statement_type (statement_type)
)

Financial fields vary significantly across industries (banking vs manufacturing), hence JSON storage for complete statement data.

market_data.sector_industry_daily / sector_concept_daily — Sector Daily K-line

CREATETABLEsector_industry_daily (
id BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT 'Auto-increment ID',
sector_name VARCHAR(50) NOT NULL COMMENT 'Sector name',
sector_code VARCHAR(20) NOT NULL COMMENT 'Sector code',
trade_date VARCHAR(20) NOT NULL COMMENT 'Trade date',
open DOUBLE COMMENT 'Open',
high DOUBLE COMMENT 'High',
low DOUBLE COMMENT 'Low',
close DOUBLE COMMENT 'Close',
vol DOUBLE COMMENT 'Volume',
amount DOUBLE COMMENT 'Turnover',
pct_chg DOUBLE COMMENT 'Change (%)',
change_data DOUBLE COMMENT 'Point change',
pct_change DOUBLE COMMENT 'Change (backup)',
turnover_rate DOUBLE COMMENT 'Turnover rate',
UNIQUE KEY uk_code_date (sector_code, trade_date),
KEY idx_trade_date (trade_date),
KEY idx_sector_name (sector_name)
)

market_data.sector_industry_cons / sector_concept_cons — Sector Constituents

CREATETABLEsector_industry_cons (
id BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT 'Auto-increment ID',
sector_name VARCHAR(50) NOT NULL COMMENT 'Sector name',
sector_code VARCHAR(20) NOT NULL COMMENT 'Sector code',
stock_code VARCHAR(10) NOT NULL COMMENT 'Stock code',
stock_name VARCHAR(50) COMMENT 'Stock name',
UNIQUE KEY uk_sector_stock (sector_code, stock_code),
KEY idx_sector_name (sector_name),
KEY idx_stock_code (stock_code)
)

stock_news.news_em — Eastmoney 7x24 News

CREATETABLEnews_em (
id INT AUTO_INCREMENT PRIMARY KEY COMMENT 'Auto-increment ID',
title VARCHAR(500) NOT NULL COMMENT 'News title',
digest TEXT COMMENT 'News digest',
publish_time VARCHAR(30) COMMENT 'Publish time',
url VARCHAR(500) COMMENT 'News URL',
crawl_time VARCHAR(30) COMMENT 'Crawl time',
UNIQUE KEY uk_title_time (title, publish_time)
)

stock_news.news_ths — Tonghuashun Financial News

CREATETABLEnews_ths (
id INT AUTO_INCREMENT PRIMARY KEY COMMENT 'Auto-increment ID',
news_id VARCHAR(20) NOT NULL COMMENT 'News ID',
title VARCHAR(500) NOT NULL COMMENT 'News title',
digest TEXT COMMENT 'News digest',
url VARCHAR(500) COMMENT 'News URL',
tags VARCHAR(500) COMMENT 'Tags (comma separated)',
ctime_str VARCHAR(30) COMMENT 'Publish time',
source VARCHAR(100) COMMENT 'Source',
crawl_time VARCHAR(30) COMMENT 'Crawl time',
UNIQUE KEY uk_news_id (news_id),
KEY idx_ctime (ctime_str)
)

3.3 Data Import Scripts

ScriptTarget TableDescription
import_company_info_to_mysql.pymarket_data.company_infoSH/SZ company info
import_kline_to_mysql.pymarket_data.stock_klineStock daily K-line (560K+ rows)
import_financial_to_mysql.pymarket_data.stock_financialFinancial statements (170K+ rows)
import_sector_to_mysql.pymarket_data.sector_*_dailySector daily K-line
import_sector_cons_to_mysql.pymarket_data.sector_*_consSector constituents
import_news_em_to_mysql.pystock_news.news_emEastmoney news
import_news_ths_to_mysql.pystock_news.news_thsTonghuashun news

3.4 Data Collection Scripts

ScriptPurposeSource
crawl_sh_stock_data.pySH stock quotes + company infoSina Finance / SSE
crawl_sz_stock_data.pySZ stock quotes + company infoSina Finance / SZSE
crawl_financial_reports.pyFinancial statementsSina Finance
crawl_sector_data.pySector daily quotes (Industry + Concept)Tonghuashun (akshare)
crawl_sector_cons.pySector constituentsSina Finance (akshare)
crawl_sector_cons_ths.pySector constituents (backup)Tonghuashun (DrissionPage)
crawl_news_ths.pyFinancial newsTonghuashun 7x24 API
crawl_news_em.pyEastmoney 7x24 news (scheduled)Eastmoney (akshare)

3.5 Known Issues

IssueDescription
Eastmoney API Blockedpush2his.eastmoney.com completely unavailable
Tonghuashun IP BlockedFrequent crawling triggers Nginx 403 block
Inconsistent Sector SourcesQuotes from THS, constituents partially from Sina, names may not match
SH Company Missing IndustrySSE API doesn't provide industry field

4. AgentScope 2.0 Implementation

4.1 Architecture

User Query → FastAPI → Agent (system_prompt + model + toolkit + middlewares)
↓
Toolkit
├── ToolGroup("Stock Analysis") → tools/stock_query.py + skills/stock-analysis/
├── ToolGroup("Sector Analysis") → tools/sector_query.py + skills/sector-rotation/
├── ToolGroup("Financial Q&A") → tools/financial_query.py + skills/financial-qa/
├── ToolGroup("Daily Report") → tools/news_query.py + skills/daily-report/
└── ToolGroup("Research Report") → tools/indicators.py + skills/research-report/

4.2 Directory Structure

FinAssistant/
├── config.py # Global config (paths, model, API Key)
├── main.py # FastAPI service entry
├── main_agent.py # Single agent script (no server, direct chat)
├── core/
│ ├── agent_setup.py # Agent + Toolkit initialization
│ └── middleware.py # Financial scenario middleware
├── tools/ # Tool functions
│ ├── __init__.py
│ ├── stock_query.py # Stock quote/company info query
│ ├── sector_query.py # Sector quote/constituent query
│ ├── financial_query.py # Financial statement query & analysis
│ ├── news_query.py # News query
│ └── indicators.py # Technical/fundamental indicator calculation
├── skills/ # Skill documents (SKILL.md)
│ ├── stock-analysis/SKILL.md
│ ├── sector-rotation/SKILL.md
│ ├── financial-qa/SKILL.md
│ ├── daily-report/SKILL.md
│ └── research-report/SKILL.md
├── data/ # Existing data (don't modify)
└── data_to_mysql_and_milvus/ # Existing crawler scripts (don't modify)

4.3 Implementation Steps

Step 1: config.py

Global configuration for data paths, model config, API keys.

Step 2: tools/ Tool Functions

Each function is async def, returns ToolChunk. Docstring is the tool description — LLM decides when to call based on docstring.

Step 3: skills/SKILL.md Skill Documents

Each skill directory has a SKILL.md with trigger conditions, dependent tools, and execution flow.

Step 4: core/middleware.py Middleware

MiddlewarePurpose
InputValidationMiddlewareFilter non-financial queries
ToolCallAuditMiddlewareLog tool calls to traces/
PerformanceMonitorMiddlewareMonitor inference rounds, latency, tokens
ContextEnrichmentMiddlewareInject current date, trading day context

Step 5: core/agent_setup.py Agent Initialization

Assemble model, tools, toolkit, and agent with middleware.

Step 6: main.py Service Entry

FastAPI service with OpenAI-compatible /v1/chat/completions endpoint.


5. Implemented Tools

tools/stock_fundamental.py — Fundamental Indicator Calculator

Calculates fundamental indicators from MySQL market_data.stock_financial table.

Core Functions:

FunctionDescription
calc_fundamental_indicators(ts_code, report_date=None)Calculate single-period indicators
calc_fundamental_trend(ts_code, periods=4)Calculate recent N-period trend
get_financial_data(ts_code, report_date=None)Get raw statement data
get_report_dates(ts_code, limit=8)Get report date list

Calculated Indicators:

IndicatorFormulaData Source
ROENet Profit / Equity × 100%Income + Balance Sheet
Gross Margin(Revenue - COGS) / Revenue × 100%Income Statement
Net MarginNet Profit / Revenue × 100%Income Statement
Debt RatioTotal Liabilities / Total Assets × 100%Balance Sheet
Cash Flow / Net ProfitOperating Cash Flow / Net ProfitCash Flow + Income
Revenue YoY Growth(Current - Prior Year) /Prior Year
Net Profit YoY Growth(Current - Prior Year) /Prior Year
Revenue QoQ Growth(Current Q - Prior Q) /Prior Q
Net Profit QoQ Growth(Current Q - Prior Q) /Prior Q

Special Handling:

  • Auto bank detection: Via balance sheet fields (loans, deposits)
  • Bank field mapping: Revenue = Net Interest Income + Fee Income; COGS = Interest Expense + Fee Expense
  • YoY calculation: Cumulative values vs same quarter last year (2026Q1 vs 2025Q1)
  • QoQ calculation: Single-quarter values (Q4 = Annual - 9-month cumulative)

Usage:

fromtools.stock_fundamentalimportcalc_fundamental_indicators, calc_fundamental_trend# Single periodresult=calc_fundamental_indicators('600519.SH')
print(result['ROE'], result['毛利率'], result['营收同比增长率'])
# Trend (recent 4 periods)trend=calc_fundamental_trend('600519.SH', periods=4)
fortintrend['trend']:
print(t['report_date'], t['ROE'], t['营收同比增长率'])

tools/stock_valuation.py — Valuation Percentile Analyzer

Calculates PE/PB/PCF percentile in 1-year history from market_data.stock_kline table.

Core Functions:

FunctionDescription
calc_valuation_percentile(ts_code, days=365)Calculate valuation percentile, return structured data
calc_valuation_summary(ts_code, days=365)Generate formatted valuation summary
get_valuation_history(ts_code, days=365)Get N-day valuation history
get_latest_valuation(ts_code)Get latest day valuation data

Valuation Indicators:

IndicatorDescriptionSource
PE_TTMPrice-to-Earnings (Trailing Twelve Months)stock_kline.pe_ttm
PBPrice-to-Bookstock_kline.pb
PCFPrice-to-Cash-Flowstock_kline.pcf

Percentile Rules:

PercentileLevelMeaning
< 20%UndervaluedAt historical low, potentially undervalued
20% - 40%Below AverageBelow historical median
40% - 60%FairAt historical median range
60% - 80%Above AverageAbove historical median
> 80%OvervaluedAt historical high, potentially overvalued

Usage:

fromtools.stock_valuationimportcalc_valuation_percentile, calc_valuation_summary# Get structured dataresult=calc_valuation_percentile('600519.SH')
print(f"PE_TTM: {result['pe_ttm']}, Percentile: {result['pe_ttm_percentile']}%, {result['pe_ttm_level']}")
# Get formatted summaryprint(calc_valuation_summary('600519.SH'))

tools/stock_technical.py — Technical Indicator Calculator

Calculates MA/MACD/RSI/BOLL/KDJ indicators from MySQL market_data.stock_kline table.

Core Functions:

FunctionDescription
calc_technical_indicators(ts_code, days=120)Calculate all technical indicators
calc_technical_summary(ts_code, days=120)Generate formatted summary
get_kline_data(ts_code, days=120)Get K-line data from MySQL

Technical Indicators:

IndicatorFormulaUsage
MA(5/10/20/60)Average of last N closing pricesTrend: Price above MA = bullish; MA crossover = buy/sell signal
MACDDIF = EMA(12) - EMA(26); DEA = EMA(DIF,9); Histogram = (DIF-DEA)×2Golden cross (DIF>DEA) = buy; Dead cross = sell
RSI(6/12/24)RS = Avg Gain / Avg Loss; RSI = 100 - 100/(1+RS)>80 = overbought; <20 = oversold
BOLL(20,2)Upper = MA+2σ; Middle = MA; Lower = MA-2σTouch upper = overbought; Touch lower = oversold
KDJ(9,3,3)RSV, K = 2/3K+1/3RSV, D = 2/3D+1/3K, J = 3K-2DK>80 = overbought; K<20 = oversold; K/D crossover

Signal Interpretation:

SignalMAMACDRSIBOLLKDJ
BullishMA5>MA10>MA20 (Bull alignment)DIF>DEA, Histogram>0RSI<20 (Oversold)Price bounces off lower bandK/D golden cross in oversold zone
BearishMA5<MA10<MA20 (Bear alignment)DIF<DEA, Histogram<0RSI>80 (Overbought)Price falls from upper bandK/D dead cross in overbought zone

Multi-indicator Confirmation:

Buy signals (need 2-3):

  • Price above MA20, MA bullish alignment (MA5>MA10>MA20)
  • MACD golden cross (DIF crosses above DEA)
  • RSI rebounds from oversold (<20 → >20)
  • Price bounces off Bollinger lower band
  • KDJ golden cross in oversold zone

Sell signals (need 2-3):

  • Price below MA20, MA bearish alignment (MA5<MA10<MA20)
  • MACD dead cross (DIF crosses below DEA)
  • RSI enters overbought (>80) then falls
  • Price falls from Bollinger upper band
  • KDJ dead cross in overbought zone

Usage:

fromtools.stock_technicalimportcalc_technical_indicators, calc_technical_summary# Get structured dataresult=calc_technical_indicators('600519.SH')
print(f"Close: {result['close']}, MA5: {result['ma5']}, MACD: {result['macd_signal']}")
# Get formatted summaryprint(calc_technical_summary('600519.SH'))

5.5 Sector Analysis Tools

tools/sector_ranking.py — Sector Ranking Tool

Calculates sector rankings from MySQL sector_industry_daily / sector_concept_daily tables.

Core Functions:

FunctionDescription
get_sector_ranking(sector_type, trade_date, top_n, sort_by)Sector ranking by pct_chg/amount/volume
get_sector_top_gainers(sector_type, days, top_n)Sectors with consecutive N-day gains
get_sector_top_losers(sector_type, days, top_n)Sectors with consecutive N-day losses
get_sector_summary(sector_type, trade_date)Market overview (advance/decline, limit up/down)

Usage:

fromtools.sector_rankingimportget_sector_ranking, get_sector_top_gainers, get_sector_summary# Top 10 industry sectors by pct_chgprint(get_sector_ranking(sector_type='industry', top_n=10))
# Sectors rising for 3 consecutive daysprint(get_sector_top_gainers(sector_type='industry', days=3))
# Industry sector market overviewprint(get_sector_summary(sector_type='industry'))

tools/sector_rotation.py — Rotation Trend Identifier

Analyzes sector momentum and capital rotation direction through short-term vs medium-term performance comparison.

Core Functions:

FunctionDescription
get_sector_momentum(sector_type, short_days, long_days, top_n)Momentum analysis — short vs medium term, momentum score
get_sector_rotation(sector_type, short_days, long_days, top_n)Rotation identification — capital inflow/outflow sectors
get_sector_strength(sector_type, days, top_n)Strength ranking — composite score of gains, up-days, volume
get_hot_cold_sectors(sector_type, days)Hot/cold classification — hot/warm/flat/cold categories

Usage:

fromtools.sector_rotationimportget_sector_momentum, get_sector_rotation, get_hot_cold_sectors# Industry sector momentum (3-day short vs 10-day medium)print(get_sector_momentum(sector_type='industry', short_days=3, long_days=10))
# Sector rotation (capital inflow/outflow)print(get_sector_rotation(sector_type='industry'))
# Hot/cold sector classificationprint(get_hot_cold_sectors(sector_type='industry', days=5))

tools/sector_compare.py — Sector Comparison Tool

Multi-sector price curve overlay comparison with normalization and ASCII trend charts.

Core Functions:

FunctionDescription
compare_sectors(sector_names, sector_type, days)Multi-sector cumulative return comparison (table + ASCII chart)
compare_sector_trend(sector_names, sector_type, days)Trend strength comparison with conclusion

Usage:

fromtools.sector_compareimportcompare_sectors, compare_sector_trend# Compare Baijiu vs Power vs Banks over 20 daysprint(compare_sectors(['白酒', '电力', '银行'], sector_type='industry', days=20))
# Trend strength comparison with conclusionprint(compare_sector_trend(['白酒', '电力', '银行', '证券'], days=20))

tools/sector_detail.py — Sector Deep Analysis Tool

Links constituent stock data to provide internal sector structure analysis.

Core Functions:

FunctionDescription
get_constituent_distribution(sector_name, sector_type, trade_date)Constituent distribution — advance/decline, limit up/down, median change, top/bottom 5
get_sector_money_flow(sector_name, sector_type, days)Capital flow analysis — volume trend, price-volume coordination, inflow/outflow
get_sector_correlation(sector_name1, sector_name2, sector_type)Sector correlation — Jaccard coefficient, overlapping constituents

Usage:

fromtools.sector_detailimportget_constituent_distribution, get_sector_money_flow, get_sector_correlation# Baijiu sector constituent distributionprint(get_constituent_distribution('白酒', sector_type='industry'))
# Power sector capital flow analysisprint(get_sector_money_flow('电力', sector_type='industry', days=10))
# Baijiu vs Beer sector correlationprint(get_sector_correlation('白酒', '啤酒', sector_type='industry'))

tools/news_stock_linker.py — News-Stock Linker

Links news headlines to mentioned companies/sectors and correlates with their recent price trends.

Core Functions:

FunctionDescription
find_news_by_keyword(keyword, limit)Search news by keyword (title/digest fuzzy match)
search_news_with_market(keyword, limit, days_before, days_after)Search news and auto-correlate with matched stocks/sectors price trends

Usage Example:

fromtools.news_stock_linkerimportfind_news_by_keyword, search_news_with_market# Search news by keywordprint(find_news_by_keyword('半导体', limit=5))
# Search news and correlate with market dataprint(search_news_with_market('贵州茅台', limit=3, days_before=3, days_after=3))

5.6 Sector Analysis Agent

agents/sector_agent.py — Sector Analysis Agent

Integrates sector ranking, rotation, comparison, and deep analysis tool groups for sector rotation analysis.

Tool Group Structure:

Tool GroupToolsDescription
sector-rankingget_sector_ranking / get_sector_top_gainers / get_sector_top_losers / get_sector_summarySector ranking
sector-rotationget_sector_momentum / get_sector_rotation / get_sector_strength / get_hot_cold_sectorsRotation analysis
sector-comparecompare_sectors / compare_sector_trendSector comparison
sector-detailget_constituent_distribution / get_sector_money_flow / get_sector_correlationDeep analysis

Run:

python agents/sector_agent.py

5.7 Correlation Analysis Agent

agents/correlation_agent.py — Correlation Analysis Agent

Integrates stock-sector mapping, sector financial aggregation, and news-market correlation tool groups for cross-data analysis.

Tool Group Structure:

Tool GroupToolsDescription
stock-sectorfind_stock_sectorsStock-sector mapping
sector-financeget_sector_financial_agg / get_sector_valuation_statsSector financial aggregation, valuation distribution
news-marketfind_news_by_keyword / search_news_with_marketNews search, news-market correlation

Run:

python agents/correlation_agent.py

5.8 Financial Health Scoring Tool

tools/financial_score.py — Financial Health Scoring Tool

Computes a four-dimension composite financial health score (0-100) with rating (Excellent/Good/Fair/Poor).

Scoring Dimensions:

DimensionWeightIndicators
Profitability30%ROE(40%) + Gross Margin(30%) + Net Margin(30%)
Growth25%Revenue YoY Growth(50%) + Net Profit YoY Growth(50%)
Safety25%Debt Ratio(40%) + Cash Flow/NP(35%) + AR Ratio(25%)
Quality20%Deducted NP Ratio(50%) + Cash Flow Consistency(50%)

Anomaly Deduction: HIGH -5pts, MEDIUM -2pts, max -15pts.

Core Functions:

FunctionDescription
calc_financial_score(ts_code, report_date=None)Calculate single stock financial health score
format_financial_score(ts_code, report_date=None)Generate formatted Markdown output
score_sector(sector_name, sector_type, top_n)Batch score sector constituents

Run:

python tools/financial_score.py --ts_code 600519.SH
python tools/financial_score.py --sector 白酒 --top_n 10
python tools/financial_score.py --ts_codes 600519.SH,300750.SZ,601318.SH

5.9 Financial Q&A Agent

agents/financial_agent.py — Financial Q&A Agent

Integrates fundamental indicators, trend analysis, comparison, anomaly detection, financial scoring, and batch screening tool groups for complex financial Q&A.

Tool Group Structure:

Tool GroupToolsDescription
fundamentalcalc_fundamental_indicators / calc_fundamental_trend / get_financial_data / get_report_datesFinancial indicator calculation
comparecompare_companies / compare_periodsFinancial comparison and trends
score-anomalyformat_financial_score / calc_financial_score / detect_anomaliesScoring and anomaly detection
screeningscreen_cashflow_positive_stocks / screen_margin_decline_stocks / screen_roe_stocksBatch screening
queryquery_financial_dataFinancial data query

Example Queries:

"Which banks have positive operating cash flow for the past year?"
"Compare CATL and BYD's debt ratio trends"
"Which companies had gross margin drop > 10% last quarter?"
"Give me a DuPont analysis for Kweichow Moutai"
"Find companies with ROE > 20% for 3 consecutive years"

Run:

python agents/financial_agent.py

5.10 Daily Market Report Agent

agents/daily_report_agent.py — Daily Market Report Agent

Integrates market overview, trend assessment, sector rotation, anomaly detection, news correlation, and watchlist report tool groups for natural language Q&A on daily market briefings.

Tool Group Structure:

Tool GroupToolsDescription
market-overviewget_market_overview / format_market_overviewMarket overview
market-trendanalyze_market_trend / format_market_trendTrend assessment
sector-analysisget_sector_ranking / get_sector_rotation / get_hot_cold_sectors etc. (8 tools)Sector analysis
abnormal-detectiondetect_abnormal / format_abnormalAnomaly detection
newsfind_news_by_keyword / search_news_with_marketNews search
watchlistget_watchlist_report / format_watchlist_reportWatchlist report
daily-digestgenerate_daily_digestOne-click daily report

Example Queries:

"Generate today's market morning briefing"
"Which stocks hit limit up today? Which sectors do they belong to?"
"How has market sentiment been this week?"
"Which sectors are seeing capital inflow?"
"What important news is there today?"
"How are my watchlist stocks performing?"

Run:

python agents/daily_report_agent.py

5.11 Daily Market Report Tools

tools/market_overview.py — Market Overview Tool

Aggregates all market stock data to compute daily market overview (advance/decline counts, limit up/down, turnover, etc.).

Core Functions:

FunctionDescription
get_market_overview(trade_date=None)Get market overview as structured data
format_market_overview(trade_date=None)Generate formatted Markdown output

Output Metrics:

MetricDescription
Advance/DeclineUp/down/flat counts and percentages
Limit Up/DownMain board >=9.9%, ChiNext/STAR >=19.9%
Total TurnoverMarket-wide turnover (100M CNY)
Avg/Median ChangeOverall market change level
Market SentimentStrong rally/Bullish/Neutral/Bearish/Weak decline

Run:

python tools/market_overview.py
python tools/market_overview.py --trade_date 20260801

tools/abnormal_detector.py — Anomaly Detection Tool

Detects daily market anomalies: limit up/down stocks, volume breakouts, abnormal price movements, sector anomalies.

Core Functions:

FunctionDescription
detect_abnormal(trade_date=None)Detect anomalies, return structured data
format_abnormal(trade_date=None)Generate formatted Markdown output

Detection Types:

TypeCondition
Limit Up/DownMain board >=9.9%, ChiNext/STAR >=19.9%
Volume BreakoutVolume ratio >3 AND gain >3% (ratio = current vol / 20-day avg vol)
Price Surge
Sector Anomaly

Run:

python tools/abnormal_detector.py
python tools/abnormal_detector.py --trade_date 20260801

tools/market_trend.py — Trend Assessment Tool

Multi-dimensional market sentiment analysis based on recent N-day data.

Core Functions:

FunctionDescription
analyze_market_trend(days=5)Analyze market trend, return structured data
format_market_trend(days=5)Generate formatted Markdown output

Scoring Dimensions (20 pts each, 100 total):

DimensionSourceLogic
Advance/Decline Ratiostock_kline 5-dayAverage advancing stock ratio
Limit Up/Down Ratiostock_kline latestLimit up / (up + down + 1)
Turnover Trendstock_kline 5-dayRecent 5d vs prior 5d, volume expansion/contraction
Sector Rotationsector_industry_dailyAdvancing sector ratio
Consecutive Trendstock_kline 5-dayConsecutive up/down days

Sentiment Mapping: >=75 Optimistic / >=60 Mildly Bullish / >=40 Neutral / >=25 Mildly Bearish / <25 Pessimistic

Run:

python tools/market_trend.py
python tools/market_trend.py --days 10

tools/watchlist_report.py — Watchlist Report Tool

Personalized daily report for user-watched stocks: daily performance, 5-day change, related news.

Core Functions:

FunctionDescription
get_watchlist_report(ts_codes, trade_date=None)Get watchlist report as structured data
format_watchlist_report(ts_codes, trade_date=None)Generate formatted Markdown output

Report Content:

ModuleDescription
Daily PerformanceClose price, change %, turnover
5-Day ChangeCumulative change over 5 trading days
Related NewsSearch news by stock name (max 3 per stock)

Watchlist Config: Edit tools/watchlist_config.json to set default watchlist.

Run:

python tools/watchlist_report.py --ts_codes 600519.SH,300750.SZ
python tools/watchlist_report.py # Use default from watchlist_config.json

tools/daily_digest.py — Daily Report Generator (Enhanced)

Generates complete daily market briefing by integrating all 6 modules.

Core Functions:

FunctionDescription
generate_daily_digest(trade_date=None, watchlist=None)Generate complete daily report (Markdown)

Report Structure:

SectionModuleSource
1Market Overviewmarket_overview.py
2Trend Assessmentmarket_trend.py
3Sector Rotationsector_ranking.py + sector_rotation.py
4Market Anomaliesabnormal_detector.py
5Important Newsnews_stock_linker.py
6Watchlist Report (optional)watchlist_report.py

Run:

python tools/daily_digest.py
python tools/daily_digest.py --trade_date 20260801
python tools/daily_digest.py --watchlist 600519.SH,300750.SZ

5.12 Tool Function Mapping

Existing langgraph_getdata/New tools/Description
query_market_data_day_k.pystock_query.pyStock K-line query
query_industry_index_market.pysector_query.pySector quote query
query_industry_component_list.pysector_query.pySector constituents
query_concept_dc_day.pysector_query.pyConcept sector quotes
query_concept_dc_stock.pysector_query.pyConcept sector constituents
query_fin_account.pyfinancial_query.pyFinancial statement query (Done)
(None)news_query.pyNews query (New)
(None)stock_fundamental.pyFundamental indicators (Done)
(None)stock_valuation.pyValuation percentile (Done)
(None)stock_technical.pyTechnical indicators (Done)
(None)stock_sector_mapping.pyStock-sector mapping (Done)
(None)sector_financial_agg.pySector financial aggregation (Done)
(None)news_stock_linker.pyNews-stock correlation (Done)
(None)financial_score.pyFinancial health scoring (Done)
(None)sector_data.pySector data utilities (Done)
(None)market_overview.pyMarket overview tool (Done)
(None)abnormal_detector.pyAnomaly detection tool (Done)
(None)market_trend.pyTrend assessment tool (Done)
(None)watchlist_report.pyWatchlist report tool (Done)
(None)daily_digest.pyDaily report generator (Done)

5.13 Dependencies

pip install agentscope>=2.0.3 fastapi uvicorn

About

Built on professional finance knowledge, it provides stock diagnostics, sector index analysis, investment Q&A and news insights to help investors capture market opportunities efficiently.

Resources

Stars

5 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

FinAssistant Logo

FinAssistant — AI-Powered Financial Analysis

RAG Retrieval & Agent System for China A-Share Market

BackgroundFeaturesData AssetsImplementationTools

中文 | English


1. Background

The China A-share market has diverse data dimensions and massive information volumes. Retail investors and small-to-medium institutions struggle to efficiently integrate stock quotes, sector rotation, financial statements, and market news for comprehensive analysis. This project aims to build a financial RAG retrieval and agent system based on collected A-share data assets, enabling users to perform professional financial analysis through natural language conversations.

Core Objectives

  • Lower Analysis Barriers: Replace manual data queries, indicator calculations, and report writing with natural language
  • Multi-dimensional Data Correlation: Connect stocks, sectors, financials, and news for a panoramic view
  • Agent Collaboration: Multiple specialized agents working together, covering the full workflow from data queries to research reports

Tech Stack

LayerTechnology
Agent FrameworkAgentScope 2.0 (Multi-Agent Orchestration)
Data StorageMySQL (Structured Query) + Milvus (Vector Retrieval)
Data CollectionPython + akshare + DrissionPage
LLMQwen / GPT / Claude
Embeddingtext-embedding-v3 / BGE
FrontendStreamlit / Gradio

2. Feature Modules

Six intelligent agent modules planned based on existing data assets:


2.1 Stock Analysis Agent

Data Support: Daily stock quotes + Company info + Financial statements

Core Features:

FeatureDescriptionImplementation
Fundamental ScoreAuto-score (0-100) based on ROE, gross margin, debt ratio, cash flowExtract key fields from 3 statements, weighted calculation
Valuation PercentilePE/PB/PCF percentile in 1-year history, determine over/undervaluedCalculate percentile on daily PE/PB series
Technical IndicatorsMA(5/10/20/60), MACD, RSI, Bollinger Bands, KDJReal-time calculation based on OHLCV data
Trading SignalsGolden/Dead cross, MA breakout, RSI overbought/oversoldTechnical indicator crossover detection
Stock Profile ReportComprehensive fundamental + technical + valuation + sector reportLLM aggregates analysis results into text

Example Queries:

"How is Pudong Bank's cash flow situation this quarter?"
"What is Ping An Bank's current valuation percentile?"
"Analyze Kweichow Moutai's technical trend and give trading advice"
"Generate a stock profile report for CATL"

To-Do:

  • tools/stock_fundamental.py — Fundamental indicator calculator (Done)
  • tools/stock_valuation.py — Valuation percentile analyzer (Done)
  • tools/stock_technical.py — Technical indicator calculator (Done)
  • tools/stock_analysis.py — Comprehensive stock analysis report (Done)
  • agents/stock_agent.py — Stock analysis agent (Done)

Agent Demo:

$ python agents/stock_agent.py
============================================================
FinAssistant — 金融智能体
============================================================
输入股票代码或问题开始分析,输入 'quit' 退出
============================================================
你: 帮我分析贵州茅台的技术面走势,给出操作建议
FinAssistant:
[调用工具: reset_tools]
[完成] 结果: The currently activated tool group(s): stock-technical.
[调用工具: calc_technical_summary]
[完成] 结果: === 600519.SH 技术指标分析 (2026-07-17) ===
收盘价: 1253.0
【移动平均线 MA】
MA5: 1237.78
MA10: 1217.11
MA20: 1204.07
MA60: 1263.65
均线趋势: 多头排列
【MACD】
DIF: -0.2443
DEA: -11.3353
MACD柱: 22.182
信号: 金叉
【RSI】
RSI(6): 92.76
RSI(12): 68.8
RSI(24): 48.73
RSI(6)信号: 超买
【布林带 BOLL】
上轨: 1252.21
中轨: 1204.07
下轨: 1155.92
【KDJ】
K: 84.3
D: 79.2
J: 94.49
信号: 金叉
【综合研判】
当前信号: MA多头排列, MACD金叉, RSI超买, KDJ金叉
### 贵州茅台(600519.SH)技术面分析与操作建议
#### 一、核心技术指标摘要(近120天)
| 指标类型 | 关键数据 | 信号解读 |
|---------|---------|---------|
| **均线系统** | MA5:1237.78, MA10:1217.11, MA20:1204.07, MA60:1263.65 | 短期均线多头排列,股价略低于MA60(1263.65),中期趋势依然向上 |
| **MACD** | DIF:-0.24, DEA:-11.34, MACD柱:22.18 | 低位金叉形成,空头趋势减弱,短期反弹信号明确 |
| **RSI** | RSI(6):92.76, RSI(12):68.80, RSI(24):48.73 | 短期RSI严重超买(>90),警惕回调风险 |
| **布林带** | 上轨:1252.21, 中轨:1204.07, 下轨:1155.92 | 股价突破上轨,处于强势区间,但短期乖离率偏大 |
| **KDJ** | K:84.30, D:79.20, J:94.49 | 高位金叉,短期上涨动能充足,但J线接近超买区 |
#### 二、综合研判
技术面呈现**强趋势与短期超买并存**的格局:
1. **多头趋势明确**:均线多头排列、MACD低位金叉、KDJ金叉共同构成中期上涨信号
2. **短期回调风险**:RSI超买、股价突破布林上轨提示短期涨幅过大,存在技术性回调需求
#### 三、操作建议
1. **持仓投资者**:
- 继续持有为主,可将MA20(1204.07)作为止损线
- 若股价回落至MA5-MA10区间(1217-1238)可适当加仓
- 短期若冲高至MA60(1263.65)遇阻,可考虑部分止盈
2. **观望投资者**:
- 等待回调至关键支撑位(MA20:1204或布林中轨:1204)再考虑进场
- 若股价直接突破MA60并站稳,可小仓位追涨
⚠️ **风险提示**:技术分析仅供参考,不构成投资建议。市场存在不确定性,需结合自身风险承受能力决策。

2.2 Sector Rotation Analysis Agent

Data Support: Industry/Concept sector daily quotes (90 industry + 374 concept) + Constituent stocks

Core Features:

FeatureDescriptionImplementation
Sector RankingRank by pct_chg, volume change, capital flowAggregate sector daily_index
Rotation TrendSectors with consecutive top N-day gains marked as "hot"Sliding window rank change analysis
Sector ComparisonMulti-sector price curves overlayExtract multiple sector close series
Constituent DistributionAdvance/decline count, limit up/down, median changeLink constituent daily data
Capital FlowVolume change trend, determine inflow/outflowVolume QoQ change analysis
Sector CorrelationConstituent stock overlap between two sectorsSet intersection/union ratio

Example Queries:

"Which industry sectors had the highest gains this week?"
"How has the semiconductor sector performed this month? Is capital flowing in or out?"
"How high is the overlap between AI and robotics concept constituents?"
"Which sectors had limit-down waves today?"

To-Do:

  • tools/sector_ranking.py — Sector ranking tool (Done)
  • tools/sector_rotation.py — Rotation trend identifier (Done)
  • tools/sector_compare.py — Sector comparison tool (Done)
  • tools/sector_detail.py — Sector deep analysis tool (Done)
  • agents/sector_agent.py — Sector analysis agent (Done)

Agent Demo:

$ python agents/sector_agent.py
============================================================
FinAssistant — 板块轮动分析智能体
============================================================
输入板块相关问题开始分析,输入 'quit' 退出
示例:
- 最近一周涨幅最大的行业板块有哪些?
- 半导体板块最近一个月资金是在流入还是流出?
- AI概念和机器人概念的成分股重叠度有多高?
- 今天哪些板块出现了跌停潮?
============================================================
你: 最近一周涨幅最大的行业板块有哪些?
FinAssistant:
[调用工具: get_sector_ranking]
[完成] 结果: === 行业板块涨跌幅排名 (2026-07-17) ===
Top 10:
排名 板块名称 涨跌幅(%) 成交额(亿)
1 通信设备 +5.23 312.45
2 半导体 +4.87 528.91
3 消费电子 +3.65 287.33
...
[调用工具: get_sector_top_gainers]
[完成] 结果: === 连续3天上涨的行业板块 ===
板块名称 连涨天数 累计涨幅(%)
半导体 3 +8.92
通信设备 3 +7.56
...
综合来看,最近一周涨幅最大的行业板块主要集中在科技领域:
1. **通信设备** (+5.23%) — 5G建设持续推进,板块领涨
2. **半导体** (+4.87%) — 国产替代逻辑强化,资金持续流入
3. **消费电子** (+3.65%) — 新品发布预期带动板块走强
其中半导体和通信设备已连续3天上涨,短期动能较强。
⚠️ 风险提示:板块轮动较快,追高需谨慎。以上分析仅供参考,不构成投资建议。

2.3 Cross-Data Correlation Analysis Agent

Data Support: Quotes + Constituents + Financial statements + News (Full data cross-correlation)

Core Features:

FeatureDescriptionImplementation
Stock→Sector MappingQuery which sectors a stock belongs to, recent performanceReverse lookup in constituent data
Sector→Financial AggregationAverage ROE, median PE, total revenue for sector constituentsLink constituent codes to financial statements
News→Quote CorrelationCompanies/sectors mentioned in news, link to recent price trendsNER entity recognition + code matching
Industry ChainInfer upstream/downstream relationships via concept overlapConstituent set similarity clustering
Leader EffectTop N stocks by market cap vs sector overall performanceMarket-cap weighted vs equal-weight index

Example Queries:

"Which concept sectors does BYD belong to? How are they performing?"
"What's the average PE and ROE for the semiconductor sector?"
"Any recent news about solar power? How are related sectors trending?"
"Find the top 5 stocks most correlated with CATL"

To-Do:

  • tools/stock_sector_mapping.py — Stock-sector mapping tool (Done)
  • tools/sector_financial_agg.py — Sector financial aggregation (Done)
  • tools/news_stock_linker.py — News-quote correlation tool (Done)
  • agents/correlation_agent.py — Correlation analysis agent (Done)

2.4 Financial Q&A Agent (RAG)

Data Support: Financial statements (4,593 stocks × multi-period) + Vector database (Milvus)

Core Features:

FeatureDescriptionImplementation
NL Financial Query"Which companies have gross margin > 50%" → SQL/Vector searchVectorize financial fields + structured query
Cross-stock ComparisonHorizontal comparison of financial indicators for same-industry companiesGroup by industry + indicator comparison
Multi-period TrendVertical comparison of same company across periodsTime series analysis + trend detection
Anomaly AlertCash flow plunge, receivables surge, goodwill impairmentThreshold/QoQ change detection
Financial Health ScoreComprehensive solvency, profitability, growth, operational abilityDuPont analysis system + weighted scoring

Example Queries:

"Which banks have positive operating cash flow for the past year?"
"Compare CATL and BYD's debt ratio trends"
"Which companies had gross margin drop > 10% last quarter?"
"Give me a DuPont analysis for Kweichow Moutai"
"Find companies with ROE > 20% for 3 consecutive years"

To-Do:

  • tools/financial_query.py — Financial data query tool (Done)
  • tools/financial_compare.py — Financial comparison tool (Done)
  • tools/financial_anomaly.py — Anomaly detection tool (Done)
  • tools/financial_score.py — Financial health scoring tool (Done)
  • agents/financial_agent.py — Financial Q&A agent (Done)
  • rag/financial_embedding.py — Financial statement vectorization

2.5 Daily Market Report Agent

Data Support: Full data (Quotes + Sectors + News + Financials)

Core Features:

FeatureDescriptionImplementation
Market OverviewMajor index changes, volume, advance/decline statsAggregate all market stock data
Sector Rotation SummaryTop gainers/losers, capital inflow/outflow Top5Sector ranking tool output
Anomaly DetectionLimit up/down, volume breakout, abnormal volatilityFilter conditions
News SummaryMarket-related important news, linked sectorsNews filtering + LLM summary
Watchlist ReportUser's watched stocks daily performance, announcementsPersonalized filtering
Trend AssessmentBased on recent N-day data, market sentiment judgmentMulti-indicator synthesis

Example Queries:

"Generate today's market morning briefing"
"Which stocks hit limit up today? Which sectors do they belong to?"
"How has market sentiment been this week?"
"How are my watchlist stocks performing today?"

To-Do:

  • tools/market_overview.py — Market overview tool (Done)
  • tools/abnormal_detector.py — Anomaly detection tool (Done)
  • tools/market_trend.py — Trend assessment tool (Done)
  • tools/watchlist_report.py — Watchlist report tool (Done)
  • tools/daily_digest.py — Daily report generator (Done, integrates all 6 modules)
  • agents/daily_report_agent.py — Daily report agent (Done)

2.6 Research Report Generation Agent

Data Support: Full data + LLM generation capabilities

Core Features:

FeatureDescriptionImplementation
Stock Deep ReportComprehensive fundamental + technical + valuation + industry positionCall previous tools + LLM long-text generation
Industry ResearchSector trends, constituent financials, industry chain analysisSector tools + Financial tools + LLM
Comparative Report2-3 same-industry companies multi-dimensional comparisonComparison tools + LLM
Event Impact AnalysisNews/policy impact on related sectors and stocksNews correlation + Historical analogy + LLM
Portfolio SuggestionRecommend sector/stock allocation based on risk preferenceOptimization algorithm + LLM

Example Queries:

"Write a deep research report on the semiconductor industry"
"Compare BYD, CATL, and LONGi Green Energy with a comparative analysis"
"Which A-share sectors are most affected by Fed rate hikes?"
"I prefer conservative investing, recommend some sector allocation plans"

To-Do:

  • tools/report_generator.py — Report generation tool (LLM + templates)
  • templates/ — Report templates (stock/industry/comparison/event)
  • agents/report_agent.py — Report generation agent
  • agents/portfolio_agent.py — Portfolio optimization agent

3. Data Assets

3.1 Data Overview

Data TypeVolumeSourceTime Range
SH Stock Daily Quotes2,308 stocksSina Finance (akshare)2026-01-01 ~ Present
SZ Stock Daily Quotes2,895 stocksSina Finance (akshare)2026-01-01 ~ Present
SH Company Info2,308 (Main 1,699 + STAR 609)SSE (akshare)-
SZ Company Info2,895SZSE (akshare)-
SH Financial Statements2,308 stocksSina Finance (akshare)Recent 3 years
SZ Financial Statements2,895 stocksSina Finance (akshare)Recent 3 years
Industry Sector Quotes90 sectorsTonghuashun (akshare)2026-01-01 ~ Present
Concept Sector Quotes374 sectorsTonghuashun (akshare)2026-01-01 ~ Present
Industry Constituents90 sectorsTonghuashun (DrissionPage)-
Concept Constituents374 sectorsTonghuashun (DrissionPage)-
Financial News-Tonghuashun 7x242026-01-01 ~ Present

3.2 MySQL Table Schema

Data is stored in Alibaba Cloud RDS MySQL with two databases: market_data (quotes/financials) and stock_news (news).

market_data.company_info — Company Basic Info

CREATETABLEcompany_info (
id INT AUTO_INCREMENT PRIMARY KEY COMMENT 'Auto-increment ID',
ts_code VARCHAR(20) NOT NULL COMMENT 'Stock code with suffix, e.g., 600000.SH',
symbol VARCHAR(10) NOT NULL COMMENT 'Stock code (numeric only)',
stock_name VARCHAR(50) COMMENT 'Stock short name',
full_name VARCHAR(100) COMMENT 'Company full name',
industry VARCHAR(50) COMMENT 'Industry, e.g., J Finance',
list_date VARCHAR(20) COMMENT 'Listing date, format YYYY-MM-DD',
market VARCHAR(5) COMMENT 'Market, SH=Shanghai SZ=Shenzhen',
updated_at VARCHAR(30) COMMENT 'Data update time',
UNIQUE KEY uk_ts_code (ts_code)
)

market_data.stock_kline — Stock Daily K-line

CREATETABLEstock_kline (
id BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT 'Auto-increment ID',
ts_code VARCHAR(20) NOT NULL COMMENT 'Stock code with suffix',
symbol VARCHAR(10) NOT NULL COMMENT 'Stock code (numeric only)',
trade_date VARCHAR(20) NOT NULL COMMENT 'Trade date, format YYYY-MM-DD',
open DOUBLE COMMENT 'Open price (CNY)',
close DOUBLE COMMENT 'Close price (CNY)',
high DOUBLE COMMENT 'High price (CNY)',
low DOUBLE COMMENT 'Low price (CNY)',
pre_close DOUBLE COMMENT 'Previous close (CNY)',
change_data DOUBLE COMMENT 'Price change (CNY)',
pct_chg DOUBLE COMMENT 'Change percentage (%)',
volume DOUBLE COMMENT 'Volume (shares)',
amount DOUBLE COMMENT 'Turnover (CNY)',
pe DOUBLE COMMENT 'P/E ratio',
pb DOUBLE COMMENT 'P/B ratio',
total_mv DOUBLE COMMENT 'Total market cap (100M CNY)',
total_share DOUBLE COMMENT 'Total shares',
float_share DOUBLE COMMENT 'Float shares',
circ_mv DOUBLE COMMENT 'Circulating market cap (100M CNY)',
ln_pctchg DOUBLE COMMENT 'Log return',
pe_ttm DOUBLE COMMENT 'P/E ratio (TTM)',
pe_static DOUBLE COMMENT 'Static P/E ratio',
pcf DOUBLE COMMENT 'Price-to-Cash-Flow ratio',
UNIQUE KEY uk_code_date (ts_code, trade_date),
KEY idx_trade_date (trade_date),
KEY idx_symbol (symbol)
)

market_data.stock_financial — Financial Statements

CREATETABLEstock_financial (
id BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT 'Auto-increment ID',
ts_code VARCHAR(20) NOT NULL COMMENT 'Stock code with suffix',
symbol VARCHAR(10) NOT NULL COMMENT 'Stock code (numeric only)',
statement_type VARCHAR(20) NOT NULL COMMENT 'Statement type: income/balance/cashflow',
report_date VARCHAR(20) NOT NULL COMMENT 'Report date, e.g., 20260331',
report_data JSON COMMENT 'Complete statement data (JSON)',
UNIQUE KEY uk_code_type_date (ts_code, statement_type, report_date),
KEY idx_symbol (symbol),
KEY idx_report_date (report_date),
KEY idx_statement_type (statement_type)
)

Financial fields vary significantly across industries (banking vs manufacturing), hence JSON storage for complete statement data.

market_data.sector_industry_daily / sector_concept_daily — Sector Daily K-line

CREATETABLEsector_industry_daily (
id BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT 'Auto-increment ID',
sector_name VARCHAR(50) NOT NULL COMMENT 'Sector name',
sector_code VARCHAR(20) NOT NULL COMMENT 'Sector code',
trade_date VARCHAR(20) NOT NULL COMMENT 'Trade date',
open DOUBLE COMMENT 'Open',
high DOUBLE COMMENT 'High',
low DOUBLE COMMENT 'Low',
close DOUBLE COMMENT 'Close',
vol DOUBLE COMMENT 'Volume',
amount DOUBLE COMMENT 'Turnover',
pct_chg DOUBLE COMMENT 'Change (%)',
change_data DOUBLE COMMENT 'Point change',
pct_change DOUBLE COMMENT 'Change (backup)',
turnover_rate DOUBLE COMMENT 'Turnover rate',
UNIQUE KEY uk_code_date (sector_code, trade_date),
KEY idx_trade_date (trade_date),
KEY idx_sector_name (sector_name)
)

market_data.sector_industry_cons / sector_concept_cons — Sector Constituents

CREATETABLEsector_industry_cons (
id BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT 'Auto-increment ID',
sector_name VARCHAR(50) NOT NULL COMMENT 'Sector name',
sector_code VARCHAR(20) NOT NULL COMMENT 'Sector code',
stock_code VARCHAR(10) NOT NULL COMMENT 'Stock code',
stock_name VARCHAR(50) COMMENT 'Stock name',
UNIQUE KEY uk_sector_stock (sector_code, stock_code),
KEY idx_sector_name (sector_name),
KEY idx_stock_code (stock_code)
)

stock_news.news_em — Eastmoney 7x24 News

CREATETABLEnews_em (
id INT AUTO_INCREMENT PRIMARY KEY COMMENT 'Auto-increment ID',
title VARCHAR(500) NOT NULL COMMENT 'News title',
digest TEXT COMMENT 'News digest',
publish_time VARCHAR(30) COMMENT 'Publish time',
url VARCHAR(500) COMMENT 'News URL',
crawl_time VARCHAR(30) COMMENT 'Crawl time',
UNIQUE KEY uk_title_time (title, publish_time)
)

stock_news.news_ths — Tonghuashun Financial News

CREATETABLEnews_ths (
id INT AUTO_INCREMENT PRIMARY KEY COMMENT 'Auto-increment ID',
news_id VARCHAR(20) NOT NULL COMMENT 'News ID',
title VARCHAR(500) NOT NULL COMMENT 'News title',
digest TEXT COMMENT 'News digest',
url VARCHAR(500) COMMENT 'News URL',
tags VARCHAR(500) COMMENT 'Tags (comma separated)',
ctime_str VARCHAR(30) COMMENT 'Publish time',
source VARCHAR(100) COMMENT 'Source',
crawl_time VARCHAR(30) COMMENT 'Crawl time',
UNIQUE KEY uk_news_id (news_id),
KEY idx_ctime (ctime_str)
)

3.3 Data Import Scripts

ScriptTarget TableDescription
import_company_info_to_mysql.pymarket_data.company_infoSH/SZ company info
import_kline_to_mysql.pymarket_data.stock_klineStock daily K-line (560K+ rows)
import_financial_to_mysql.pymarket_data.stock_financialFinancial statements (170K+ rows)
import_sector_to_mysql.pymarket_data.sector_*_dailySector daily K-line
import_sector_cons_to_mysql.pymarket_data.sector_*_consSector constituents
import_news_em_to_mysql.pystock_news.news_emEastmoney news
import_news_ths_to_mysql.pystock_news.news_thsTonghuashun news

3.4 Data Collection Scripts

ScriptPurposeSource
crawl_sh_stock_data.pySH stock quotes + company infoSina Finance / SSE
crawl_sz_stock_data.pySZ stock quotes + company infoSina Finance / SZSE
crawl_financial_reports.pyFinancial statementsSina Finance
crawl_sector_data.pySector daily quotes (Industry + Concept)Tonghuashun (akshare)
crawl_sector_cons.pySector constituentsSina Finance (akshare)
crawl_sector_cons_ths.pySector constituents (backup)Tonghuashun (DrissionPage)
crawl_news_ths.pyFinancial newsTonghuashun 7x24 API
crawl_news_em.pyEastmoney 7x24 news (scheduled)Eastmoney (akshare)

3.5 Known Issues

IssueDescription
Eastmoney API Blockedpush2his.eastmoney.com completely unavailable
Tonghuashun IP BlockedFrequent crawling triggers Nginx 403 block
Inconsistent Sector SourcesQuotes from THS, constituents partially from Sina, names may not match
SH Company Missing IndustrySSE API doesn't provide industry field

4. AgentScope 2.0 Implementation

4.1 Architecture

User Query → FastAPI → Agent (system_prompt + model + toolkit + middlewares)
↓
Toolkit
├── ToolGroup("Stock Analysis") → tools/stock_query.py + skills/stock-analysis/
├── ToolGroup("Sector Analysis") → tools/sector_query.py + skills/sector-rotation/
├── ToolGroup("Financial Q&A") → tools/financial_query.py + skills/financial-qa/
├── ToolGroup("Daily Report") → tools/news_query.py + skills/daily-report/
└── ToolGroup("Research Report") → tools/indicators.py + skills/research-report/

4.2 Directory Structure

FinAssistant/
├── config.py # Global config (paths, model, API Key)
├── main.py # FastAPI service entry
├── main_agent.py # Single agent script (no server, direct chat)
├── core/
│ ├── agent_setup.py # Agent + Toolkit initialization
│ └── middleware.py # Financial scenario middleware
├── tools/ # Tool functions
│ ├── __init__.py
│ ├── stock_query.py # Stock quote/company info query
│ ├── sector_query.py # Sector quote/constituent query
│ ├── financial_query.py # Financial statement query & analysis
│ ├── news_query.py # News query
│ └── indicators.py # Technical/fundamental indicator calculation
├── skills/ # Skill documents (SKILL.md)
│ ├── stock-analysis/SKILL.md
│ ├── sector-rotation/SKILL.md
│ ├── financial-qa/SKILL.md
│ ├── daily-report/SKILL.md
│ └── research-report/SKILL.md
├── data/ # Existing data (don't modify)
└── data_to_mysql_and_milvus/ # Existing crawler scripts (don't modify)

4.3 Implementation Steps

Step 1: config.py

Global configuration for data paths, model config, API keys.

Step 2: tools/ Tool Functions

Each function is async def, returns ToolChunk. Docstring is the tool description — LLM decides when to call based on docstring.

Step 3: skills/SKILL.md Skill Documents

Each skill directory has a SKILL.md with trigger conditions, dependent tools, and execution flow.

Step 4: core/middleware.py Middleware

MiddlewarePurpose
InputValidationMiddlewareFilter non-financial queries
ToolCallAuditMiddlewareLog tool calls to traces/
PerformanceMonitorMiddlewareMonitor inference rounds, latency, tokens
ContextEnrichmentMiddlewareInject current date, trading day context

Step 5: core/agent_setup.py Agent Initialization

Assemble model, tools, toolkit, and agent with middleware.

Step 6: main.py Service Entry

FastAPI service with OpenAI-compatible /v1/chat/completions endpoint.


5. Implemented Tools

tools/stock_fundamental.py — Fundamental Indicator Calculator

Calculates fundamental indicators from MySQL market_data.stock_financial table.

Core Functions:

FunctionDescription
calc_fundamental_indicators(ts_code, report_date=None)Calculate single-period indicators
calc_fundamental_trend(ts_code, periods=4)Calculate recent N-period trend
get_financial_data(ts_code, report_date=None)Get raw statement data
get_report_dates(ts_code, limit=8)Get report date list

Calculated Indicators:

IndicatorFormulaData Source
ROENet Profit / Equity × 100%Income + Balance Sheet
Gross Margin(Revenue - COGS) / Revenue × 100%Income Statement
Net MarginNet Profit / Revenue × 100%Income Statement
Debt RatioTotal Liabilities / Total Assets × 100%Balance Sheet
Cash Flow / Net ProfitOperating Cash Flow / Net ProfitCash Flow + Income
Revenue YoY Growth(Current - Prior Year) /Prior Year
Net Profit YoY Growth(Current - Prior Year) /Prior Year
Revenue QoQ Growth(Current Q - Prior Q) /Prior Q
Net Profit QoQ Growth(Current Q - Prior Q) /Prior Q

Special Handling:

  • Auto bank detection: Via balance sheet fields (loans, deposits)
  • Bank field mapping: Revenue = Net Interest Income + Fee Income; COGS = Interest Expense + Fee Expense
  • YoY calculation: Cumulative values vs same quarter last year (2026Q1 vs 2025Q1)
  • QoQ calculation: Single-quarter values (Q4 = Annual - 9-month cumulative)

Usage:

fromtools.stock_fundamentalimportcalc_fundamental_indicators, calc_fundamental_trend# Single periodresult=calc_fundamental_indicators('600519.SH')
print(result['ROE'], result['毛利率'], result['营收同比增长率'])
# Trend (recent 4 periods)trend=calc_fundamental_trend('600519.SH', periods=4)
fortintrend['trend']:
print(t['report_date'], t['ROE'], t['营收同比增长率'])

tools/stock_valuation.py — Valuation Percentile Analyzer

Calculates PE/PB/PCF percentile in 1-year history from market_data.stock_kline table.

Core Functions:

FunctionDescription
calc_valuation_percentile(ts_code, days=365)Calculate valuation percentile, return structured data
calc_valuation_summary(ts_code, days=365)Generate formatted valuation summary
get_valuation_history(ts_code, days=365)Get N-day valuation history
get_latest_valuation(ts_code)Get latest day valuation data

Valuation Indicators:

IndicatorDescriptionSource
PE_TTMPrice-to-Earnings (Trailing Twelve Months)stock_kline.pe_ttm
PBPrice-to-Bookstock_kline.pb
PCFPrice-to-Cash-Flowstock_kline.pcf

Percentile Rules:

PercentileLevelMeaning
< 20%UndervaluedAt historical low, potentially undervalued
20% - 40%Below AverageBelow historical median
40% - 60%FairAt historical median range
60% - 80%Above AverageAbove historical median
> 80%OvervaluedAt historical high, potentially overvalued

Usage:

fromtools.stock_valuationimportcalc_valuation_percentile, calc_valuation_summary# Get structured dataresult=calc_valuation_percentile('600519.SH')
print(f"PE_TTM: {result['pe_ttm']}, Percentile: {result['pe_ttm_percentile']}%, {result['pe_ttm_level']}")
# Get formatted summaryprint(calc_valuation_summary('600519.SH'))

tools/stock_technical.py — Technical Indicator Calculator

Calculates MA/MACD/RSI/BOLL/KDJ indicators from MySQL market_data.stock_kline table.

Core Functions:

FunctionDescription
calc_technical_indicators(ts_code, days=120)Calculate all technical indicators
calc_technical_summary(ts_code, days=120)Generate formatted summary
get_kline_data(ts_code, days=120)Get K-line data from MySQL

Technical Indicators:

IndicatorFormulaUsage
MA(5/10/20/60)Average of last N closing pricesTrend: Price above MA = bullish; MA crossover = buy/sell signal
MACDDIF = EMA(12) - EMA(26); DEA = EMA(DIF,9); Histogram = (DIF-DEA)×2Golden cross (DIF>DEA) = buy; Dead cross = sell
RSI(6/12/24)RS = Avg Gain / Avg Loss; RSI = 100 - 100/(1+RS)>80 = overbought; <20 = oversold
BOLL(20,2)Upper = MA+2σ; Middle = MA; Lower = MA-2σTouch upper = overbought; Touch lower = oversold
KDJ(9,3,3)RSV, K = 2/3K+1/3RSV, D = 2/3D+1/3K, J = 3K-2DK>80 = overbought; K<20 = oversold; K/D crossover

Signal Interpretation:

SignalMAMACDRSIBOLLKDJ
BullishMA5>MA10>MA20 (Bull alignment)DIF>DEA, Histogram>0RSI<20 (Oversold)Price bounces off lower bandK/D golden cross in oversold zone
BearishMA5<MA10<MA20 (Bear alignment)DIF<DEA, Histogram<0RSI>80 (Overbought)Price falls from upper bandK/D dead cross in overbought zone

Multi-indicator Confirmation:

Buy signals (need 2-3):

  • Price above MA20, MA bullish alignment (MA5>MA10>MA20)
  • MACD golden cross (DIF crosses above DEA)
  • RSI rebounds from oversold (<20 → >20)
  • Price bounces off Bollinger lower band
  • KDJ golden cross in oversold zone

Sell signals (need 2-3):

  • Price below MA20, MA bearish alignment (MA5<MA10<MA20)
  • MACD dead cross (DIF crosses below DEA)
  • RSI enters overbought (>80) then falls
  • Price falls from Bollinger upper band
  • KDJ dead cross in overbought zone

Usage:

fromtools.stock_technicalimportcalc_technical_indicators, calc_technical_summary# Get structured dataresult=calc_technical_indicators('600519.SH')
print(f"Close: {result['close']}, MA5: {result['ma5']}, MACD: {result['macd_signal']}")
# Get formatted summaryprint(calc_technical_summary('600519.SH'))

5.5 Sector Analysis Tools

tools/sector_ranking.py — Sector Ranking Tool

Calculates sector rankings from MySQL sector_industry_daily / sector_concept_daily tables.

Core Functions:

FunctionDescription
get_sector_ranking(sector_type, trade_date, top_n, sort_by)Sector ranking by pct_chg/amount/volume
get_sector_top_gainers(sector_type, days, top_n)Sectors with consecutive N-day gains
get_sector_top_losers(sector_type, days, top_n)Sectors with consecutive N-day losses
get_sector_summary(sector_type, trade_date)Market overview (advance/decline, limit up/down)

Usage:

fromtools.sector_rankingimportget_sector_ranking, get_sector_top_gainers, get_sector_summary# Top 10 industry sectors by pct_chgprint(get_sector_ranking(sector_type='industry', top_n=10))
# Sectors rising for 3 consecutive daysprint(get_sector_top_gainers(sector_type='industry', days=3))
# Industry sector market overviewprint(get_sector_summary(sector_type='industry'))

tools/sector_rotation.py — Rotation Trend Identifier

Analyzes sector momentum and capital rotation direction through short-term vs medium-term performance comparison.

Core Functions:

FunctionDescription
get_sector_momentum(sector_type, short_days, long_days, top_n)Momentum analysis — short vs medium term, momentum score
get_sector_rotation(sector_type, short_days, long_days, top_n)Rotation identification — capital inflow/outflow sectors
get_sector_strength(sector_type, days, top_n)Strength ranking — composite score of gains, up-days, volume
get_hot_cold_sectors(sector_type, days)Hot/cold classification — hot/warm/flat/cold categories

Usage:

fromtools.sector_rotationimportget_sector_momentum, get_sector_rotation, get_hot_cold_sectors# Industry sector momentum (3-day short vs 10-day medium)print(get_sector_momentum(sector_type='industry', short_days=3, long_days=10))
# Sector rotation (capital inflow/outflow)print(get_sector_rotation(sector_type='industry'))
# Hot/cold sector classificationprint(get_hot_cold_sectors(sector_type='industry', days=5))

tools/sector_compare.py — Sector Comparison Tool

Multi-sector price curve overlay comparison with normalization and ASCII trend charts.

Core Functions:

FunctionDescription
compare_sectors(sector_names, sector_type, days)Multi-sector cumulative return comparison (table + ASCII chart)
compare_sector_trend(sector_names, sector_type, days)Trend strength comparison with conclusion

Usage:

fromtools.sector_compareimportcompare_sectors, compare_sector_trend# Compare Baijiu vs Power vs Banks over 20 daysprint(compare_sectors(['白酒', '电力', '银行'], sector_type='industry', days=20))
# Trend strength comparison with conclusionprint(compare_sector_trend(['白酒', '电力', '银行', '证券'], days=20))

tools/sector_detail.py — Sector Deep Analysis Tool

Links constituent stock data to provide internal sector structure analysis.

Core Functions:

FunctionDescription
get_constituent_distribution(sector_name, sector_type, trade_date)Constituent distribution — advance/decline, limit up/down, median change, top/bottom 5
get_sector_money_flow(sector_name, sector_type, days)Capital flow analysis — volume trend, price-volume coordination, inflow/outflow
get_sector_correlation(sector_name1, sector_name2, sector_type)Sector correlation — Jaccard coefficient, overlapping constituents

Usage:

fromtools.sector_detailimportget_constituent_distribution, get_sector_money_flow, get_sector_correlation# Baijiu sector constituent distributionprint(get_constituent_distribution('白酒', sector_type='industry'))
# Power sector capital flow analysisprint(get_sector_money_flow('电力', sector_type='industry', days=10))
# Baijiu vs Beer sector correlationprint(get_sector_correlation('白酒', '啤酒', sector_type='industry'))

tools/news_stock_linker.py — News-Stock Linker

Links news headlines to mentioned companies/sectors and correlates with their recent price trends.

Core Functions:

FunctionDescription
find_news_by_keyword(keyword, limit)Search news by keyword (title/digest fuzzy match)
search_news_with_market(keyword, limit, days_before, days_after)Search news and auto-correlate with matched stocks/sectors price trends

Usage Example:

fromtools.news_stock_linkerimportfind_news_by_keyword, search_news_with_market# Search news by keywordprint(find_news_by_keyword('半导体', limit=5))
# Search news and correlate with market dataprint(search_news_with_market('贵州茅台', limit=3, days_before=3, days_after=3))

5.6 Sector Analysis Agent

agents/sector_agent.py — Sector Analysis Agent

Integrates sector ranking, rotation, comparison, and deep analysis tool groups for sector rotation analysis.

Tool Group Structure:

Tool GroupToolsDescription
sector-rankingget_sector_ranking / get_sector_top_gainers / get_sector_top_losers / get_sector_summarySector ranking
sector-rotationget_sector_momentum / get_sector_rotation / get_sector_strength / get_hot_cold_sectorsRotation analysis
sector-comparecompare_sectors / compare_sector_trendSector comparison
sector-detailget_constituent_distribution / get_sector_money_flow / get_sector_correlationDeep analysis

Run:

python agents/sector_agent.py

5.7 Correlation Analysis Agent

agents/correlation_agent.py — Correlation Analysis Agent

Integrates stock-sector mapping, sector financial aggregation, and news-market correlation tool groups for cross-data analysis.

Tool Group Structure:

Tool GroupToolsDescription
stock-sectorfind_stock_sectorsStock-sector mapping
sector-financeget_sector_financial_agg / get_sector_valuation_statsSector financial aggregation, valuation distribution
news-marketfind_news_by_keyword / search_news_with_marketNews search, news-market correlation

Run:

python agents/correlation_agent.py

5.8 Financial Health Scoring Tool

tools/financial_score.py — Financial Health Scoring Tool

Computes a four-dimension composite financial health score (0-100) with rating (Excellent/Good/Fair/Poor).

Scoring Dimensions:

DimensionWeightIndicators
Profitability30%ROE(40%) + Gross Margin(30%) + Net Margin(30%)
Growth25%Revenue YoY Growth(50%) + Net Profit YoY Growth(50%)
Safety25%Debt Ratio(40%) + Cash Flow/NP(35%) + AR Ratio(25%)
Quality20%Deducted NP Ratio(50%) + Cash Flow Consistency(50%)

Anomaly Deduction: HIGH -5pts, MEDIUM -2pts, max -15pts.

Core Functions:

FunctionDescription
calc_financial_score(ts_code, report_date=None)Calculate single stock financial health score
format_financial_score(ts_code, report_date=None)Generate formatted Markdown output
score_sector(sector_name, sector_type, top_n)Batch score sector constituents

Run:

python tools/financial_score.py --ts_code 600519.SH
python tools/financial_score.py --sector 白酒 --top_n 10
python tools/financial_score.py --ts_codes 600519.SH,300750.SZ,601318.SH

5.9 Financial Q&A Agent

agents/financial_agent.py — Financial Q&A Agent

Integrates fundamental indicators, trend analysis, comparison, anomaly detection, financial scoring, and batch screening tool groups for complex financial Q&A.

Tool Group Structure:

Tool GroupToolsDescription
fundamentalcalc_fundamental_indicators / calc_fundamental_trend / get_financial_data / get_report_datesFinancial indicator calculation
comparecompare_companies / compare_periodsFinancial comparison and trends
score-anomalyformat_financial_score / calc_financial_score / detect_anomaliesScoring and anomaly detection
screeningscreen_cashflow_positive_stocks / screen_margin_decline_stocks / screen_roe_stocksBatch screening
queryquery_financial_dataFinancial data query

Example Queries:

"Which banks have positive operating cash flow for the past year?"
"Compare CATL and BYD's debt ratio trends"
"Which companies had gross margin drop > 10% last quarter?"
"Give me a DuPont analysis for Kweichow Moutai"
"Find companies with ROE > 20% for 3 consecutive years"

Run:

python agents/financial_agent.py

5.10 Daily Market Report Agent

agents/daily_report_agent.py — Daily Market Report Agent

Integrates market overview, trend assessment, sector rotation, anomaly detection, news correlation, and watchlist report tool groups for natural language Q&A on daily market briefings.

Tool Group Structure:

Tool GroupToolsDescription
market-overviewget_market_overview / format_market_overviewMarket overview
market-trendanalyze_market_trend / format_market_trendTrend assessment
sector-analysisget_sector_ranking / get_sector_rotation / get_hot_cold_sectors etc. (8 tools)Sector analysis
abnormal-detectiondetect_abnormal / format_abnormalAnomaly detection
newsfind_news_by_keyword / search_news_with_marketNews search
watchlistget_watchlist_report / format_watchlist_reportWatchlist report
daily-digestgenerate_daily_digestOne-click daily report

Example Queries:

"Generate today's market morning briefing"
"Which stocks hit limit up today? Which sectors do they belong to?"
"How has market sentiment been this week?"
"Which sectors are seeing capital inflow?"
"What important news is there today?"
"How are my watchlist stocks performing?"

Run:

python agents/daily_report_agent.py

5.11 Daily Market Report Tools

tools/market_overview.py — Market Overview Tool

Aggregates all market stock data to compute daily market overview (advance/decline counts, limit up/down, turnover, etc.).

Core Functions:

FunctionDescription
get_market_overview(trade_date=None)Get market overview as structured data
format_market_overview(trade_date=None)Generate formatted Markdown output

Output Metrics:

MetricDescription
Advance/DeclineUp/down/flat counts and percentages
Limit Up/DownMain board >=9.9%, ChiNext/STAR >=19.9%
Total TurnoverMarket-wide turnover (100M CNY)
Avg/Median ChangeOverall market change level
Market SentimentStrong rally/Bullish/Neutral/Bearish/Weak decline

Run:

python tools/market_overview.py
python tools/market_overview.py --trade_date 20260801

tools/abnormal_detector.py — Anomaly Detection Tool

Detects daily market anomalies: limit up/down stocks, volume breakouts, abnormal price movements, sector anomalies.

Core Functions:

FunctionDescription
detect_abnormal(trade_date=None)Detect anomalies, return structured data
format_abnormal(trade_date=None)Generate formatted Markdown output

Detection Types:

TypeCondition
Limit Up/DownMain board >=9.9%, ChiNext/STAR >=19.9%
Volume BreakoutVolume ratio >3 AND gain >3% (ratio = current vol / 20-day avg vol)
Price Surge
Sector Anomaly

Run:

python tools/abnormal_detector.py
python tools/abnormal_detector.py --trade_date 20260801

tools/market_trend.py — Trend Assessment Tool

Multi-dimensional market sentiment analysis based on recent N-day data.

Core Functions:

FunctionDescription
analyze_market_trend(days=5)Analyze market trend, return structured data
format_market_trend(days=5)Generate formatted Markdown output

Scoring Dimensions (20 pts each, 100 total):

DimensionSourceLogic
Advance/Decline Ratiostock_kline 5-dayAverage advancing stock ratio
Limit Up/Down Ratiostock_kline latestLimit up / (up + down + 1)
Turnover Trendstock_kline 5-dayRecent 5d vs prior 5d, volume expansion/contraction
Sector Rotationsector_industry_dailyAdvancing sector ratio
Consecutive Trendstock_kline 5-dayConsecutive up/down days

Sentiment Mapping: >=75 Optimistic / >=60 Mildly Bullish / >=40 Neutral / >=25 Mildly Bearish / <25 Pessimistic

Run:

python tools/market_trend.py
python tools/market_trend.py --days 10

tools/watchlist_report.py — Watchlist Report Tool

Personalized daily report for user-watched stocks: daily performance, 5-day change, related news.

Core Functions:

FunctionDescription
get_watchlist_report(ts_codes, trade_date=None)Get watchlist report as structured data
format_watchlist_report(ts_codes, trade_date=None)Generate formatted Markdown output

Report Content:

ModuleDescription
Daily PerformanceClose price, change %, turnover
5-Day ChangeCumulative change over 5 trading days
Related NewsSearch news by stock name (max 3 per stock)

Watchlist Config: Edit tools/watchlist_config.json to set default watchlist.

Run:

python tools/watchlist_report.py --ts_codes 600519.SH,300750.SZ
python tools/watchlist_report.py # Use default from watchlist_config.json

tools/daily_digest.py — Daily Report Generator (Enhanced)

Generates complete daily market briefing by integrating all 6 modules.

Core Functions:

FunctionDescription
generate_daily_digest(trade_date=None, watchlist=None)Generate complete daily report (Markdown)

Report Structure:

SectionModuleSource
1Market Overviewmarket_overview.py
2Trend Assessmentmarket_trend.py
3Sector Rotationsector_ranking.py + sector_rotation.py
4Market Anomaliesabnormal_detector.py
5Important Newsnews_stock_linker.py
6Watchlist Report (optional)watchlist_report.py

Run:

python tools/daily_digest.py
python tools/daily_digest.py --trade_date 20260801
python tools/daily_digest.py --watchlist 600519.SH,300750.SZ

5.12 Tool Function Mapping

Existing langgraph_getdata/New tools/Description
query_market_data_day_k.pystock_query.pyStock K-line query
query_industry_index_market.pysector_query.pySector quote query
query_industry_component_list.pysector_query.pySector constituents
query_concept_dc_day.pysector_query.pyConcept sector quotes
query_concept_dc_stock.pysector_query.pyConcept sector constituents
query_fin_account.pyfinancial_query.pyFinancial statement query (Done)
(None)news_query.pyNews query (New)
(None)stock_fundamental.pyFundamental indicators (Done)
(None)stock_valuation.pyValuation percentile (Done)
(None)stock_technical.pyTechnical indicators (Done)
(None)stock_sector_mapping.pyStock-sector mapping (Done)
(None)sector_financial_agg.pySector financial aggregation (Done)
(None)news_stock_linker.pyNews-stock correlation (Done)
(None)financial_score.pyFinancial health scoring (Done)
(None)sector_data.pySector data utilities (Done)
(None)market_overview.pyMarket overview tool (Done)
(None)abnormal_detector.pyAnomaly detection tool (Done)
(None)market_trend.pyTrend assessment tool (Done)
(None)watchlist_report.pyWatchlist report tool (Done)
(None)daily_digest.pyDaily report generator (Done)

5.13 Dependencies

pip install agentscope>=2.0.3 fastapi uvicorn

About

Built on professional finance knowledge, it provides stock diagnostics, sector index analysis, investment Q&A and news insights to help investors capture market opportunities efficiently.

Resources

Stars

5 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

FinAssistant Logo

FinAssistant — AI-Powered Financial Analysis

RAG Retrieval & Agent System for China A-Share Market

BackgroundFeaturesData AssetsImplementationTools

中文 | English


1. Background

The China A-share market has diverse data dimensions and massive information volumes. Retail investors and small-to-medium institutions struggle to efficiently integrate stock quotes, sector rotation, financial statements, and market news for comprehensive analysis. This project aims to build a financial RAG retrieval and agent system based on collected A-share data assets, enabling users to perform professional financial analysis through natural language conversations.

Core Objectives

  • Lower Analysis Barriers: Replace manual data queries, indicator calculations, and report writing with natural language
  • Multi-dimensional Data Correlation: Connect stocks, sectors, financials, and news for a panoramic view
  • Agent Collaboration: Multiple specialized agents working together, covering the full workflow from data queries to research reports

Tech Stack

LayerTechnology
Agent FrameworkAgentScope 2.0 (Multi-Agent Orchestration)
Data StorageMySQL (Structured Query) + Milvus (Vector Retrieval)
Data CollectionPython + akshare + DrissionPage
LLMQwen / GPT / Claude
Embeddingtext-embedding-v3 / BGE
FrontendStreamlit / Gradio

2. Feature Modules

Six intelligent agent modules planned based on existing data assets:


2.1 Stock Analysis Agent

Data Support: Daily stock quotes + Company info + Financial statements

Core Features:

FeatureDescriptionImplementation
Fundamental ScoreAuto-score (0-100) based on ROE, gross margin, debt ratio, cash flowExtract key fields from 3 statements, weighted calculation
Valuation PercentilePE/PB/PCF percentile in 1-year history, determine over/undervaluedCalculate percentile on daily PE/PB series
Technical IndicatorsMA(5/10/20/60), MACD, RSI, Bollinger Bands, KDJReal-time calculation based on OHLCV data
Trading SignalsGolden/Dead cross, MA breakout, RSI overbought/oversoldTechnical indicator crossover detection
Stock Profile ReportComprehensive fundamental + technical + valuation + sector reportLLM aggregates analysis results into text

Example Queries:

"How is Pudong Bank's cash flow situation this quarter?"
"What is Ping An Bank's current valuation percentile?"
"Analyze Kweichow Moutai's technical trend and give trading advice"
"Generate a stock profile report for CATL"

To-Do:

  • tools/stock_fundamental.py — Fundamental indicator calculator (Done)
  • tools/stock_valuation.py — Valuation percentile analyzer (Done)
  • tools/stock_technical.py — Technical indicator calculator (Done)
  • tools/stock_analysis.py — Comprehensive stock analysis report (Done)
  • agents/stock_agent.py — Stock analysis agent (Done)

Agent Demo:

$ python agents/stock_agent.py
============================================================
FinAssistant — 金融智能体
============================================================
输入股票代码或问题开始分析,输入 'quit' 退出
============================================================
你: 帮我分析贵州茅台的技术面走势,给出操作建议
FinAssistant:
[调用工具: reset_tools]
[完成] 结果: The currently activated tool group(s): stock-technical.
[调用工具: calc_technical_summary]
[完成] 结果: === 600519.SH 技术指标分析 (2026-07-17) ===
收盘价: 1253.0
【移动平均线 MA】
MA5: 1237.78
MA10: 1217.11
MA20: 1204.07
MA60: 1263.65
均线趋势: 多头排列
【MACD】
DIF: -0.2443
DEA: -11.3353
MACD柱: 22.182
信号: 金叉
【RSI】
RSI(6): 92.76
RSI(12): 68.8
RSI(24): 48.73
RSI(6)信号: 超买
【布林带 BOLL】
上轨: 1252.21
中轨: 1204.07
下轨: 1155.92
【KDJ】
K: 84.3
D: 79.2
J: 94.49
信号: 金叉
【综合研判】
当前信号: MA多头排列, MACD金叉, RSI超买, KDJ金叉
### 贵州茅台(600519.SH)技术面分析与操作建议
#### 一、核心技术指标摘要(近120天)
| 指标类型 | 关键数据 | 信号解读 |
|---------|---------|---------|
| **均线系统** | MA5:1237.78, MA10:1217.11, MA20:1204.07, MA60:1263.65 | 短期均线多头排列,股价略低于MA60(1263.65),中期趋势依然向上 |
| **MACD** | DIF:-0.24, DEA:-11.34, MACD柱:22.18 | 低位金叉形成,空头趋势减弱,短期反弹信号明确 |
| **RSI** | RSI(6):92.76, RSI(12):68.80, RSI(24):48.73 | 短期RSI严重超买(>90),警惕回调风险 |
| **布林带** | 上轨:1252.21, 中轨:1204.07, 下轨:1155.92 | 股价突破上轨,处于强势区间,但短期乖离率偏大 |
| **KDJ** | K:84.30, D:79.20, J:94.49 | 高位金叉,短期上涨动能充足,但J线接近超买区 |
#### 二、综合研判
技术面呈现**强趋势与短期超买并存**的格局:
1. **多头趋势明确**:均线多头排列、MACD低位金叉、KDJ金叉共同构成中期上涨信号
2. **短期回调风险**:RSI超买、股价突破布林上轨提示短期涨幅过大,存在技术性回调需求
#### 三、操作建议
1. **持仓投资者**:
- 继续持有为主,可将MA20(1204.07)作为止损线
- 若股价回落至MA5-MA10区间(1217-1238)可适当加仓
- 短期若冲高至MA60(1263.65)遇阻,可考虑部分止盈
2. **观望投资者**:
- 等待回调至关键支撑位(MA20:1204或布林中轨:1204)再考虑进场
- 若股价直接突破MA60并站稳,可小仓位追涨
⚠️ **风险提示**:技术分析仅供参考,不构成投资建议。市场存在不确定性,需结合自身风险承受能力决策。

2.2 Sector Rotation Analysis Agent

Data Support: Industry/Concept sector daily quotes (90 industry + 374 concept) + Constituent stocks

Core Features:

FeatureDescriptionImplementation
Sector RankingRank by pct_chg, volume change, capital flowAggregate sector daily_index
Rotation TrendSectors with consecutive top N-day gains marked as "hot"Sliding window rank change analysis
Sector ComparisonMulti-sector price curves overlayExtract multiple sector close series
Constituent DistributionAdvance/decline count, limit up/down, median changeLink constituent daily data
Capital FlowVolume change trend, determine inflow/outflowVolume QoQ change analysis
Sector CorrelationConstituent stock overlap between two sectorsSet intersection/union ratio

Example Queries:

"Which industry sectors had the highest gains this week?"
"How has the semiconductor sector performed this month? Is capital flowing in or out?"
"How high is the overlap between AI and robotics concept constituents?"
"Which sectors had limit-down waves today?"

To-Do:

  • tools/sector_ranking.py — Sector ranking tool (Done)
  • tools/sector_rotation.py — Rotation trend identifier (Done)
  • tools/sector_compare.py — Sector comparison tool (Done)
  • tools/sector_detail.py — Sector deep analysis tool (Done)
  • agents/sector_agent.py — Sector analysis agent (Done)

Agent Demo:

$ python agents/sector_agent.py
============================================================
FinAssistant — 板块轮动分析智能体
============================================================
输入板块相关问题开始分析,输入 'quit' 退出
示例:
- 最近一周涨幅最大的行业板块有哪些?
- 半导体板块最近一个月资金是在流入还是流出?
- AI概念和机器人概念的成分股重叠度有多高?
- 今天哪些板块出现了跌停潮?
============================================================
你: 最近一周涨幅最大的行业板块有哪些?
FinAssistant:
[调用工具: get_sector_ranking]
[完成] 结果: === 行业板块涨跌幅排名 (2026-07-17) ===
Top 10:
排名 板块名称 涨跌幅(%) 成交额(亿)
1 通信设备 +5.23 312.45
2 半导体 +4.87 528.91
3 消费电子 +3.65 287.33
...
[调用工具: get_sector_top_gainers]
[完成] 结果: === 连续3天上涨的行业板块 ===
板块名称 连涨天数 累计涨幅(%)
半导体 3 +8.92
通信设备 3 +7.56
...
综合来看,最近一周涨幅最大的行业板块主要集中在科技领域:
1. **通信设备** (+5.23%) — 5G建设持续推进,板块领涨
2. **半导体** (+4.87%) — 国产替代逻辑强化,资金持续流入
3. **消费电子** (+3.65%) — 新品发布预期带动板块走强
其中半导体和通信设备已连续3天上涨,短期动能较强。
⚠️ 风险提示:板块轮动较快,追高需谨慎。以上分析仅供参考,不构成投资建议。

2.3 Cross-Data Correlation Analysis Agent

Data Support: Quotes + Constituents + Financial statements + News (Full data cross-correlation)

Core Features:

FeatureDescriptionImplementation
Stock→Sector MappingQuery which sectors a stock belongs to, recent performanceReverse lookup in constituent data
Sector→Financial AggregationAverage ROE, median PE, total revenue for sector constituentsLink constituent codes to financial statements
News→Quote CorrelationCompanies/sectors mentioned in news, link to recent price trendsNER entity recognition + code matching
Industry ChainInfer upstream/downstream relationships via concept overlapConstituent set similarity clustering
Leader EffectTop N stocks by market cap vs sector overall performanceMarket-cap weighted vs equal-weight index

Example Queries:

"Which concept sectors does BYD belong to? How are they performing?"
"What's the average PE and ROE for the semiconductor sector?"
"Any recent news about solar power? How are related sectors trending?"
"Find the top 5 stocks most correlated with CATL"

To-Do:

  • tools/stock_sector_mapping.py — Stock-sector mapping tool (Done)
  • tools/sector_financial_agg.py — Sector financial aggregation (Done)
  • tools/news_stock_linker.py — News-quote correlation tool (Done)
  • agents/correlation_agent.py — Correlation analysis agent (Done)

2.4 Financial Q&A Agent (RAG)

Data Support: Financial statements (4,593 stocks × multi-period) + Vector database (Milvus)

Core Features:

FeatureDescriptionImplementation
NL Financial Query"Which companies have gross margin > 50%" → SQL/Vector searchVectorize financial fields + structured query
Cross-stock ComparisonHorizontal comparison of financial indicators for same-industry companiesGroup by industry + indicator comparison
Multi-period TrendVertical comparison of same company across periodsTime series analysis + trend detection
Anomaly AlertCash flow plunge, receivables surge, goodwill impairmentThreshold/QoQ change detection
Financial Health ScoreComprehensive solvency, profitability, growth, operational abilityDuPont analysis system + weighted scoring

Example Queries:

"Which banks have positive operating cash flow for the past year?"
"Compare CATL and BYD's debt ratio trends"
"Which companies had gross margin drop > 10% last quarter?"
"Give me a DuPont analysis for Kweichow Moutai"
"Find companies with ROE > 20% for 3 consecutive years"

To-Do:

  • tools/financial_query.py — Financial data query tool (Done)
  • tools/financial_compare.py — Financial comparison tool (Done)
  • tools/financial_anomaly.py — Anomaly detection tool (Done)
  • tools/financial_score.py — Financial health scoring tool (Done)
  • agents/financial_agent.py — Financial Q&A agent (Done)
  • rag/financial_embedding.py — Financial statement vectorization

2.5 Daily Market Report Agent

Data Support: Full data (Quotes + Sectors + News + Financials)

Core Features:

FeatureDescriptionImplementation
Market OverviewMajor index changes, volume, advance/decline statsAggregate all market stock data
Sector Rotation SummaryTop gainers/losers, capital inflow/outflow Top5Sector ranking tool output
Anomaly DetectionLimit up/down, volume breakout, abnormal volatilityFilter conditions
News SummaryMarket-related important news, linked sectorsNews filtering + LLM summary
Watchlist ReportUser's watched stocks daily performance, announcementsPersonalized filtering
Trend AssessmentBased on recent N-day data, market sentiment judgmentMulti-indicator synthesis

Example Queries:

"Generate today's market morning briefing"
"Which stocks hit limit up today? Which sectors do they belong to?"
"How has market sentiment been this week?"
"How are my watchlist stocks performing today?"

To-Do:

  • tools/market_overview.py — Market overview tool (Done)
  • tools/abnormal_detector.py — Anomaly detection tool (Done)
  • tools/market_trend.py — Trend assessment tool (Done)
  • tools/watchlist_report.py — Watchlist report tool (Done)
  • tools/daily_digest.py — Daily report generator (Done, integrates all 6 modules)
  • agents/daily_report_agent.py — Daily report agent (Done)

2.6 Research Report Generation Agent

Data Support: Full data + LLM generation capabilities

Core Features:

FeatureDescriptionImplementation
Stock Deep ReportComprehensive fundamental + technical + valuation + industry positionCall previous tools + LLM long-text generation
Industry ResearchSector trends, constituent financials, industry chain analysisSector tools + Financial tools + LLM
Comparative Report2-3 same-industry companies multi-dimensional comparisonComparison tools + LLM
Event Impact AnalysisNews/policy impact on related sectors and stocksNews correlation + Historical analogy + LLM
Portfolio SuggestionRecommend sector/stock allocation based on risk preferenceOptimization algorithm + LLM

Example Queries:

"Write a deep research report on the semiconductor industry"
"Compare BYD, CATL, and LONGi Green Energy with a comparative analysis"
"Which A-share sectors are most affected by Fed rate hikes?"
"I prefer conservative investing, recommend some sector allocation plans"

To-Do:

  • tools/report_generator.py — Report generation tool (LLM + templates)
  • templates/ — Report templates (stock/industry/comparison/event)
  • agents/report_agent.py — Report generation agent
  • agents/portfolio_agent.py — Portfolio optimization agent

3. Data Assets

3.1 Data Overview

Data TypeVolumeSourceTime Range
SH Stock Daily Quotes2,308 stocksSina Finance (akshare)2026-01-01 ~ Present
SZ Stock Daily Quotes2,895 stocksSina Finance (akshare)2026-01-01 ~ Present
SH Company Info2,308 (Main 1,699 + STAR 609)SSE (akshare)-
SZ Company Info2,895SZSE (akshare)-
SH Financial Statements2,308 stocksSina Finance (akshare)Recent 3 years
SZ Financial Statements2,895 stocksSina Finance (akshare)Recent 3 years
Industry Sector Quotes90 sectorsTonghuashun (akshare)2026-01-01 ~ Present
Concept Sector Quotes374 sectorsTonghuashun (akshare)2026-01-01 ~ Present
Industry Constituents90 sectorsTonghuashun (DrissionPage)-
Concept Constituents374 sectorsTonghuashun (DrissionPage)-
Financial News-Tonghuashun 7x242026-01-01 ~ Present

3.2 MySQL Table Schema

Data is stored in Alibaba Cloud RDS MySQL with two databases: market_data (quotes/financials) and stock_news (news).

market_data.company_info — Company Basic Info

CREATETABLEcompany_info (
id INT AUTO_INCREMENT PRIMARY KEY COMMENT 'Auto-increment ID',
ts_code VARCHAR(20) NOT NULL COMMENT 'Stock code with suffix, e.g., 600000.SH',
symbol VARCHAR(10) NOT NULL COMMENT 'Stock code (numeric only)',
stock_name VARCHAR(50) COMMENT 'Stock short name',
full_name VARCHAR(100) COMMENT 'Company full name',
industry VARCHAR(50) COMMENT 'Industry, e.g., J Finance',
list_date VARCHAR(20) COMMENT 'Listing date, format YYYY-MM-DD',
market VARCHAR(5) COMMENT 'Market, SH=Shanghai SZ=Shenzhen',
updated_at VARCHAR(30) COMMENT 'Data update time',
UNIQUE KEY uk_ts_code (ts_code)
)

market_data.stock_kline — Stock Daily K-line

CREATETABLEstock_kline (
id BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT 'Auto-increment ID',
ts_code VARCHAR(20) NOT NULL COMMENT 'Stock code with suffix',
symbol VARCHAR(10) NOT NULL COMMENT 'Stock code (numeric only)',
trade_date VARCHAR(20) NOT NULL COMMENT 'Trade date, format YYYY-MM-DD',
open DOUBLE COMMENT 'Open price (CNY)',
close DOUBLE COMMENT 'Close price (CNY)',
high DOUBLE COMMENT 'High price (CNY)',
low DOUBLE COMMENT 'Low price (CNY)',
pre_close DOUBLE COMMENT 'Previous close (CNY)',
change_data DOUBLE COMMENT 'Price change (CNY)',
pct_chg DOUBLE COMMENT 'Change percentage (%)',
volume DOUBLE COMMENT 'Volume (shares)',
amount DOUBLE COMMENT 'Turnover (CNY)',
pe DOUBLE COMMENT 'P/E ratio',
pb DOUBLE COMMENT 'P/B ratio',
total_mv DOUBLE COMMENT 'Total market cap (100M CNY)',
total_share DOUBLE COMMENT 'Total shares',
float_share DOUBLE COMMENT 'Float shares',
circ_mv DOUBLE COMMENT 'Circulating market cap (100M CNY)',
ln_pctchg DOUBLE COMMENT 'Log return',
pe_ttm DOUBLE COMMENT 'P/E ratio (TTM)',
pe_static DOUBLE COMMENT 'Static P/E ratio',
pcf DOUBLE COMMENT 'Price-to-Cash-Flow ratio',
UNIQUE KEY uk_code_date (ts_code, trade_date),
KEY idx_trade_date (trade_date),
KEY idx_symbol (symbol)
)

market_data.stock_financial — Financial Statements

CREATETABLEstock_financial (
id BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT 'Auto-increment ID',
ts_code VARCHAR(20) NOT NULL COMMENT 'Stock code with suffix',
symbol VARCHAR(10) NOT NULL COMMENT 'Stock code (numeric only)',
statement_type VARCHAR(20) NOT NULL COMMENT 'Statement type: income/balance/cashflow',
report_date VARCHAR(20) NOT NULL COMMENT 'Report date, e.g., 20260331',
report_data JSON COMMENT 'Complete statement data (JSON)',
UNIQUE KEY uk_code_type_date (ts_code, statement_type, report_date),
KEY idx_symbol (symbol),
KEY idx_report_date (report_date),
KEY idx_statement_type (statement_type)
)

Financial fields vary significantly across industries (banking vs manufacturing), hence JSON storage for complete statement data.

market_data.sector_industry_daily / sector_concept_daily — Sector Daily K-line

CREATETABLEsector_industry_daily (
id BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT 'Auto-increment ID',
sector_name VARCHAR(50) NOT NULL COMMENT 'Sector name',
sector_code VARCHAR(20) NOT NULL COMMENT 'Sector code',
trade_date VARCHAR(20) NOT NULL COMMENT 'Trade date',
open DOUBLE COMMENT 'Open',
high DOUBLE COMMENT 'High',
low DOUBLE COMMENT 'Low',
close DOUBLE COMMENT 'Close',
vol DOUBLE COMMENT 'Volume',
amount DOUBLE COMMENT 'Turnover',
pct_chg DOUBLE COMMENT 'Change (%)',
change_data DOUBLE COMMENT 'Point change',
pct_change DOUBLE COMMENT 'Change (backup)',
turnover_rate DOUBLE COMMENT 'Turnover rate',
UNIQUE KEY uk_code_date (sector_code, trade_date),
KEY idx_trade_date (trade_date),
KEY idx_sector_name (sector_name)
)

market_data.sector_industry_cons / sector_concept_cons — Sector Constituents

CREATETABLEsector_industry_cons (
id BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT 'Auto-increment ID',
sector_name VARCHAR(50) NOT NULL COMMENT 'Sector name',
sector_code VARCHAR(20) NOT NULL COMMENT 'Sector code',
stock_code VARCHAR(10) NOT NULL COMMENT 'Stock code',
stock_name VARCHAR(50) COMMENT 'Stock name',
UNIQUE KEY uk_sector_stock (sector_code, stock_code),
KEY idx_sector_name (sector_name),
KEY idx_stock_code (stock_code)
)

stock_news.news_em — Eastmoney 7x24 News

CREATETABLEnews_em (
id INT AUTO_INCREMENT PRIMARY KEY COMMENT 'Auto-increment ID',
title VARCHAR(500) NOT NULL COMMENT 'News title',
digest TEXT COMMENT 'News digest',
publish_time VARCHAR(30) COMMENT 'Publish time',
url VARCHAR(500) COMMENT 'News URL',
crawl_time VARCHAR(30) COMMENT 'Crawl time',
UNIQUE KEY uk_title_time (title, publish_time)
)

stock_news.news_ths — Tonghuashun Financial News

CREATETABLEnews_ths (
id INT AUTO_INCREMENT PRIMARY KEY COMMENT 'Auto-increment ID',
news_id VARCHAR(20) NOT NULL COMMENT 'News ID',
title VARCHAR(500) NOT NULL COMMENT 'News title',
digest TEXT COMMENT 'News digest',
url VARCHAR(500) COMMENT 'News URL',
tags VARCHAR(500) COMMENT 'Tags (comma separated)',
ctime_str VARCHAR(30) COMMENT 'Publish time',
source VARCHAR(100) COMMENT 'Source',
crawl_time VARCHAR(30) COMMENT 'Crawl time',
UNIQUE KEY uk_news_id (news_id),
KEY idx_ctime (ctime_str)
)

3.3 Data Import Scripts

ScriptTarget TableDescription
import_company_info_to_mysql.pymarket_data.company_infoSH/SZ company info
import_kline_to_mysql.pymarket_data.stock_klineStock daily K-line (560K+ rows)
import_financial_to_mysql.pymarket_data.stock_financialFinancial statements (170K+ rows)
import_sector_to_mysql.pymarket_data.sector_*_dailySector daily K-line
import_sector_cons_to_mysql.pymarket_data.sector_*_consSector constituents
import_news_em_to_mysql.pystock_news.news_emEastmoney news
import_news_ths_to_mysql.pystock_news.news_thsTonghuashun news

3.4 Data Collection Scripts

ScriptPurposeSource
crawl_sh_stock_data.pySH stock quotes + company infoSina Finance / SSE
crawl_sz_stock_data.pySZ stock quotes + company infoSina Finance / SZSE
crawl_financial_reports.pyFinancial statementsSina Finance
crawl_sector_data.pySector daily quotes (Industry + Concept)Tonghuashun (akshare)
crawl_sector_cons.pySector constituentsSina Finance (akshare)
crawl_sector_cons_ths.pySector constituents (backup)Tonghuashun (DrissionPage)
crawl_news_ths.pyFinancial newsTonghuashun 7x24 API
crawl_news_em.pyEastmoney 7x24 news (scheduled)Eastmoney (akshare)

3.5 Known Issues

IssueDescription
Eastmoney API Blockedpush2his.eastmoney.com completely unavailable
Tonghuashun IP BlockedFrequent crawling triggers Nginx 403 block
Inconsistent Sector SourcesQuotes from THS, constituents partially from Sina, names may not match
SH Company Missing IndustrySSE API doesn't provide industry field

4. AgentScope 2.0 Implementation

4.1 Architecture

User Query → FastAPI → Agent (system_prompt + model + toolkit + middlewares)
↓
Toolkit
├── ToolGroup("Stock Analysis") → tools/stock_query.py + skills/stock-analysis/
├── ToolGroup("Sector Analysis") → tools/sector_query.py + skills/sector-rotation/
├── ToolGroup("Financial Q&A") → tools/financial_query.py + skills/financial-qa/
├── ToolGroup("Daily Report") → tools/news_query.py + skills/daily-report/
└── ToolGroup("Research Report") → tools/indicators.py + skills/research-report/

4.2 Directory Structure

FinAssistant/
├── config.py # Global config (paths, model, API Key)
├── main.py # FastAPI service entry
├── main_agent.py # Single agent script (no server, direct chat)
├── core/
│ ├── agent_setup.py # Agent + Toolkit initialization
│ └── middleware.py # Financial scenario middleware
├── tools/ # Tool functions
│ ├── __init__.py
│ ├── stock_query.py # Stock quote/company info query
│ ├── sector_query.py # Sector quote/constituent query
│ ├── financial_query.py # Financial statement query & analysis
│ ├── news_query.py # News query
│ └── indicators.py # Technical/fundamental indicator calculation
├── skills/ # Skill documents (SKILL.md)
│ ├── stock-analysis/SKILL.md
│ ├── sector-rotation/SKILL.md
│ ├── financial-qa/SKILL.md
│ ├── daily-report/SKILL.md
│ └── research-report/SKILL.md
├── data/ # Existing data (don't modify)
└── data_to_mysql_and_milvus/ # Existing crawler scripts (don't modify)

4.3 Implementation Steps

Step 1: config.py

Global configuration for data paths, model config, API keys.

Step 2: tools/ Tool Functions

Each function is async def, returns ToolChunk. Docstring is the tool description — LLM decides when to call based on docstring.

Step 3: skills/SKILL.md Skill Documents

Each skill directory has a SKILL.md with trigger conditions, dependent tools, and execution flow.

Step 4: core/middleware.py Middleware

MiddlewarePurpose
InputValidationMiddlewareFilter non-financial queries
ToolCallAuditMiddlewareLog tool calls to traces/
PerformanceMonitorMiddlewareMonitor inference rounds, latency, tokens
ContextEnrichmentMiddlewareInject current date, trading day context

Step 5: core/agent_setup.py Agent Initialization

Assemble model, tools, toolkit, and agent with middleware.

Step 6: main.py Service Entry

FastAPI service with OpenAI-compatible /v1/chat/completions endpoint.


5. Implemented Tools

tools/stock_fundamental.py — Fundamental Indicator Calculator

Calculates fundamental indicators from MySQL market_data.stock_financial table.

Core Functions:

FunctionDescription
calc_fundamental_indicators(ts_code, report_date=None)Calculate single-period indicators
calc_fundamental_trend(ts_code, periods=4)Calculate recent N-period trend
get_financial_data(ts_code, report_date=None)Get raw statement data
get_report_dates(ts_code, limit=8)Get report date list

Calculated Indicators:

IndicatorFormulaData Source
ROENet Profit / Equity × 100%Income + Balance Sheet
Gross Margin(Revenue - COGS) / Revenue × 100%Income Statement
Net MarginNet Profit / Revenue × 100%Income Statement
Debt RatioTotal Liabilities / Total Assets × 100%Balance Sheet
Cash Flow / Net ProfitOperating Cash Flow / Net ProfitCash Flow + Income
Revenue YoY Growth(Current - Prior Year) /Prior Year
Net Profit YoY Growth(Current - Prior Year) /Prior Year
Revenue QoQ Growth(Current Q - Prior Q) /Prior Q
Net Profit QoQ Growth(Current Q - Prior Q) /Prior Q

Special Handling:

  • Auto bank detection: Via balance sheet fields (loans, deposits)
  • Bank field mapping: Revenue = Net Interest Income + Fee Income; COGS = Interest Expense + Fee Expense
  • YoY calculation: Cumulative values vs same quarter last year (2026Q1 vs 2025Q1)
  • QoQ calculation: Single-quarter values (Q4 = Annual - 9-month cumulative)

Usage:

fromtools.stock_fundamentalimportcalc_fundamental_indicators, calc_fundamental_trend# Single periodresult=calc_fundamental_indicators('600519.SH')
print(result['ROE'], result['毛利率'], result['营收同比增长率'])
# Trend (recent 4 periods)trend=calc_fundamental_trend('600519.SH', periods=4)
fortintrend['trend']:
print(t['report_date'], t['ROE'], t['营收同比增长率'])

tools/stock_valuation.py — Valuation Percentile Analyzer

Calculates PE/PB/PCF percentile in 1-year history from market_data.stock_kline table.

Core Functions:

FunctionDescription
calc_valuation_percentile(ts_code, days=365)Calculate valuation percentile, return structured data
calc_valuation_summary(ts_code, days=365)Generate formatted valuation summary
get_valuation_history(ts_code, days=365)Get N-day valuation history
get_latest_valuation(ts_code)Get latest day valuation data

Valuation Indicators:

IndicatorDescriptionSource
PE_TTMPrice-to-Earnings (Trailing Twelve Months)stock_kline.pe_ttm
PBPrice-to-Bookstock_kline.pb
PCFPrice-to-Cash-Flowstock_kline.pcf

Percentile Rules:

PercentileLevelMeaning
< 20%UndervaluedAt historical low, potentially undervalued
20% - 40%Below AverageBelow historical median
40% - 60%FairAt historical median range
60% - 80%Above AverageAbove historical median
> 80%OvervaluedAt historical high, potentially overvalued

Usage:

fromtools.stock_valuationimportcalc_valuation_percentile, calc_valuation_summary# Get structured dataresult=calc_valuation_percentile('600519.SH')
print(f"PE_TTM: {result['pe_ttm']}, Percentile: {result['pe_ttm_percentile']}%, {result['pe_ttm_level']}")
# Get formatted summaryprint(calc_valuation_summary('600519.SH'))

tools/stock_technical.py — Technical Indicator Calculator

Calculates MA/MACD/RSI/BOLL/KDJ indicators from MySQL market_data.stock_kline table.

Core Functions:

FunctionDescription
calc_technical_indicators(ts_code, days=120)Calculate all technical indicators
calc_technical_summary(ts_code, days=120)Generate formatted summary
get_kline_data(ts_code, days=120)Get K-line data from MySQL

Technical Indicators:

IndicatorFormulaUsage
MA(5/10/20/60)Average of last N closing pricesTrend: Price above MA = bullish; MA crossover = buy/sell signal
MACDDIF = EMA(12) - EMA(26); DEA = EMA(DIF,9); Histogram = (DIF-DEA)×2Golden cross (DIF>DEA) = buy; Dead cross = sell
RSI(6/12/24)RS = Avg Gain / Avg Loss; RSI = 100 - 100/(1+RS)>80 = overbought; <20 = oversold
BOLL(20,2)Upper = MA+2σ; Middle = MA; Lower = MA-2σTouch upper = overbought; Touch lower = oversold
KDJ(9,3,3)RSV, K = 2/3K+1/3RSV, D = 2/3D+1/3K, J = 3K-2DK>80 = overbought; K<20 = oversold; K/D crossover

Signal Interpretation:

SignalMAMACDRSIBOLLKDJ
BullishMA5>MA10>MA20 (Bull alignment)DIF>DEA, Histogram>0RSI<20 (Oversold)Price bounces off lower bandK/D golden cross in oversold zone
BearishMA5<MA10<MA20 (Bear alignment)DIF<DEA, Histogram<0RSI>80 (Overbought)Price falls from upper bandK/D dead cross in overbought zone

Multi-indicator Confirmation:

Buy signals (need 2-3):

  • Price above MA20, MA bullish alignment (MA5>MA10>MA20)
  • MACD golden cross (DIF crosses above DEA)
  • RSI rebounds from oversold (<20 → >20)
  • Price bounces off Bollinger lower band
  • KDJ golden cross in oversold zone

Sell signals (need 2-3):

  • Price below MA20, MA bearish alignment (MA5<MA10<MA20)
  • MACD dead cross (DIF crosses below DEA)
  • RSI enters overbought (>80) then falls
  • Price falls from Bollinger upper band
  • KDJ dead cross in overbought zone

Usage:

fromtools.stock_technicalimportcalc_technical_indicators, calc_technical_summary# Get structured dataresult=calc_technical_indicators('600519.SH')
print(f"Close: {result['close']}, MA5: {result['ma5']}, MACD: {result['macd_signal']}")
# Get formatted summaryprint(calc_technical_summary('600519.SH'))

5.5 Sector Analysis Tools

tools/sector_ranking.py — Sector Ranking Tool

Calculates sector rankings from MySQL sector_industry_daily / sector_concept_daily tables.

Core Functions:

FunctionDescription
get_sector_ranking(sector_type, trade_date, top_n, sort_by)Sector ranking by pct_chg/amount/volume
get_sector_top_gainers(sector_type, days, top_n)Sectors with consecutive N-day gains
get_sector_top_losers(sector_type, days, top_n)Sectors with consecutive N-day losses
get_sector_summary(sector_type, trade_date)Market overview (advance/decline, limit up/down)

Usage:

fromtools.sector_rankingimportget_sector_ranking, get_sector_top_gainers, get_sector_summary# Top 10 industry sectors by pct_chgprint(get_sector_ranking(sector_type='industry', top_n=10))
# Sectors rising for 3 consecutive daysprint(get_sector_top_gainers(sector_type='industry', days=3))
# Industry sector market overviewprint(get_sector_summary(sector_type='industry'))

tools/sector_rotation.py — Rotation Trend Identifier

Analyzes sector momentum and capital rotation direction through short-term vs medium-term performance comparison.

Core Functions:

FunctionDescription
get_sector_momentum(sector_type, short_days, long_days, top_n)Momentum analysis — short vs medium term, momentum score
get_sector_rotation(sector_type, short_days, long_days, top_n)Rotation identification — capital inflow/outflow sectors
get_sector_strength(sector_type, days, top_n)Strength ranking — composite score of gains, up-days, volume
get_hot_cold_sectors(sector_type, days)Hot/cold classification — hot/warm/flat/cold categories

Usage:

fromtools.sector_rotationimportget_sector_momentum, get_sector_rotation, get_hot_cold_sectors# Industry sector momentum (3-day short vs 10-day medium)print(get_sector_momentum(sector_type='industry', short_days=3, long_days=10))
# Sector rotation (capital inflow/outflow)print(get_sector_rotation(sector_type='industry'))
# Hot/cold sector classificationprint(get_hot_cold_sectors(sector_type='industry', days=5))

tools/sector_compare.py — Sector Comparison Tool

Multi-sector price curve overlay comparison with normalization and ASCII trend charts.

Core Functions:

FunctionDescription
compare_sectors(sector_names, sector_type, days)Multi-sector cumulative return comparison (table + ASCII chart)
compare_sector_trend(sector_names, sector_type, days)Trend strength comparison with conclusion

Usage:

fromtools.sector_compareimportcompare_sectors, compare_sector_trend# Compare Baijiu vs Power vs Banks over 20 daysprint(compare_sectors(['白酒', '电力', '银行'], sector_type='industry', days=20))
# Trend strength comparison with conclusionprint(compare_sector_trend(['白酒', '电力', '银行', '证券'], days=20))

tools/sector_detail.py — Sector Deep Analysis Tool

Links constituent stock data to provide internal sector structure analysis.

Core Functions:

FunctionDescription
get_constituent_distribution(sector_name, sector_type, trade_date)Constituent distribution — advance/decline, limit up/down, median change, top/bottom 5
get_sector_money_flow(sector_name, sector_type, days)Capital flow analysis — volume trend, price-volume coordination, inflow/outflow
get_sector_correlation(sector_name1, sector_name2, sector_type)Sector correlation — Jaccard coefficient, overlapping constituents

Usage:

fromtools.sector_detailimportget_constituent_distribution, get_sector_money_flow, get_sector_correlation# Baijiu sector constituent distributionprint(get_constituent_distribution('白酒', sector_type='industry'))
# Power sector capital flow analysisprint(get_sector_money_flow('电力', sector_type='industry', days=10))
# Baijiu vs Beer sector correlationprint(get_sector_correlation('白酒', '啤酒', sector_type='industry'))

tools/news_stock_linker.py — News-Stock Linker

Links news headlines to mentioned companies/sectors and correlates with their recent price trends.

Core Functions:

FunctionDescription
find_news_by_keyword(keyword, limit)Search news by keyword (title/digest fuzzy match)
search_news_with_market(keyword, limit, days_before, days_after)Search news and auto-correlate with matched stocks/sectors price trends

Usage Example:

fromtools.news_stock_linkerimportfind_news_by_keyword, search_news_with_market# Search news by keywordprint(find_news_by_keyword('半导体', limit=5))
# Search news and correlate with market dataprint(search_news_with_market('贵州茅台', limit=3, days_before=3, days_after=3))

5.6 Sector Analysis Agent

agents/sector_agent.py — Sector Analysis Agent

Integrates sector ranking, rotation, comparison, and deep analysis tool groups for sector rotation analysis.

Tool Group Structure:

Tool GroupToolsDescription
sector-rankingget_sector_ranking / get_sector_top_gainers / get_sector_top_losers / get_sector_summarySector ranking
sector-rotationget_sector_momentum / get_sector_rotation / get_sector_strength / get_hot_cold_sectorsRotation analysis
sector-comparecompare_sectors / compare_sector_trendSector comparison
sector-detailget_constituent_distribution / get_sector_money_flow / get_sector_correlationDeep analysis

Run:

python agents/sector_agent.py

5.7 Correlation Analysis Agent

agents/correlation_agent.py — Correlation Analysis Agent

Integrates stock-sector mapping, sector financial aggregation, and news-market correlation tool groups for cross-data analysis.

Tool Group Structure:

Tool GroupToolsDescription
stock-sectorfind_stock_sectorsStock-sector mapping
sector-financeget_sector_financial_agg / get_sector_valuation_statsSector financial aggregation, valuation distribution
news-marketfind_news_by_keyword / search_news_with_marketNews search, news-market correlation

Run:

python agents/correlation_agent.py

5.8 Financial Health Scoring Tool

tools/financial_score.py — Financial Health Scoring Tool

Computes a four-dimension composite financial health score (0-100) with rating (Excellent/Good/Fair/Poor).

Scoring Dimensions:

DimensionWeightIndicators
Profitability30%ROE(40%) + Gross Margin(30%) + Net Margin(30%)
Growth25%Revenue YoY Growth(50%) + Net Profit YoY Growth(50%)
Safety25%Debt Ratio(40%) + Cash Flow/NP(35%) + AR Ratio(25%)
Quality20%Deducted NP Ratio(50%) + Cash Flow Consistency(50%)

Anomaly Deduction: HIGH -5pts, MEDIUM -2pts, max -15pts.

Core Functions:

FunctionDescription
calc_financial_score(ts_code, report_date=None)Calculate single stock financial health score
format_financial_score(ts_code, report_date=None)Generate formatted Markdown output
score_sector(sector_name, sector_type, top_n)Batch score sector constituents

Run:

python tools/financial_score.py --ts_code 600519.SH
python tools/financial_score.py --sector 白酒 --top_n 10
python tools/financial_score.py --ts_codes 600519.SH,300750.SZ,601318.SH

5.9 Financial Q&A Agent

agents/financial_agent.py — Financial Q&A Agent

Integrates fundamental indicators, trend analysis, comparison, anomaly detection, financial scoring, and batch screening tool groups for complex financial Q&A.

Tool Group Structure:

Tool GroupToolsDescription
fundamentalcalc_fundamental_indicators / calc_fundamental_trend / get_financial_data / get_report_datesFinancial indicator calculation
comparecompare_companies / compare_periodsFinancial comparison and trends
score-anomalyformat_financial_score / calc_financial_score / detect_anomaliesScoring and anomaly detection
screeningscreen_cashflow_positive_stocks / screen_margin_decline_stocks / screen_roe_stocksBatch screening
queryquery_financial_dataFinancial data query

Example Queries:

"Which banks have positive operating cash flow for the past year?"
"Compare CATL and BYD's debt ratio trends"
"Which companies had gross margin drop > 10% last quarter?"
"Give me a DuPont analysis for Kweichow Moutai"
"Find companies with ROE > 20% for 3 consecutive years"

Run:

python agents/financial_agent.py

5.10 Daily Market Report Agent

agents/daily_report_agent.py — Daily Market Report Agent

Integrates market overview, trend assessment, sector rotation, anomaly detection, news correlation, and watchlist report tool groups for natural language Q&A on daily market briefings.

Tool Group Structure:

Tool GroupToolsDescription
market-overviewget_market_overview / format_market_overviewMarket overview
market-trendanalyze_market_trend / format_market_trendTrend assessment
sector-analysisget_sector_ranking / get_sector_rotation / get_hot_cold_sectors etc. (8 tools)Sector analysis
abnormal-detectiondetect_abnormal / format_abnormalAnomaly detection
newsfind_news_by_keyword / search_news_with_marketNews search
watchlistget_watchlist_report / format_watchlist_reportWatchlist report
daily-digestgenerate_daily_digestOne-click daily report

Example Queries:

"Generate today's market morning briefing"
"Which stocks hit limit up today? Which sectors do they belong to?"
"How has market sentiment been this week?"
"Which sectors are seeing capital inflow?"
"What important news is there today?"
"How are my watchlist stocks performing?"

Run:

python agents/daily_report_agent.py

5.11 Daily Market Report Tools

tools/market_overview.py — Market Overview Tool

Aggregates all market stock data to compute daily market overview (advance/decline counts, limit up/down, turnover, etc.).

Core Functions:

FunctionDescription
get_market_overview(trade_date=None)Get market overview as structured data
format_market_overview(trade_date=None)Generate formatted Markdown output

Output Metrics:

MetricDescription
Advance/DeclineUp/down/flat counts and percentages
Limit Up/DownMain board >=9.9%, ChiNext/STAR >=19.9%
Total TurnoverMarket-wide turnover (100M CNY)
Avg/Median ChangeOverall market change level
Market SentimentStrong rally/Bullish/Neutral/Bearish/Weak decline

Run:

python tools/market_overview.py
python tools/market_overview.py --trade_date 20260801

tools/abnormal_detector.py — Anomaly Detection Tool

Detects daily market anomalies: limit up/down stocks, volume breakouts, abnormal price movements, sector anomalies.

Core Functions:

FunctionDescription
detect_abnormal(trade_date=None)Detect anomalies, return structured data
format_abnormal(trade_date=None)Generate formatted Markdown output

Detection Types:

TypeCondition
Limit Up/DownMain board >=9.9%, ChiNext/STAR >=19.9%
Volume BreakoutVolume ratio >3 AND gain >3% (ratio = current vol / 20-day avg vol)
Price Surge
Sector Anomaly

Run:

python tools/abnormal_detector.py
python tools/abnormal_detector.py --trade_date 20260801

tools/market_trend.py — Trend Assessment Tool

Multi-dimensional market sentiment analysis based on recent N-day data.

Core Functions:

FunctionDescription
analyze_market_trend(days=5)Analyze market trend, return structured data
format_market_trend(days=5)Generate formatted Markdown output

Scoring Dimensions (20 pts each, 100 total):

DimensionSourceLogic
Advance/Decline Ratiostock_kline 5-dayAverage advancing stock ratio
Limit Up/Down Ratiostock_kline latestLimit up / (up + down + 1)
Turnover Trendstock_kline 5-dayRecent 5d vs prior 5d, volume expansion/contraction
Sector Rotationsector_industry_dailyAdvancing sector ratio
Consecutive Trendstock_kline 5-dayConsecutive up/down days

Sentiment Mapping: >=75 Optimistic / >=60 Mildly Bullish / >=40 Neutral / >=25 Mildly Bearish / <25 Pessimistic

Run:

python tools/market_trend.py
python tools/market_trend.py --days 10

tools/watchlist_report.py — Watchlist Report Tool

Personalized daily report for user-watched stocks: daily performance, 5-day change, related news.

Core Functions:

FunctionDescription
get_watchlist_report(ts_codes, trade_date=None)Get watchlist report as structured data
format_watchlist_report(ts_codes, trade_date=None)Generate formatted Markdown output

Report Content:

ModuleDescription
Daily PerformanceClose price, change %, turnover
5-Day ChangeCumulative change over 5 trading days
Related NewsSearch news by stock name (max 3 per stock)

Watchlist Config: Edit tools/watchlist_config.json to set default watchlist.

Run:

python tools/watchlist_report.py --ts_codes 600519.SH,300750.SZ
python tools/watchlist_report.py # Use default from watchlist_config.json

tools/daily_digest.py — Daily Report Generator (Enhanced)

Generates complete daily market briefing by integrating all 6 modules.

Core Functions:

FunctionDescription
generate_daily_digest(trade_date=None, watchlist=None)Generate complete daily report (Markdown)

Report Structure:

SectionModuleSource
1Market Overviewmarket_overview.py
2Trend Assessmentmarket_trend.py
3Sector Rotationsector_ranking.py + sector_rotation.py
4Market Anomaliesabnormal_detector.py
5Important Newsnews_stock_linker.py
6Watchlist Report (optional)watchlist_report.py

Run:

python tools/daily_digest.py
python tools/daily_digest.py --trade_date 20260801
python tools/daily_digest.py --watchlist 600519.SH,300750.SZ

5.12 Tool Function Mapping

Existing langgraph_getdata/New tools/Description
query_market_data_day_k.pystock_query.pyStock K-line query
query_industry_index_market.pysector_query.pySector quote query
query_industry_component_list.pysector_query.pySector constituents
query_concept_dc_day.pysector_query.pyConcept sector quotes
query_concept_dc_stock.pysector_query.pyConcept sector constituents
query_fin_account.pyfinancial_query.pyFinancial statement query (Done)
(None)news_query.pyNews query (New)
(None)stock_fundamental.pyFundamental indicators (Done)
(None)stock_valuation.pyValuation percentile (Done)
(None)stock_technical.pyTechnical indicators (Done)
(None)stock_sector_mapping.pyStock-sector mapping (Done)
(None)sector_financial_agg.pySector financial aggregation (Done)
(None)news_stock_linker.pyNews-stock correlation (Done)
(None)financial_score.pyFinancial health scoring (Done)
(None)sector_data.pySector data utilities (Done)
(None)market_overview.pyMarket overview tool (Done)
(None)abnormal_detector.pyAnomaly detection tool (Done)
(None)market_trend.pyTrend assessment tool (Done)
(None)watchlist_report.pyWatchlist report tool (Done)
(None)daily_digest.pyDaily report generator (Done)

5.13 Dependencies

pip install agentscope>=2.0.3 fastapi uvicorn

About

Built on professional finance knowledge, it provides stock diagnostics, sector index analysis, investment Q&A and news insights to help investors capture market opportunities efficiently.

Resources

Stars

5 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Repository files navigation

FinAssistant Logo

FinAssistant — AI-Powered Financial Analysis

RAG Retrieval & Agent System for China A-Share Market

BackgroundFeaturesData AssetsImplementationTools

中文 | English


1. Background

The China A-share market has diverse data dimensions and massive information volumes. Retail investors and small-to-medium institutions struggle to efficiently integrate stock quotes, sector rotation, financial statements, and market news for comprehensive analysis. This project aims to build a financial RAG retrieval and agent system based on collected A-share data assets, enabling users to perform professional financial analysis through natural language conversations.

Core Objectives

  • Lower Analysis Barriers: Replace manual data queries, indicator calculations, and report writing with natural language
  • Multi-dimensional Data Correlation: Connect stocks, sectors, financials, and news for a panoramic view
  • Agent Collaboration: Multiple specialized agents working together, covering the full workflow from data queries to research reports

Tech Stack

LayerTechnology
Agent FrameworkAgentScope 2.0 (Multi-Agent Orchestration)
Data StorageMySQL (Structured Query) + Milvus (Vector Retrieval)
Data CollectionPython + akshare + DrissionPage
LLMQwen / GPT / Claude
Embeddingtext-embedding-v3 / BGE
FrontendStreamlit / Gradio

2. Feature Modules

Six intelligent agent modules planned based on existing data assets:


2.1 Stock Analysis Agent

Data Support: Daily stock quotes + Company info + Financial statements

Core Features:

FeatureDescriptionImplementation
Fundamental ScoreAuto-score (0-100) based on ROE, gross margin, debt ratio, cash flowExtract key fields from 3 statements, weighted calculation
Valuation PercentilePE/PB/PCF percentile in 1-year history, determine over/undervaluedCalculate percentile on daily PE/PB series
Technical IndicatorsMA(5/10/20/60), MACD, RSI, Bollinger Bands, KDJReal-time calculation based on OHLCV data
Trading SignalsGolden/Dead cross, MA breakout, RSI overbought/oversoldTechnical indicator crossover detection
Stock Profile ReportComprehensive fundamental + technical + valuation + sector reportLLM aggregates analysis results into text

Example Queries:

"How is Pudong Bank's cash flow situation this quarter?"
"What is Ping An Bank's current valuation percentile?"
"Analyze Kweichow Moutai's technical trend and give trading advice"
"Generate a stock profile report for CATL"

To-Do:

  • tools/stock_fundamental.py — Fundamental indicator calculator (Done)
  • tools/stock_valuation.py — Valuation percentile analyzer (Done)
  • tools/stock_technical.py — Technical indicator calculator (Done)
  • tools/stock_analysis.py — Comprehensive stock analysis report (Done)
  • agents/stock_agent.py — Stock analysis agent (Done)

Agent Demo:

$ python agents/stock_agent.py
============================================================
FinAssistant — 金融智能体
============================================================
输入股票代码或问题开始分析,输入 'quit' 退出
============================================================
你: 帮我分析贵州茅台的技术面走势,给出操作建议
FinAssistant:
[调用工具: reset_tools]
[完成] 结果: The currently activated tool group(s): stock-technical.
[调用工具: calc_technical_summary]
[完成] 结果: === 600519.SH 技术指标分析 (2026-07-17) ===
收盘价: 1253.0
【移动平均线 MA】
MA5: 1237.78
MA10: 1217.11
MA20: 1204.07
MA60: 1263.65
均线趋势: 多头排列
【MACD】
DIF: -0.2443
DEA: -11.3353
MACD柱: 22.182
信号: 金叉
【RSI】
RSI(6): 92.76
RSI(12): 68.8
RSI(24): 48.73
RSI(6)信号: 超买
【布林带 BOLL】
上轨: 1252.21
中轨: 1204.07
下轨: 1155.92
【KDJ】
K: 84.3
D: 79.2
J: 94.49
信号: 金叉
【综合研判】
当前信号: MA多头排列, MACD金叉, RSI超买, KDJ金叉
### 贵州茅台(600519.SH)技术面分析与操作建议
#### 一、核心技术指标摘要(近120天)
| 指标类型 | 关键数据 | 信号解读 |
|---------|---------|---------|
| **均线系统** | MA5:1237.78, MA10:1217.11, MA20:1204.07, MA60:1263.65 | 短期均线多头排列,股价略低于MA60(1263.65),中期趋势依然向上 |
| **MACD** | DIF:-0.24, DEA:-11.34, MACD柱:22.18 | 低位金叉形成,空头趋势减弱,短期反弹信号明确 |
| **RSI** | RSI(6):92.76, RSI(12):68.80, RSI(24):48.73 | 短期RSI严重超买(>90),警惕回调风险 |
| **布林带** | 上轨:1252.21, 中轨:1204.07, 下轨:1155.92 | 股价突破上轨,处于强势区间,但短期乖离率偏大 |
| **KDJ** | K:84.30, D:79.20, J:94.49 | 高位金叉,短期上涨动能充足,但J线接近超买区 |
#### 二、综合研判
技术面呈现**强趋势与短期超买并存**的格局:
1. **多头趋势明确**:均线多头排列、MACD低位金叉、KDJ金叉共同构成中期上涨信号
2. **短期回调风险**:RSI超买、股价突破布林上轨提示短期涨幅过大,存在技术性回调需求
#### 三、操作建议
1. **持仓投资者**:
- 继续持有为主,可将MA20(1204.07)作为止损线
- 若股价回落至MA5-MA10区间(1217-1238)可适当加仓
- 短期若冲高至MA60(1263.65)遇阻,可考虑部分止盈
2. **观望投资者**:
- 等待回调至关键支撑位(MA20:1204或布林中轨:1204)再考虑进场
- 若股价直接突破MA60并站稳,可小仓位追涨
⚠️ **风险提示**:技术分析仅供参考,不构成投资建议。市场存在不确定性,需结合自身风险承受能力决策。

2.2 Sector Rotation Analysis Agent

Data Support: Industry/Concept sector daily quotes (90 industry + 374 concept) + Constituent stocks

Core Features:

FeatureDescriptionImplementation
Sector RankingRank by pct_chg, volume change, capital flowAggregate sector daily_index
Rotation TrendSectors with consecutive top N-day gains marked as "hot"Sliding window rank change analysis
Sector ComparisonMulti-sector price curves overlayExtract multiple sector close series
Constituent DistributionAdvance/decline count, limit up/down, median changeLink constituent daily data
Capital FlowVolume change trend, determine inflow/outflowVolume QoQ change analysis
Sector CorrelationConstituent stock overlap between two sectorsSet intersection/union ratio

Example Queries:

"Which industry sectors had the highest gains this week?"
"How has the semiconductor sector performed this month? Is capital flowing in or out?"
"How high is the overlap between AI and robotics concept constituents?"
"Which sectors had limit-down waves today?"

To-Do:

  • tools/sector_ranking.py — Sector ranking tool (Done)
  • tools/sector_rotation.py — Rotation trend identifier (Done)
  • tools/sector_compare.py — Sector comparison tool (Done)
  • tools/sector_detail.py — Sector deep analysis tool (Done)
  • agents/sector_agent.py — Sector analysis agent (Done)

Agent Demo:

$ python agents/sector_agent.py
============================================================
FinAssistant — 板块轮动分析智能体
============================================================
输入板块相关问题开始分析,输入 'quit' 退出
示例:
- 最近一周涨幅最大的行业板块有哪些?
- 半导体板块最近一个月资金是在流入还是流出?
- AI概念和机器人概念的成分股重叠度有多高?
- 今天哪些板块出现了跌停潮?
============================================================
你: 最近一周涨幅最大的行业板块有哪些?
FinAssistant:
[调用工具: get_sector_ranking]
[完成] 结果: === 行业板块涨跌幅排名 (2026-07-17) ===
Top 10:
排名 板块名称 涨跌幅(%) 成交额(亿)
1 通信设备 +5.23 312.45
2 半导体 +4.87 528.91
3 消费电子 +3.65 287.33
...
[调用工具: get_sector_top_gainers]
[完成] 结果: === 连续3天上涨的行业板块 ===
板块名称 连涨天数 累计涨幅(%)
半导体 3 +8.92
通信设备 3 +7.56
...
综合来看,最近一周涨幅最大的行业板块主要集中在科技领域:
1. **通信设备** (+5.23%) — 5G建设持续推进,板块领涨
2. **半导体** (+4.87%) — 国产替代逻辑强化,资金持续流入
3. **消费电子** (+3.65%) — 新品发布预期带动板块走强
其中半导体和通信设备已连续3天上涨,短期动能较强。
⚠️ 风险提示:板块轮动较快,追高需谨慎。以上分析仅供参考,不构成投资建议。

2.3 Cross-Data Correlation Analysis Agent

Data Support: Quotes + Constituents + Financial statements + News (Full data cross-correlation)

Core Features:

FeatureDescriptionImplementation
Stock→Sector MappingQuery which sectors a stock belongs to, recent performanceReverse lookup in constituent data
Sector→Financial AggregationAverage ROE, median PE, total revenue for sector constituentsLink constituent codes to financial statements
News→Quote CorrelationCompanies/sectors mentioned in news, link to recent price trendsNER entity recognition + code matching
Industry ChainInfer upstream/downstream relationships via concept overlapConstituent set similarity clustering
Leader EffectTop N stocks by market cap vs sector overall performanceMarket-cap weighted vs equal-weight index

Example Queries:

"Which concept sectors does BYD belong to? How are they performing?"
"What's the average PE and ROE for the semiconductor sector?"
"Any recent news about solar power? How are related sectors trending?"
"Find the top 5 stocks most correlated with CATL"

To-Do:

  • tools/stock_sector_mapping.py — Stock-sector mapping tool (Done)
  • tools/sector_financial_agg.py — Sector financial aggregation (Done)
  • tools/news_stock_linker.py — News-quote correlation tool (Done)
  • agents/correlation_agent.py — Correlation analysis agent (Done)

2.4 Financial Q&A Agent (RAG)

Data Support: Financial statements (4,593 stocks × multi-period) + Vector database (Milvus)

Core Features:

FeatureDescriptionImplementation
NL Financial Query"Which companies have gross margin > 50%" → SQL/Vector searchVectorize financial fields + structured query
Cross-stock ComparisonHorizontal comparison of financial indicators for same-industry companiesGroup by industry + indicator comparison
Multi-period TrendVertical comparison of same company across periodsTime series analysis + trend detection
Anomaly AlertCash flow plunge, receivables surge, goodwill impairmentThreshold/QoQ change detection
Financial Health ScoreComprehensive solvency, profitability, growth, operational abilityDuPont analysis system + weighted scoring

Example Queries:

"Which banks have positive operating cash flow for the past year?"
"Compare CATL and BYD's debt ratio trends"
"Which companies had gross margin drop > 10% last quarter?"
"Give me a DuPont analysis for Kweichow Moutai"
"Find companies with ROE > 20% for 3 consecutive years"

To-Do:

  • tools/financial_query.py — Financial data query tool (Done)
  • tools/financial_compare.py — Financial comparison tool (Done)
  • tools/financial_anomaly.py — Anomaly detection tool (Done)
  • tools/financial_score.py — Financial health scoring tool (Done)
  • agents/financial_agent.py — Financial Q&A agent (Done)
  • rag/financial_embedding.py — Financial statement vectorization

2.5 Daily Market Report Agent

Data Support: Full data (Quotes + Sectors + News + Financials)

Core Features:

FeatureDescriptionImplementation
Market OverviewMajor index changes, volume, advance/decline statsAggregate all market stock data
Sector Rotation SummaryTop gainers/losers, capital inflow/outflow Top5Sector ranking tool output
Anomaly DetectionLimit up/down, volume breakout, abnormal volatilityFilter conditions
News SummaryMarket-related important news, linked sectorsNews filtering + LLM summary
Watchlist ReportUser's watched stocks daily performance, announcementsPersonalized filtering
Trend AssessmentBased on recent N-day data, market sentiment judgmentMulti-indicator synthesis

Example Queries:

"Generate today's market morning briefing"
"Which stocks hit limit up today? Which sectors do they belong to?"
"How has market sentiment been this week?"
"How are my watchlist stocks performing today?"

To-Do:

  • tools/market_overview.py — Market overview tool (Done)
  • tools/abnormal_detector.py — Anomaly detection tool (Done)
  • tools/market_trend.py — Trend assessment tool (Done)
  • tools/watchlist_report.py — Watchlist report tool (Done)
  • tools/daily_digest.py — Daily report generator (Done, integrates all 6 modules)
  • agents/daily_report_agent.py — Daily report agent (Done)

2.6 Research Report Generation Agent

Data Support: Full data + LLM generation capabilities

Core Features:

FeatureDescriptionImplementation
Stock Deep ReportComprehensive fundamental + technical + valuation + industry positionCall previous tools + LLM long-text generation
Industry ResearchSector trends, constituent financials, industry chain analysisSector tools + Financial tools + LLM
Comparative Report2-3 same-industry companies multi-dimensional comparisonComparison tools + LLM
Event Impact AnalysisNews/policy impact on related sectors and stocksNews correlation + Historical analogy + LLM
Portfolio SuggestionRecommend sector/stock allocation based on risk preferenceOptimization algorithm + LLM

Example Queries:

"Write a deep research report on the semiconductor industry"
"Compare BYD, CATL, and LONGi Green Energy with a comparative analysis"
"Which A-share sectors are most affected by Fed rate hikes?"
"I prefer conservative investing, recommend some sector allocation plans"

To-Do:

  • tools/report_generator.py — Report generation tool (LLM + templates)
  • templates/ — Report templates (stock/industry/comparison/event)
  • agents/report_agent.py — Report generation agent
  • agents/portfolio_agent.py — Portfolio optimization agent

3. Data Assets

3.1 Data Overview

Data TypeVolumeSourceTime Range
SH Stock Daily Quotes2,308 stocksSina Finance (akshare)2026-01-01 ~ Present
SZ Stock Daily Quotes2,895 stocksSina Finance (akshare)2026-01-01 ~ Present
SH Company Info2,308 (Main 1,699 + STAR 609)SSE (akshare)-
SZ Company Info2,895SZSE (akshare)-
SH Financial Statements2,308 stocksSina Finance (akshare)Recent 3 years
SZ Financial Statements2,895 stocksSina Finance (akshare)Recent 3 years
Industry Sector Quotes90 sectorsTonghuashun (akshare)2026-01-01 ~ Present
Concept Sector Quotes374 sectorsTonghuashun (akshare)2026-01-01 ~ Present
Industry Constituents90 sectorsTonghuashun (DrissionPage)-
Concept Constituents374 sectorsTonghuashun (DrissionPage)-
Financial News-Tonghuashun 7x242026-01-01 ~ Present

3.2 MySQL Table Schema

Data is stored in Alibaba Cloud RDS MySQL with two databases: market_data (quotes/financials) and stock_news (news).

market_data.company_info — Company Basic Info

CREATETABLEcompany_info (
id INT AUTO_INCREMENT PRIMARY KEY COMMENT 'Auto-increment ID',
ts_code VARCHAR(20) NOT NULL COMMENT 'Stock code with suffix, e.g., 600000.SH',
symbol VARCHAR(10) NOT NULL COMMENT 'Stock code (numeric only)',
stock_name VARCHAR(50) COMMENT 'Stock short name',
full_name VARCHAR(100) COMMENT 'Company full name',
industry VARCHAR(50) COMMENT 'Industry, e.g., J Finance',
list_date VARCHAR(20) COMMENT 'Listing date, format YYYY-MM-DD',
market VARCHAR(5) COMMENT 'Market, SH=Shanghai SZ=Shenzhen',
updated_at VARCHAR(30) COMMENT 'Data update time',
UNIQUE KEY uk_ts_code (ts_code)
)

market_data.stock_kline — Stock Daily K-line

CREATETABLEstock_kline (
id BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT 'Auto-increment ID',
ts_code VARCHAR(20) NOT NULL COMMENT 'Stock code with suffix',
symbol VARCHAR(10) NOT NULL COMMENT 'Stock code (numeric only)',
trade_date VARCHAR(20) NOT NULL COMMENT 'Trade date, format YYYY-MM-DD',
open DOUBLE COMMENT 'Open price (CNY)',
close DOUBLE COMMENT 'Close price (CNY)',
high DOUBLE COMMENT 'High price (CNY)',
low DOUBLE COMMENT 'Low price (CNY)',
pre_close DOUBLE COMMENT 'Previous close (CNY)',
change_data DOUBLE COMMENT 'Price change (CNY)',
pct_chg DOUBLE COMMENT 'Change percentage (%)',
volume DOUBLE COMMENT 'Volume (shares)',
amount DOUBLE COMMENT 'Turnover (CNY)',
pe DOUBLE COMMENT 'P/E ratio',
pb DOUBLE COMMENT 'P/B ratio',
total_mv DOUBLE COMMENT 'Total market cap (100M CNY)',
total_share DOUBLE COMMENT 'Total shares',
float_share DOUBLE COMMENT 'Float shares',
circ_mv DOUBLE COMMENT 'Circulating market cap (100M CNY)',
ln_pctchg DOUBLE COMMENT 'Log return',
pe_ttm DOUBLE COMMENT 'P/E ratio (TTM)',
pe_static DOUBLE COMMENT 'Static P/E ratio',
pcf DOUBLE COMMENT 'Price-to-Cash-Flow ratio',
UNIQUE KEY uk_code_date (ts_code, trade_date),
KEY idx_trade_date (trade_date),
KEY idx_symbol (symbol)
)

market_data.stock_financial — Financial Statements

CREATETABLEstock_financial (
id BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT 'Auto-increment ID',
ts_code VARCHAR(20) NOT NULL COMMENT 'Stock code with suffix',
symbol VARCHAR(10) NOT NULL COMMENT 'Stock code (numeric only)',
statement_type VARCHAR(20) NOT NULL COMMENT 'Statement type: income/balance/cashflow',
report_date VARCHAR(20) NOT NULL COMMENT 'Report date, e.g., 20260331',
report_data JSON COMMENT 'Complete statement data (JSON)',
UNIQUE KEY uk_code_type_date (ts_code, statement_type, report_date),
KEY idx_symbol (symbol),
KEY idx_report_date (report_date),
KEY idx_statement_type (statement_type)
)

Financial fields vary significantly across industries (banking vs manufacturing), hence JSON storage for complete statement data.

market_data.sector_industry_daily / sector_concept_daily — Sector Daily K-line

CREATETABLEsector_industry_daily (
id BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT 'Auto-increment ID',
sector_name VARCHAR(50) NOT NULL COMMENT 'Sector name',
sector_code VARCHAR(20) NOT NULL COMMENT 'Sector code',
trade_date VARCHAR(20) NOT NULL COMMENT 'Trade date',
open DOUBLE COMMENT 'Open',
high DOUBLE COMMENT 'High',
low DOUBLE COMMENT 'Low',
close DOUBLE COMMENT 'Close',
vol DOUBLE COMMENT 'Volume',
amount DOUBLE COMMENT 'Turnover',
pct_chg DOUBLE COMMENT 'Change (%)',
change_data DOUBLE COMMENT 'Point change',
pct_change DOUBLE COMMENT 'Change (backup)',
turnover_rate DOUBLE COMMENT 'Turnover rate',
UNIQUE KEY uk_code_date (sector_code, trade_date),
KEY idx_trade_date (trade_date),
KEY idx_sector_name (sector_name)
)

market_data.sector_industry_cons / sector_concept_cons — Sector Constituents

CREATETABLEsector_industry_cons (
id BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT 'Auto-increment ID',
sector_name VARCHAR(50) NOT NULL COMMENT 'Sector name',
sector_code VARCHAR(20) NOT NULL COMMENT 'Sector code',
stock_code VARCHAR(10) NOT NULL COMMENT 'Stock code',
stock_name VARCHAR(50) COMMENT 'Stock name',
UNIQUE KEY uk_sector_stock (sector_code, stock_code),
KEY idx_sector_name (sector_name),
KEY idx_stock_code (stock_code)
)

stock_news.news_em — Eastmoney 7x24 News

CREATETABLEnews_em (
id INT AUTO_INCREMENT PRIMARY KEY COMMENT 'Auto-increment ID',
title VARCHAR(500) NOT NULL COMMENT 'News title',
digest TEXT COMMENT 'News digest',
publish_time VARCHAR(30) COMMENT 'Publish time',
url VARCHAR(500) COMMENT 'News URL',
crawl_time VARCHAR(30) COMMENT 'Crawl time',
UNIQUE KEY uk_title_time (title, publish_time)
)

stock_news.news_ths — Tonghuashun Financial News

CREATETABLEnews_ths (
id INT AUTO_INCREMENT PRIMARY KEY COMMENT 'Auto-increment ID',
news_id VARCHAR(20) NOT NULL COMMENT 'News ID',
title VARCHAR(500) NOT NULL COMMENT 'News title',
digest TEXT COMMENT 'News digest',
url VARCHAR(500) COMMENT 'News URL',
tags VARCHAR(500) COMMENT 'Tags (comma separated)',
ctime_str VARCHAR(30) COMMENT 'Publish time',
source VARCHAR(100) COMMENT 'Source',
crawl_time VARCHAR(30) COMMENT 'Crawl time',
UNIQUE KEY uk_news_id (news_id),
KEY idx_ctime (ctime_str)
)

3.3 Data Import Scripts

ScriptTarget TableDescription
import_company_info_to_mysql.pymarket_data.company_infoSH/SZ company info
import_kline_to_mysql.pymarket_data.stock_klineStock daily K-line (560K+ rows)
import_financial_to_mysql.pymarket_data.stock_financialFinancial statements (170K+ rows)
import_sector_to_mysql.pymarket_data.sector_*_dailySector daily K-line
import_sector_cons_to_mysql.pymarket_data.sector_*_consSector constituents
import_news_em_to_mysql.pystock_news.news_emEastmoney news
import_news_ths_to_mysql.pystock_news.news_thsTonghuashun news

3.4 Data Collection Scripts

ScriptPurposeSource
crawl_sh_stock_data.pySH stock quotes + company infoSina Finance / SSE
crawl_sz_stock_data.pySZ stock quotes + company infoSina Finance / SZSE
crawl_financial_reports.pyFinancial statementsSina Finance
crawl_sector_data.pySector daily quotes (Industry + Concept)Tonghuashun (akshare)
crawl_sector_cons.pySector constituentsSina Finance (akshare)
crawl_sector_cons_ths.pySector constituents (backup)Tonghuashun (DrissionPage)
crawl_news_ths.pyFinancial newsTonghuashun 7x24 API
crawl_news_em.pyEastmoney 7x24 news (scheduled)Eastmoney (akshare)

3.5 Known Issues

IssueDescription
Eastmoney API Blockedpush2his.eastmoney.com completely unavailable
Tonghuashun IP BlockedFrequent crawling triggers Nginx 403 block
Inconsistent Sector SourcesQuotes from THS, constituents partially from Sina, names may not match
SH Company Missing IndustrySSE API doesn't provide industry field

4. AgentScope 2.0 Implementation

4.1 Architecture

User Query → FastAPI → Agent (system_prompt + model + toolkit + middlewares)
↓
Toolkit
├── ToolGroup("Stock Analysis") → tools/stock_query.py + skills/stock-analysis/
├── ToolGroup("Sector Analysis") → tools/sector_query.py + skills/sector-rotation/
├── ToolGroup("Financial Q&A") → tools/financial_query.py + skills/financial-qa/
├── ToolGroup("Daily Report") → tools/news_query.py + skills/daily-report/
└── ToolGroup("Research Report") → tools/indicators.py + skills/research-report/

4.2 Directory Structure

FinAssistant/
├── config.py # Global config (paths, model, API Key)
├── main.py # FastAPI service entry
├── main_agent.py # Single agent script (no server, direct chat)
├── core/
│ ├── agent_setup.py # Agent + Toolkit initialization
│ └── middleware.py # Financial scenario middleware
├── tools/ # Tool functions
│ ├── __init__.py
│ ├── stock_query.py # Stock quote/company info query
│ ├── sector_query.py # Sector quote/constituent query
│ ├── financial_query.py # Financial statement query & analysis
│ ├── news_query.py # News query
│ └── indicators.py # Technical/fundamental indicator calculation
├── skills/ # Skill documents (SKILL.md)
│ ├── stock-analysis/SKILL.md
│ ├── sector-rotation/SKILL.md
│ ├── financial-qa/SKILL.md
│ ├── daily-report/SKILL.md
│ └── research-report/SKILL.md
├── data/ # Existing data (don't modify)
└── data_to_mysql_and_milvus/ # Existing crawler scripts (don't modify)

4.3 Implementation Steps

Step 1: config.py

Global configuration for data paths, model config, API keys.

Step 2: tools/ Tool Functions

Each function is async def, returns ToolChunk. Docstring is the tool description — LLM decides when to call based on docstring.

Step 3: skills/SKILL.md Skill Documents

Each skill directory has a SKILL.md with trigger conditions, dependent tools, and execution flow.

Step 4: core/middleware.py Middleware

MiddlewarePurpose
InputValidationMiddlewareFilter non-financial queries
ToolCallAuditMiddlewareLog tool calls to traces/
PerformanceMonitorMiddlewareMonitor inference rounds, latency, tokens
ContextEnrichmentMiddlewareInject current date, trading day context

Step 5: core/agent_setup.py Agent Initialization

Assemble model, tools, toolkit, and agent with middleware.

Step 6: main.py Service Entry

FastAPI service with OpenAI-compatible /v1/chat/completions endpoint.


5. Implemented Tools

tools/stock_fundamental.py — Fundamental Indicator Calculator

Calculates fundamental indicators from MySQL market_data.stock_financial table.

Core Functions:

FunctionDescription
calc_fundamental_indicators(ts_code, report_date=None)Calculate single-period indicators
calc_fundamental_trend(ts_code, periods=4)Calculate recent N-period trend
get_financial_data(ts_code, report_date=None)Get raw statement data
get_report_dates(ts_code, limit=8)Get report date list

Calculated Indicators:

IndicatorFormulaData Source
ROENet Profit / Equity × 100%Income + Balance Sheet
Gross Margin(Revenue - COGS) / Revenue × 100%Income Statement
Net MarginNet Profit / Revenue × 100%Income Statement
Debt RatioTotal Liabilities / Total Assets × 100%Balance Sheet
Cash Flow / Net ProfitOperating Cash Flow / Net ProfitCash Flow + Income
Revenue YoY Growth(Current - Prior Year) /Prior Year
Net Profit YoY Growth(Current - Prior Year) /Prior Year
Revenue QoQ Growth(Current Q - Prior Q) /Prior Q
Net Profit QoQ Growth(Current Q - Prior Q) /Prior Q

Special Handling:

  • Auto bank detection: Via balance sheet fields (loans, deposits)
  • Bank field mapping: Revenue = Net Interest Income + Fee Income; COGS = Interest Expense + Fee Expense
  • YoY calculation: Cumulative values vs same quarter last year (2026Q1 vs 2025Q1)
  • QoQ calculation: Single-quarter values (Q4 = Annual - 9-month cumulative)

Usage:

fromtools.stock_fundamentalimportcalc_fundamental_indicators, calc_fundamental_trend# Single periodresult=calc_fundamental_indicators('600519.SH')
print(result['ROE'], result['毛利率'], result['营收同比增长率'])
# Trend (recent 4 periods)trend=calc_fundamental_trend('600519.SH', periods=4)
fortintrend['trend']:
print(t['report_date'], t['ROE'], t['营收同比增长率'])

tools/stock_valuation.py — Valuation Percentile Analyzer

Calculates PE/PB/PCF percentile in 1-year history from market_data.stock_kline table.

Core Functions:

FunctionDescription
calc_valuation_percentile(ts_code, days=365)Calculate valuation percentile, return structured data
calc_valuation_summary(ts_code, days=365)Generate formatted valuation summary
get_valuation_history(ts_code, days=365)Get N-day valuation history
get_latest_valuation(ts_code)Get latest day valuation data

Valuation Indicators:

IndicatorDescriptionSource
PE_TTMPrice-to-Earnings (Trailing Twelve Months)stock_kline.pe_ttm
PBPrice-to-Bookstock_kline.pb
PCFPrice-to-Cash-Flowstock_kline.pcf

Percentile Rules:

PercentileLevelMeaning
< 20%UndervaluedAt historical low, potentially undervalued
20% - 40%Below AverageBelow historical median
40% - 60%FairAt historical median range
60% - 80%Above AverageAbove historical median
> 80%OvervaluedAt historical high, potentially overvalued

Usage:

fromtools.stock_valuationimportcalc_valuation_percentile, calc_valuation_summary# Get structured dataresult=calc_valuation_percentile('600519.SH')
print(f"PE_TTM: {result['pe_ttm']}, Percentile: {result['pe_ttm_percentile']}%, {result['pe_ttm_level']}")
# Get formatted summaryprint(calc_valuation_summary('600519.SH'))

tools/stock_technical.py — Technical Indicator Calculator

Calculates MA/MACD/RSI/BOLL/KDJ indicators from MySQL market_data.stock_kline table.

Core Functions:

FunctionDescription
calc_technical_indicators(ts_code, days=120)Calculate all technical indicators
calc_technical_summary(ts_code, days=120)Generate formatted summary
get_kline_data(ts_code, days=120)Get K-line data from MySQL

Technical Indicators:

IndicatorFormulaUsage
MA(5/10/20/60)Average of last N closing pricesTrend: Price above MA = bullish; MA crossover = buy/sell signal
MACDDIF = EMA(12) - EMA(26); DEA = EMA(DIF,9); Histogram = (DIF-DEA)×2Golden cross (DIF>DEA) = buy; Dead cross = sell
RSI(6/12/24)RS = Avg Gain / Avg Loss; RSI = 100 - 100/(1+RS)>80 = overbought; <20 = oversold
BOLL(20,2)Upper = MA+2σ; Middle = MA; Lower = MA-2σTouch upper = overbought; Touch lower = oversold
KDJ(9,3,3)RSV, K = 2/3K+1/3RSV, D = 2/3D+1/3K, J = 3K-2DK>80 = overbought; K<20 = oversold; K/D crossover

Signal Interpretation:

SignalMAMACDRSIBOLLKDJ
BullishMA5>MA10>MA20 (Bull alignment)DIF>DEA, Histogram>0RSI<20 (Oversold)Price bounces off lower bandK/D golden cross in oversold zone
BearishMA5<MA10<MA20 (Bear alignment)DIF<DEA, Histogram<0RSI>80 (Overbought)Price falls from upper bandK/D dead cross in overbought zone

Multi-indicator Confirmation:

Buy signals (need 2-3):

  • Price above MA20, MA bullish alignment (MA5>MA10>MA20)
  • MACD golden cross (DIF crosses above DEA)
  • RSI rebounds from oversold (<20 → >20)
  • Price bounces off Bollinger lower band
  • KDJ golden cross in oversold zone

Sell signals (need 2-3):

  • Price below MA20, MA bearish alignment (MA5<MA10<MA20)
  • MACD dead cross (DIF crosses below DEA)
  • RSI enters overbought (>80) then falls
  • Price falls from Bollinger upper band
  • KDJ dead cross in overbought zone

Usage:

fromtools.stock_technicalimportcalc_technical_indicators, calc_technical_summary# Get structured dataresult=calc_technical_indicators('600519.SH')
print(f"Close: {result['close']}, MA5: {result['ma5']}, MACD: {result['macd_signal']}")
# Get formatted summaryprint(calc_technical_summary('600519.SH'))

5.5 Sector Analysis Tools

tools/sector_ranking.py — Sector Ranking Tool

Calculates sector rankings from MySQL sector_industry_daily / sector_concept_daily tables.

Core Functions:

FunctionDescription
get_sector_ranking(sector_type, trade_date, top_n, sort_by)Sector ranking by pct_chg/amount/volume
get_sector_top_gainers(sector_type, days, top_n)Sectors with consecutive N-day gains
get_sector_top_losers(sector_type, days, top_n)Sectors with consecutive N-day losses
get_sector_summary(sector_type, trade_date)Market overview (advance/decline, limit up/down)

Usage:

fromtools.sector_rankingimportget_sector_ranking, get_sector_top_gainers, get_sector_summary# Top 10 industry sectors by pct_chgprint(get_sector_ranking(sector_type='industry', top_n=10))
# Sectors rising for 3 consecutive daysprint(get_sector_top_gainers(sector_type='industry', days=3))
# Industry sector market overviewprint(get_sector_summary(sector_type='industry'))

tools/sector_rotation.py — Rotation Trend Identifier

Analyzes sector momentum and capital rotation direction through short-term vs medium-term performance comparison.

Core Functions:

FunctionDescription
get_sector_momentum(sector_type, short_days, long_days, top_n)Momentum analysis — short vs medium term, momentum score
get_sector_rotation(sector_type, short_days, long_days, top_n)Rotation identification — capital inflow/outflow sectors
get_sector_strength(sector_type, days, top_n)Strength ranking — composite score of gains, up-days, volume
get_hot_cold_sectors(sector_type, days)Hot/cold classification — hot/warm/flat/cold categories

Usage:

fromtools.sector_rotationimportget_sector_momentum, get_sector_rotation, get_hot_cold_sectors# Industry sector momentum (3-day short vs 10-day medium)print(get_sector_momentum(sector_type='industry', short_days=3, long_days=10))
# Sector rotation (capital inflow/outflow)print(get_sector_rotation(sector_type='industry'))
# Hot/cold sector classificationprint(get_hot_cold_sectors(sector_type='industry', days=5))

tools/sector_compare.py — Sector Comparison Tool

Multi-sector price curve overlay comparison with normalization and ASCII trend charts.

Core Functions:

FunctionDescription
compare_sectors(sector_names, sector_type, days)Multi-sector cumulative return comparison (table + ASCII chart)
compare_sector_trend(sector_names, sector_type, days)Trend strength comparison with conclusion

Usage:

fromtools.sector_compareimportcompare_sectors, compare_sector_trend# Compare Baijiu vs Power vs Banks over 20 daysprint(compare_sectors(['白酒', '电力', '银行'], sector_type='industry', days=20))
# Trend strength comparison with conclusionprint(compare_sector_trend(['白酒', '电力', '银行', '证券'], days=20))

tools/sector_detail.py — Sector Deep Analysis Tool

Links constituent stock data to provide internal sector structure analysis.

Core Functions:

FunctionDescription
get_constituent_distribution(sector_name, sector_type, trade_date)Constituent distribution — advance/decline, limit up/down, median change, top/bottom 5
get_sector_money_flow(sector_name, sector_type, days)Capital flow analysis — volume trend, price-volume coordination, inflow/outflow
get_sector_correlation(sector_name1, sector_name2, sector_type)Sector correlation — Jaccard coefficient, overlapping constituents

Usage:

fromtools.sector_detailimportget_constituent_distribution, get_sector_money_flow, get_sector_correlation# Baijiu sector constituent distributionprint(get_constituent_distribution('白酒', sector_type='industry'))
# Power sector capital flow analysisprint(get_sector_money_flow('电力', sector_type='industry', days=10))
# Baijiu vs Beer sector correlationprint(get_sector_correlation('白酒', '啤酒', sector_type='industry'))

tools/news_stock_linker.py — News-Stock Linker

Links news headlines to mentioned companies/sectors and correlates with their recent price trends.

Core Functions:

FunctionDescription
find_news_by_keyword(keyword, limit)Search news by keyword (title/digest fuzzy match)
search_news_with_market(keyword, limit, days_before, days_after)Search news and auto-correlate with matched stocks/sectors price trends

Usage Example:

fromtools.news_stock_linkerimportfind_news_by_keyword, search_news_with_market# Search news by keywordprint(find_news_by_keyword('半导体', limit=5))
# Search news and correlate with market dataprint(search_news_with_market('贵州茅台', limit=3, days_before=3, days_after=3))

5.6 Sector Analysis Agent

agents/sector_agent.py — Sector Analysis Agent

Integrates sector ranking, rotation, comparison, and deep analysis tool groups for sector rotation analysis.

Tool Group Structure:

Tool GroupToolsDescription
sector-rankingget_sector_ranking / get_sector_top_gainers / get_sector_top_losers / get_sector_summarySector ranking
sector-rotationget_sector_momentum / get_sector_rotation / get_sector_strength / get_hot_cold_sectorsRotation analysis
sector-comparecompare_sectors / compare_sector_trendSector comparison
sector-detailget_constituent_distribution / get_sector_money_flow / get_sector_correlationDeep analysis

Run:

python agents/sector_agent.py

5.7 Correlation Analysis Agent

agents/correlation_agent.py — Correlation Analysis Agent

Integrates stock-sector mapping, sector financial aggregation, and news-market correlation tool groups for cross-data analysis.

Tool Group Structure:

Tool GroupToolsDescription
stock-sectorfind_stock_sectorsStock-sector mapping
sector-financeget_sector_financial_agg / get_sector_valuation_statsSector financial aggregation, valuation distribution
news-marketfind_news_by_keyword / search_news_with_marketNews search, news-market correlation

Run:

python agents/correlation_agent.py

5.8 Financial Health Scoring Tool

tools/financial_score.py — Financial Health Scoring Tool

Computes a four-dimension composite financial health score (0-100) with rating (Excellent/Good/Fair/Poor).

Scoring Dimensions:

DimensionWeightIndicators
Profitability30%ROE(40%) + Gross Margin(30%) + Net Margin(30%)
Growth25%Revenue YoY Growth(50%) + Net Profit YoY Growth(50%)
Safety25%Debt Ratio(40%) + Cash Flow/NP(35%) + AR Ratio(25%)
Quality20%Deducted NP Ratio(50%) + Cash Flow Consistency(50%)

Anomaly Deduction: HIGH -5pts, MEDIUM -2pts, max -15pts.

Core Functions:

FunctionDescription
calc_financial_score(ts_code, report_date=None)Calculate single stock financial health score
format_financial_score(ts_code, report_date=None)Generate formatted Markdown output
score_sector(sector_name, sector_type, top_n)Batch score sector constituents

Run:

python tools/financial_score.py --ts_code 600519.SH
python tools/financial_score.py --sector 白酒 --top_n 10
python tools/financial_score.py --ts_codes 600519.SH,300750.SZ,601318.SH

5.9 Financial Q&A Agent

agents/financial_agent.py — Financial Q&A Agent

Integrates fundamental indicators, trend analysis, comparison, anomaly detection, financial scoring, and batch screening tool groups for complex financial Q&A.

Tool Group Structure:

Tool GroupToolsDescription
fundamentalcalc_fundamental_indicators / calc_fundamental_trend / get_financial_data / get_report_datesFinancial indicator calculation
comparecompare_companies / compare_periodsFinancial comparison and trends
score-anomalyformat_financial_score / calc_financial_score / detect_anomaliesScoring and anomaly detection
screeningscreen_cashflow_positive_stocks / screen_margin_decline_stocks / screen_roe_stocksBatch screening
queryquery_financial_dataFinancial data query

Example Queries:

"Which banks have positive operating cash flow for the past year?"
"Compare CATL and BYD's debt ratio trends"
"Which companies had gross margin drop > 10% last quarter?"
"Give me a DuPont analysis for Kweichow Moutai"
"Find companies with ROE > 20% for 3 consecutive years"

Run:

python agents/financial_agent.py

5.10 Daily Market Report Agent

agents/daily_report_agent.py — Daily Market Report Agent

Integrates market overview, trend assessment, sector rotation, anomaly detection, news correlation, and watchlist report tool groups for natural language Q&A on daily market briefings.

Tool Group Structure:

Tool GroupToolsDescription
market-overviewget_market_overview / format_market_overviewMarket overview
market-trendanalyze_market_trend / format_market_trendTrend assessment
sector-analysisget_sector_ranking / get_sector_rotation / get_hot_cold_sectors etc. (8 tools)Sector analysis
abnormal-detectiondetect_abnormal / format_abnormalAnomaly detection
newsfind_news_by_keyword / search_news_with_marketNews search
watchlistget_watchlist_report / format_watchlist_reportWatchlist report
daily-digestgenerate_daily_digestOne-click daily report

Example Queries:

"Generate today's market morning briefing"
"Which stocks hit limit up today? Which sectors do they belong to?"
"How has market sentiment been this week?"
"Which sectors are seeing capital inflow?"
"What important news is there today?"
"How are my watchlist stocks performing?"

Run:

python agents/daily_report_agent.py

5.11 Daily Market Report Tools

tools/market_overview.py — Market Overview Tool

Aggregates all market stock data to compute daily market overview (advance/decline counts, limit up/down, turnover, etc.).

Core Functions:

FunctionDescription
get_market_overview(trade_date=None)Get market overview as structured data
format_market_overview(trade_date=None)Generate formatted Markdown output

Output Metrics:

MetricDescription
Advance/DeclineUp/down/flat counts and percentages
Limit Up/DownMain board >=9.9%, ChiNext/STAR >=19.9%
Total TurnoverMarket-wide turnover (100M CNY)
Avg/Median ChangeOverall market change level
Market SentimentStrong rally/Bullish/Neutral/Bearish/Weak decline

Run:

python tools/market_overview.py
python tools/market_overview.py --trade_date 20260801

tools/abnormal_detector.py — Anomaly Detection Tool

Detects daily market anomalies: limit up/down stocks, volume breakouts, abnormal price movements, sector anomalies.

Core Functions:

FunctionDescription
detect_abnormal(trade_date=None)Detect anomalies, return structured data
format_abnormal(trade_date=None)Generate formatted Markdown output

Detection Types:

TypeCondition
Limit Up/DownMain board >=9.9%, ChiNext/STAR >=19.9%
Volume BreakoutVolume ratio >3 AND gain >3% (ratio = current vol / 20-day avg vol)
Price Surge
Sector Anomaly

Run:

python tools/abnormal_detector.py
python tools/abnormal_detector.py --trade_date 20260801

tools/market_trend.py — Trend Assessment Tool

Multi-dimensional market sentiment analysis based on recent N-day data.

Core Functions:

FunctionDescription
analyze_market_trend(days=5)Analyze market trend, return structured data
format_market_trend(days=5)Generate formatted Markdown output

Scoring Dimensions (20 pts each, 100 total):

DimensionSourceLogic
Advance/Decline Ratiostock_kline 5-dayAverage advancing stock ratio
Limit Up/Down Ratiostock_kline latestLimit up / (up + down + 1)
Turnover Trendstock_kline 5-dayRecent 5d vs prior 5d, volume expansion/contraction
Sector Rotationsector_industry_dailyAdvancing sector ratio
Consecutive Trendstock_kline 5-dayConsecutive up/down days

Sentiment Mapping: >=75 Optimistic / >=60 Mildly Bullish / >=40 Neutral / >=25 Mildly Bearish / <25 Pessimistic

Run:

python tools/market_trend.py
python tools/market_trend.py --days 10

tools/watchlist_report.py — Watchlist Report Tool

Personalized daily report for user-watched stocks: daily performance, 5-day change, related news.

Core Functions:

FunctionDescription
get_watchlist_report(ts_codes, trade_date=None)Get watchlist report as structured data
format_watchlist_report(ts_codes, trade_date=None)Generate formatted Markdown output

Report Content:

ModuleDescription
Daily PerformanceClose price, change %, turnover
5-Day ChangeCumulative change over 5 trading days
Related NewsSearch news by stock name (max 3 per stock)

Watchlist Config: Edit tools/watchlist_config.json to set default watchlist.

Run:

python tools/watchlist_report.py --ts_codes 600519.SH,300750.SZ
python tools/watchlist_report.py # Use default from watchlist_config.json

tools/daily_digest.py — Daily Report Generator (Enhanced)

Generates complete daily market briefing by integrating all 6 modules.

Core Functions:

FunctionDescription
generate_daily_digest(trade_date=None, watchlist=None)Generate complete daily report (Markdown)

Report Structure:

SectionModuleSource
1Market Overviewmarket_overview.py
2Trend Assessmentmarket_trend.py
3Sector Rotationsector_ranking.py + sector_rotation.py
4Market Anomaliesabnormal_detector.py
5Important Newsnews_stock_linker.py
6Watchlist Report (optional)watchlist_report.py

Run:

python tools/daily_digest.py
python tools/daily_digest.py --trade_date 20260801
python tools/daily_digest.py --watchlist 600519.SH,300750.SZ

5.12 Tool Function Mapping

Existing langgraph_getdata/New tools/Description
query_market_data_day_k.pystock_query.pyStock K-line query
query_industry_index_market.pysector_query.pySector quote query
query_industry_component_list.pysector_query.pySector constituents
query_concept_dc_day.pysector_query.pyConcept sector quotes
query_concept_dc_stock.pysector_query.pyConcept sector constituents
query_fin_account.pyfinancial_query.pyFinancial statement query (Done)
(None)news_query.pyNews query (New)
(None)stock_fundamental.pyFundamental indicators (Done)
(None)stock_valuation.pyValuation percentile (Done)
(None)stock_technical.pyTechnical indicators (Done)
(None)stock_sector_mapping.pyStock-sector mapping (Done)
(None)sector_financial_agg.pySector financial aggregation (Done)
(None)news_stock_linker.pyNews-stock correlation (Done)
(None)financial_score.pyFinancial health scoring (Done)
(None)sector_data.pySector data utilities (Done)
(None)market_overview.pyMarket overview tool (Done)
(None)abnormal_detector.pyAnomaly detection tool (Done)
(None)market_trend.pyTrend assessment tool (Done)
(None)watchlist_report.pyWatchlist report tool (Done)
(None)daily_digest.pyDaily report generator (Done)

5.13 Dependencies

pip install agentscope>=2.0.3 fastapi uvicorn

About

Built on professional finance knowledge, it provides stock diagnostics, sector index analysis, investment Q&A and news insights to help investors capture market opportunities efficiently.

Resources

Stars

5 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages