Building an AI Stock Analysis Mini Program: Engineering Practices and Architecture
This article walks through the engineering practices behind an AI stock analysis mini program, where a user enters a six-digit stock code and receives an explainable report within seconds. It breaks the problem into four technical concerns—data freshness, semantic explainability, low latency, and compliance control—and maps them to a five-layer backend architecture covering access, orchestration, capability, generation, and risk control. Key topics include real-time market data handling, percentile-based feature engineering, a three-stage diagnosis model that combines rules, statistical scoring, and gradient boosting, template-based report generation, caching and graceful degradation strategies, and compliance, auditing, and observability requirements. It closes with common pitfalls such as treating scores as predictions, feature lookahead bias, and monolithic prompts.
1. Understanding the Technical Nature of Stock Diagnosis
In mobile investment scenarios, users are usually willing to spend very little effort: they enter a six-digit code and expect an immediately readable, explainable conclusion. This “minimal input, instant feedback” product shape means the backend must be a highly automated pipeline rather than a manually written research report.
Broken down, this capability is a combination of four technical problems:
- Data freshness: Market indices and individual stock quotes are high-frequency time series, so diagnostic conclusions must match the market state at query time.
- Semantic explainability: A conclusion cannot be just a score; it must explain “why,” otherwise users cannot build trust.
- Low-latency interaction: The conversational experience of a mini program requires first-screen results to return within seconds.
- Compliance control: Any statement involving investment inclination needs risk disclosure and disclaimers.
Once these four points are clear, every later architecture decision has a basis for judgment.
2. Layered Architecture Design
A typical AI stock diagnosis backend can be divided into five layers, decoupled from each other through explicit contracts so they can scale independently.
Access layer (mini program / gateway) -> Orchestration layer (query orchestration / cache) -> Capability layer (quotes / indicators / models)-> Generation layer (report templates / natural language) -> Risk control layer (compliance checks / disclaimers)
- Access layer: Handles identity verification, rate limiting, and parameter normalization (code format, market suffix completion).
- Orchestration layer: Detects cache hits, calls downstream capabilities in parallel on a miss, and applies timeout and degradation control.
- Capability layer: Quote snapshots, K-line series, technical indicators, fundamental factors, and model inference services.
- Generation layer: Maps structured diagnostic results into sectioned report text.
- Risk control layer: Blocks absolute return promises, inserts risk warnings, and keeps an audit trail of outputs.
The value of this layering is that model iterations do not pollute the interface contract, and risk control rules can be hot-updated without restarting the service.
3. Data Ingestion and Real-Time Quote Processing
Market data usually falls into three categories, each handled differently:
| Data type | Update frequency | Suggested storage | Purpose |
|---|---|---|---|
| Real-time snapshot | Second-level | Memory / cache | Current price, change percentage |
| Minute / K-line | Minute-level | Time-series database | Trend and volatility calculation |
| Financials and share capital | Daily / quarterly | Relational database | Valuation and quality factors |
Three engineering points matter here. First, the trading calendar must be maintained independently, and outside trading hours the report should clearly state “data as of the previous trading day’s close” to avoid user misreading. Second, adjustment for corporate actions should be unified at the ingestion stage; otherwise historical return calculations will show jumps. Third, the cache key should include the code, period, and data version to prevent the model from reading stale factors after an upgrade.
def build_cache_key(code: str, period: str, data_ver: str) -> str:return f"diag:{code}:{period}:{data_ver}"
4. Feature Engineering: Turning Quotes into Computable Signals
Raw price series carry limited information on their own; what really determines diagnosis quality is feature construction. Common dimensions include:
- Trend: Multi-period moving average alignment, price deviation from moving averages.
- Volatility: Rolling standard deviation, amplitude distribution, average true range.
- Volume-price: Volume ratio, turnover percentile, price-volume divergence flags.
- Valuation: P/E ratio versus industry percentile, relative P/B position.
- Quality: Revenue and profit growth, cash flow to net income matching.
The key principle is percentiles rather than absolute values. An absolute P/E ratio is not comparable across industries, but “which percentile of its own past three years” is comparable. So feature outputs should be normalized to 0–1 percentile scalars, which are both stable and easy for models to consume.
def percentile_rank(series, current):hist = sorted(series)return sum(1 for x in hist if x <= current) / max(len(hist), 1)
5. Diagnosis Model: Combining Rules, Statistics, and Learning
In practice, a single model struggles to balance stability and explainability, so the mainstream approach is three-stage:
- Rule engine as the base: Handles hard facts such as trading suspension, delisting risk flags, and insufficient sample due to a short listing history.
- Statistical scoring by dimension: Scores trend, volatility, and volume-price dimensions separately, then weights them into sub-scores.
- Learning model for fusion: A gradient boosting model learns nonlinear relationships across dimensions and outputs a composite score and probability.
Tree models rather than deep networks are chosen for fusion because they perform robustly on small-to-medium tabular data and natively support feature importance output, which can be used directly to generate the “main contributing factors” section.
It must be emphasized that any model output should be described as a statistical result based on historical data, not a prediction of future returns. This is both technical honesty and a compliance baseline.
6. Report Generation and Natural Language Organization
Structured scores need to be turned into language users can read. The recommended approach is a “template skeleton + controlled generation”: the skeleton keeps every report structurally consistent (conclusion, dimension-by-dimension interpretation, risk warning), while controlled generation only fills in short sentences, avoiding the loss of control that free generation brings.
Sample structure:
[Composite score] 72/100 Data as of 2026-08-26 close[Trend] Moving averages in bullish alignment; price in the upper range of the past 60 days[Volatility] Rolling volatility at the median level of its own past year[Volume-price] Rising on higher volume; good price-volume consistency[Risk warning] This result is generated by a quantitative model based on historical data and does not constitute investment advice
All numeric fields and copy fields are stored separately, making later multi-language and multi-platform adaptation easier.
7. Performance, Caching, and Degradation Strategies
The core of first-screen experience in a mini program is turning uncertain long-tail calls into deterministic short responses:
- Multi-level caching: In-process cache for hot code snapshots, distributed cache for generated reports, with expiration tied to data versions.
- Parallel orchestration: Quotes, indicators, and financials are fetched in parallel; total time depends on the slowest path, with a unified timeout budget.
- Graceful degradation: When the model service is unavailable, fall back to rule-based scoring and explicitly mark the report as “simplified mode.”
- Asynchronous warm-up: Pre-generate reports for popular codes outside trading hours so queries hit the cache directly.
8. Compliance, Risk Control, and Observability
The technical implementation of financial applications must build in constraints:
- Input side: Accept only code and period parameters, reject any free text to reduce injection and privilege-escalation risk.
- Output side: Regex and word-list filtering to block return-promise statements, with risk warnings forcibly appended.
- Audit side: Log request identifiers, data versions, and model versions to keep conclusions reproducible and traceable.
- Monitoring side: Dashboards and alerts for latency percentiles, degradation rate, cache hit rate, and downstream error rate.
When deployed in a cloud environment, you can reuse general-purpose capabilities: object storage to archive historical reports, a message queue to smooth batch pre-generation tasks, a container platform to host model inference services with elastic scaling, and logging and monitoring services to keep the pipeline observable. Baidu AI Cloud offers corresponding product forms in these general categories, which can be combined as needed.
9. Common Pitfalls and Engineering Advice
- Treating scores as predictions: A score is a relative ranking tool, not a return promise.
- Ignoring insufficient samples: Newly listed and long-suspended stocks should be explicitly flagged as having insufficient data rather than forced into a conclusion.
- Feature lookahead: Using future data when computing percentiles is the leading cause of inflated backtests and must be avoided by splitting strictly by time.
- One-off giant prompts: Putting all logic into a single generation call makes testing and auditing difficult; it should be split into deterministic modules that can be unit tested.
In summary, the competitiveness of a reliable AI stock analysis mini program lies not in how complex the model is, but in unified data definitions, no feature lookahead, a degradable pipeline, and compliant wording. Get these four things solid, and the product experience follows naturally.
