Analyzes multiple stocks in a portfolio context, computing correlation matrices, sector rotation insights, and multi-factor scores to rank and recommend the optimal securities. Produces a ranked buy/hold/sell action list with diversification metrics and relative value comparison, with macro-regime overlays (geopolitical, monetary-policy, and market-stress context) applied to scoring and allocations, plus rule-based portfolio narrative generation and per-ticker data-source diagnostics.
Transform a basket of stocks into an actionable portfolio recommendation. Rank stocks by multi-factor scores, visualize sector rotation opportunities, compute pair-wise correlations, and suggest optimal weighting based on risk/return profiles.
Input: Array of tickers, optionally pre-computed MarketIntelligenceReport objects.
useMarketData provided: validate and use existing datadataSource and fallbackReason for downstream diagnosticsFor each ticker, calculate:
momentum = (price_change_1d% + price_change_5d% + price_change_1m%) / 3
slope = (current_price - ma50) / ma50 * 100
momentumScore = min(100, max(0, 50 + slope + momentum))
qualityScore = 0
if pe > 0 and pe < 30: qualityScore += 25 (valuation not extended)
if eps > 0 and eps_growth_positive: qualityScore += 25 (earnings positive)
if sentiment_score > 0: qualityScore += 25 (positive sentiment)
if analyst_upside > 10%: qualityScore += 25 (consensus price target support)
volatilityRank = (stock_vol - min_vol) / (max_vol - min_vol) * 100
riskScore = 100 - volatilityRank
if rsi > 70: riskScore -= 15 (overbought)
if rsi < 30: riskScore += 10 (oversold contrarian)
riskAdjustedScore = max(0, min(100, riskScore))
compositeScore = (
momentumScore * 0.30 +
qualityScore * 0.40 +
riskAdjustedScore * 0.30
)
// Weighted: quality > momentum > risk
From price history of all tickers (30-day, if available):
Sort tickers by composite score (descending). Assign action based on score and market conditions:
| Score Range | Action | Allocation |
|---|---|---|
| ≥ 75 | STRONG BUY | 8–10% per position |
| 60–74 | BUY | 5–7% per position |
| 45–59 | HOLD | 3–5% per position |
| 30–44 | REDUCE | 1–3% per position |
| < 30 | SELL | 0% (exit) |
Allocations should sum to ≤ 100% (allow cash buffer).
macroContext from each ticker's market-intelligence output into a portfolio-level macro regime.Compute:
dataSources object with status, sourceBreakdown, details, and a human-readable messageGenerate deterministic portfolio commentary from:
Return JSON output:
executiveSummary — 1–2 sentences on portfolio thesissectorRotationInsight — Which sectors are rotating in/out and whydiversificationAssessment — Are we sufficiently diversified? Any concentration risks?recommendations — Plain-English actionable steps (e.g., "Overweight tech momentum, underweight utilities")riskWarnings — Array of portfolio-level risks (e.g., "High correlation to tech sector", "All picks are momentum-heavy")The primary output field is portfolioNarrative. A legacy compatibility alias llmNarrative should return the same object.
{
"rankedTickers": [
{
"rank": 1,
"ticker": "NVDA",
"name": "NVIDIA Corp.",
"sector": "Semiconductors",
"action": "STRONG BUY",
"compositeScore": 82.5,
"allocation": 8,
"scores": {
"momentum": 85,
"quality": 78,
"riskAdjusted": 80
},
"priceTarget": 1000,
"upside": 15.2,
"sentiment": 0.65
}
],
"correlationMatrix": {
"tickers": ["AAPL", "MSFT", "GOOGL", "NVDA", "TSLA"],
"matrix": [
[1.0, 0.72, 0.68, 0.85, 0.52],
[0.72, 1.0, 0.71, 0.79, 0.55],
[...],
]
},
"sectorAnalysis": {
"byIndustry": [
{
"sector": "Semiconductors",
"tickers": ["NVDA"],
"allocation": 8,
"avgSentiment": 0.65,
"avgMomentum": 85,
"sectorStrength": 85
}
],
"topSector": "Semiconductors (strength: 85)",
"worstSector": "Utilities (strength: 25)"
},
"diversificationMetrics": {
"correlationWeightedConcentration": 0.42,
"avgPairwiseCorrelation": 0.68,
"sectorConcentration": 0.35,
"riskAssessment": "MODERATE - Tech-heavy with high internal correlation"
},
"portfolioMetrics": {
"totalAllocation": 85,
"cashBuffer": 15,
"expectedReturn": 12.5,
"expectedVolatility": 18.2,
"sharpeRatio": 0.69
},
"dataSources": {
"status": "LIVE",
"allLive": true,
"hasMock": false,
"sourceBreakdown": { "live": 3, "mock": 0, "unknown": 0 },
"details": [
{ "ticker": "NVDA", "source": "alpha-vantage", "usedFallback": false, "fallbackReason": null }
],
"message": "Live market data used for all 3 tickers."
},
"portfolioNarrative": {
"executiveSummary": "Portfolio is tilted toward semiconductor and AI momentum with moderate diversification. Recommend increasing exposure to non-correlated sectors for risk control.",
"sectorRotationInsight": "Semiconductors and cloud infrastructure are rotating in; utilities and consumer staples remain weak.",
"diversificationAssessment": "73% of allocation is tech-correlated. Consider adding financials, healthcare, or energy for cross-sector balance.",
"recommendations": [
"Overweight NVDA and MSFT on AI tailwinds",
"Add one healthcare or financial position for diversification",
"Consider XLU (utilities) as hedge if tech pullback risk high"
],
"riskWarnings": [
"High correlation within tech cluster (>0.80)",
"Portfolio momentum-heavy; vulnerable to sentiment reversal",
"Sector concentration risk: 73% in Technology"
]
},
"llmNarrative": { "sameAs": "portfolioNarrative" },
"skillUsed": "portfolio-optimization"
}
references/multi-factor-model.md for detailed factor definitions and calibration notes.