DEV Community

Cover image for Building an AI Stock Forecasting API
swapnil shingare
swapnil shingare

Posted on

Building an AI Stock Forecasting API

๐Ÿง  Build an AI Stock Forecasting API with LangGraph, OpenAI, and FastAPI
Want to predict stock prices using modern AI tools? In this guide, weโ€™ll build a production-grade API using LangGraph, OpenAI, and FastAPI โ€” powered by AI agents that:

โœ… Analyze financial news
โœ… Analyze stock charts & trends
โœ… Predict price forecasts with confidence levels & sentiment
โœ… Suggest short- and long-term selling targets
โœ… Return elegant HTML for direct frontend display

๐Ÿงฑ Project Architecture
Layer Tech Stack
๐Ÿง  AI Reasoning LangGraph + OpenAI GPT-4
๐Ÿ“‰ Stock Data Yahoo Finance via yfinance
๐Ÿ“ฐ News Custom scraper or NewsAPI
๐Ÿ” Backend FastAPI
โšก Caching Redis / FAISS
๐Ÿงฉ Agents Modular, parallel AI agents

๐Ÿง  AI Agent Design
We created three modular AI agents:

NewsAgent: Fetches and summarizes the latest news for a stock.

TrendAgent: Analyzes historical prices and technical patterns.

PredictionAgent: Uses output from News & Trend agents + stock history to predict:

Stock prices for 7d, 15d, 1mo, and 3mo

Short- and long-term sell targets

๐Ÿ“ˆ Bullish, ๐Ÿ“‰ Bearish, ๐Ÿค Neutral sentiment

๐Ÿ” Confidence level: High / Medium / Low

๐Ÿงญ Process Flow Diagram

Here's how the LangGraph flow looks:

Start([๐Ÿ”„ Start API Call]) --> NewsAgent[๐Ÿ—ž๏ธ News Agent]
Start --> TrendAgent[๐Ÿ“Š Trend Agent]
NewsAgent --> Combine[๐Ÿ”— Merge Outputs]
TrendAgent --> Combine
Combine --> PredictionAgent[๐Ÿ”ฎ Prediction Agent]
PredictionAgent --> Return([๐Ÿ“ค Return HTML Result])
Enter fullscreen mode Exit fullscreen mode

NewsAgent and TrendAgent run in parallel

PredictionAgent uses their output to forecast intelligently

๐Ÿ”ฎ Prediction Agent Sample Logic

def predict_future(stock, news, trend):
history_summary = get_history_summary(stock)

prompt = (
    f"Stock: {stock}\n\n"
    f"News: {news['summary']}\n"
    f"Trend: {trend['analysis']}\n"
    f"History: {history_summary}\n\n"
    f"Predict future stock price ranges:\n"
    f"  - 7d, 15d, 1mo, 3mo\n"
    f"Suggest:\n"
    f"  - Short-term and long-term sell targets\n"
    f"Provide sentiment (Bullish/Neutral/Bearish) and confidence level\n\n"
    f"Output as styled HTML with headers and bullet points."
)

response = client.chat.completions.create(
    model="gpt-4",
    messages=[{"role": "user", "content": prompt}],
    max_tokens=800
)
return {"html_prediction": response.choices[0].message.content}
Enter fullscreen mode Exit fullscreen mode

๐Ÿงช Example HTML Output

๐Ÿ“ˆ 15-Day Price Forecast

  • 7 Days: โ‚น3,420 โ€“ โ‚น3,480
  • 15 Days: โ‚น3,500 โ€“ โ‚น3,570

๐ŸŽฏ Sell Targets

  • Short-term: โ‚น3,550
  • Long-term: โ‚น3,700+

๐Ÿ“Š Sentiment

๐Ÿš€ Bullish โ€“ Positive momentum and rising volumes.

๐Ÿ” Confidence

High โ€“ Aligned news and technical signals, with historical support.

โšก Frontend Integration
Return the prediction as HTMLResponse from your FastAPI backend:

from fastapi.responses import HTMLResponse
@app.post("/predict", response_class=HTMLResponse)
async def predict_stock(...):
result = await flow.invoke(input)
return result["html_prediction"]

Inject in React or Vue:

๐Ÿ’พ Caching for Performance
Use Redis or FAISS to cache:

Past news summaries

Processed trend data

Full prediction HTML for frequently requested stocks

import redis

redis_client = redis.Redis(host="localhost", port=6379)
redis_client.set(stock_symbol, prediction_html, ex=3600)
๐Ÿš€ Deployment Tips
Use uvicorn or gunicorn to serve FastAPI

Host on Render, Fly.io, or your own VPS

Secure .env for API keys

Use openai>=1.0.0 (new SDK format)

๐ŸŽฏ Final Thoughts
With LangGraph + FastAPI + OpenAI, you've created a fully modular, explainable stock forecasting API that:

Thinks like an AI co-analyst ๐Ÿง 

Responds in seconds ๐Ÿ”

Presents beautiful HTML results ๐ŸŒ

Gives confidence-driven decisions for buyers & investors

For collab DM me on LinkedIn

Let me know your thoughts or suggestions on this idea in the comments below! ๐Ÿ‘‡

Top comments (0)