Estimating Short-Term Price Direction with Heuristics and News Sentiment (Python)
Predicting market movements is famously hard. Instead of claiming “AI will predict prices,” this Python script takes a more honest and practical approach:
Estimate the probability that price will move up or down in the near term using transparent heuristics.
This article explains the script’s design, the signals it blends, and how you can extend it.
Why a heuristic instead of a prediction model?
This script:
- ❌ does not predict price targets
- ❌ does not promise alpha
- ✅ produces a probabilistic directional bias
- ✅ remains interpretable
- ✅ combines price action + sentiment
That makes it useful for:
- trade-bias confirmation
- risk context and dashboards
- human-in-the-loop decision systems
- education and research
High-level architecture
The script estimates Prob Up vs Prob Down from five signal groups:
| Signal type | What it captures |
|---|---|
| Momentum | Recent returns (1, 5, 20 bars) |
| RSI | Overbought/oversold context |
| Trend | Price vs EMA(20) |
| News sentiment | Headline polarity (keyword or LLM) |
| Macro bias | Gold-aware tilt from macro keywords |
These are blended into a single score, then mapped into probabilities via a logistic function.
Step 1: Market data → momentum features
The script fetches OHLCV data and requires enough history (e.g., 30+ bars) to compute indicators.
It derives simple momentum features:
- ret1 = 1-bar return
- ret5 = 5-bar return
- ret20 = 20-bar return
Momentum is intentionally “plain”—no complex pattern mining—because the goal is explainable bias, not overfit prediction.
Step 2: RSI as context (not a hard rule)
RSI(14) is computed (commonly via EMA-smoothed gains/losses) and converted into a continuous score.
Instead of rigid thresholds (“RSI > 70 = sell”), the script normalizes RSI around 50:
- RSI above 50 contributes bullish bias
- RSI below 50 contributes bearish bias
This makes RSI compatible with other numeric signals.
Step 3: Trend via EMA(20)
A short-term trend check compares current price to EMA(20):
- price above EMA(20) → mild bullish tilt
- price below EMA(20) → mild bearish tilt
This answers a simple question:
Is price trading above or below its recent trend baseline?
Step 4: News sentiment (two modes)
Mode A: Keyword-based sentiment (fast + deterministic)
Headlines are scored using a whitelist/blacklist of words.
Bullish examples
- beats, upgrade, strong, record
Bearish examples
- miss, downgrade, lawsuit, warning
Scores are normalized to roughly [-1, +1].
Mode B: Optional LLM sentiment (Ollama)
If enabled, the script uses a local LLM (Ollama) to classify news text as:
- bullish
- neutral
- bearish
LLM mode is optional and meant to stay:
- local
- auditable
- supportive (not dominant)
Step 5: Macro keyword tilt (gold-aware)
For gold-related symbols (e.g., XAU, GOLD, GC=F), macro context matters.
The script boosts sentiment when headlines mention:
- war / conflict
- central bank buying
- inflation
- debt
- rate cuts
- currency debasement
And penalizes:
- rate hikes
- hawkish policy
- strong dollar
This prevents an equity-centric sentiment model from misreading commodity drivers.
Step 6: Blending into a score
Signals are combined with simple weights (example):
- momentum dominates (ret5, ret20)
- RSI and trend add context
- news sentiment supports (doesn’t lead)
This weighted score is intentionally conservative: no single feature should overwhelm the result.
Step 7: Score → probability
A logistic (sigmoid) function converts the score into probabilities:
- prob_up = sigmoid(score × scale)
- prob_down = 1 − prob_up
Logistic mapping is useful because it:
- stays bounded between 0 and 1
- responds smoothly to changing signals
- naturally represents uncertainty
Many implementations also cap extremes (e.g., 1%–99%) to avoid false certainty.
Example output (how to read it)
A typical run might produce:
- Prob Up: 63%
- Prob Down: 37%
With a breakdown like:
- ret5 positive
- ret20 positive
- RSI moderately above 50
- price above EMA(20)
- news sentiment slightly bullish
Interpretation:
“Given recent momentum, trend, and news, upward movement is more likely than downward—yet uncertainty remains.”
What this script is (and isn’t)
✅ Good for
- directional bias / confirmation
- trade filtering (only act when bias is strong)
- risk dashboards / monitoring
- research and education
❌ Not for
- price targets
- high-frequency trading
- fully automated execution
- “guaranteed” prediction claims
Practical extensions
If you want to evolve the script while keeping it interpretable:
- volatility-adjusted weighting (scale returns by ATR or realized vol)
- regime detection (trend vs mean-reversion)
- time-decay for news (fresh headlines matter more)
- symbol-specific calibration (gold vs stocks vs crypto)
- portfolio aggregation (bias across multiple instruments)
Closing thoughts
This script is a solid example of post-hype engineering:
- transparent
- interpretable
- honest about uncertainty
Instead of asking “Can AI predict the market?”, it asks a better question:
Given what we know right now, which direction is more plausible?
Get in Touch with us
Related Posts
- AI-Driven Legacy Modernization: Integrating Machine Intelligence into ERP, SCADA, and On-Premise Systems
- The Price of Intelligence: What AI Really Costs
- 为什么你的 RAG 应用在生产环境中会失败(以及如何修复)
- Why Your RAG App Fails in Production (And How to Fix It)
- AI 时代的 AI-Assisted Programming:从《The Elements of Style》看如何写出更高质量的代码
- AI-Assisted Programming in the Age of AI: What *The Elements of Style* Teaches About Writing Better Code with Copilots
- AI取代人类的迷思:为什么2026年的企业仍然需要工程师与真正的软件系统
- The AI Replacement Myth: Why Enterprises Still Need Human Engineers and Real Software in 2026
- NSM vs AV vs IPS vs IDS vs EDR:你的企业安全体系还缺少什么?
- NSM vs AV vs IPS vs IDS vs EDR: What Your Security Architecture Is Probably Missing
- AI驱动的 Network Security Monitoring(NSM)
- AI-Powered Network Security Monitoring (NSM)
- 使用开源 + AI 构建企业级系统
- How to Build an Enterprise System Using Open-Source + AI
- AI会在2026年取代软件开发公司吗?企业管理层必须知道的真相
- Will AI Replace Software Development Agencies in 2026? The Brutal Truth for Enterprise Leaders
- 使用开源 + AI 构建企业级系统(2026 实战指南)
- How to Build an Enterprise System Using Open-Source + AI (2026 Practical Guide)
- AI赋能的软件开发 —— 为业务而生,而不仅仅是写代码
- AI-Powered Software Development — Built for Business, Not Just Code













