Skip to content

Your personal Investment Advisor to help pick, understand, and predict stocks to help plan investments better

License

Notifications You must be signed in to change notification settings

SRX9/plex-al-gaib

Repository files navigation

Plex al-gaib – The AI Investment Advisor

“The desert prophet of the markets – AI-powered insights that never dry up.”


Plex al-gaib is a full-stack, end-to-end AI Investment Advisor powered by the Perplexity Sonar family of models. It automates the hard work of a human equity analyst – scraping data, crunching fundamentals, running scenario simulations and finally issuing a Buy / Watch / Reject verdict complete with narrative rationale.

Disclaimer: Plex AL-Gaib's main moto is to help with analysis. Nothing herein constitutes guarantee or financial advice.


✨ Key Features

  1. 10-Stage Fundamental Pipeline – from liquidity checks all the way to macro-economic stress-tests.
  2. Advanced Insights – price prediction, technical indicators, sector competitiveness, dividend quality, valuation metrics & macro factors.
  3. Perplexity Sonar + Reasoning Calls – fast point-lookups (perplexity/sonar) and deep research (openai/o4-mini-high).
  4. Automatic JSON Repair ✨ – messy model output is "healed" with jsonrepair for rock-solid downstream parsing.
  5. Modular & Extensible – each stage lives in its own function, so you can hot-swap logic or add new gates (ESG, sentiment, quant, etc.).
  6. Next.js 14 / App Router – out-of-the-box file-based API routes (/api/analyze-stock) and React server components.
  7. Tailwind + HeroUI v2 – sleek, responsive UI ready for dashboards, alerts and PDF exports.

🗺️ Architecture Overview

Client / Front-End
        |
        v
/api/analyze-stock (Next.js Route)
        |
        v
   analyzeStock.ts (Core Engine)
        |
        v
+-----------------------------+
| 10-Stage Analysis Pipeline: |
|  1. Data Ingestion          |
|  2. Core Fundamentals       |
|  3. AI Forecast             |
|  4. Sentiment & Momentum    |
|  5. Risk & Portfolio Fit    |
|  6. Price & Technical       |
|  7. Sector Analysis         |
|  8. Dividend Analysis       |
|  9. Valuation               |
| 10. Macro Factors           |
+-----------------------------+
        |
        v
  Decision Engine
        |
        v
+-------------------------------+
| Final Decision:               |
|  - Buy Recommendation         |
|  - Watch Recommendation       |
|  - Reject Recommendation      |
|  - Low Growth Flag            |
|  - Liquidity Concern          |
+-------------------------------+
        |
        v
   JSON Response
        |
        v
Client / Front-End (renders)

Stage-by-Stage Breakdown

# Stage Gate Criteria (pass/fail)
1 Data Ingestion & Liquidity Minimum $300 M market-cap & 100 K avg volume
2 Core Fundamentals P/E ≤ 100, P/B ≤ 10, D/E ≤ 2, ROE ≥ 15 %
3 AI Forecasting Perplexity growth forecast ≥ investor hurdle rate & confidence ≥ 0.6
4 Sentiment + Momentum Combines news sentiment and analyst consensus
5 Risk & Portfolio Fit ESG threshold, risk flags, diversification checks
6 Price Prediction & Technicals Computed technical score ≥ 0.3
7 Sector & Competitive Position Must not be bottom-quartile "Follower"
8 Dividend Health Informational – never hard-fails
9 Valuation Metrics Warns if stock is severely over-valued
10 Macroeconomic Factors Flags high rate-sensitivity during tightening cycles

If any hard gate fails, the pipeline short-circuits with the appropriate decision tag. Otherwise a final synthesis engine weighs all soft scores and produces the verdict.


🔍 How Perplexity API is Used

Function Model Purpose
SonarAICall perplexity/sonar Ultrafast point-data look-ups (e.g., P/E ratio, market-cap) – called 11× per stock.
SonarAIReasoningCall openai/o4-mini-high (via OpenRouter) Deep multi-paragraph reasoning for forward growth forecasts and scenario analysis.

Both helpers share the same signature and live in app/api/sonarAICall.ts. They:

  1. Hit the OpenRouter endpoint with your OPENROUTER_API key.
  2. Return raw text from Perplexity.
  3. Hand it to finalContentExtraction (JSON-repair pipeline) for bullet-proof parsing.

⚙️ Getting Started

# 1. Clone the repo (private for judging)
$ git clone https://github.com/your-org/plex-al-gaib.git
$ cd plex-al-gaib

# 2. Install deps (npm, pnpm, yarn – pick one)
$ npm i

# 3. Configure environment
$ cp .env.example .env
$ echo "OPENROUTER_API=sk-your-openrouter-key" >> .env
$ echo "ALPHA_VANTAGE_API_KEY=your-alpha-vantage-key" >> .env
$ echo "FINNHUB_API_KEY=your-finnhub-key" >> .env
$ echo "UPSTASH_REDIS_REST_URL=your-upstash-redis-url" >> .env
$ echo "UPSTASH_REDIS_REST_TOKEN=your-upstash-redis-token" >> .env

# 4. Run local dev server
$ npm run dev

# 5. Try the analyst API
$ curl "http://localhost:3000/api/analyze-stock?symbol=AAPL" | jq .

Environment Variables

Variable Description Required
OPENROUTER_API Required. API key with access to Perplexity Sonar models.
ALPHA_VANTAGE_API_KEY Required. API key for Alpha Vantage financial data service (stock validation & search).
FINNHUB_API_KEY Required. API key for Finnhub financial data service (stock search functionality).
UPSTASH_REDIS_REST_URL Required. Upstash Redis REST URL for caching API responses.
UPSTASH_REDIS_REST_TOKEN Required. Upstash Redis REST token for authentication.
NEXT_PUBLIC_HOST Optional. Public host URL (defaults to https://plex-al-gaib.vercel.app).
NEXT_PUBLIC_HOST_DOMAIN Optional. Public host domain (defaults to plex-al-gaib.vercel.app).

📦 Project Structure (Relevant Bits)

app/api/
  ├─ analyze-stock/route.ts   # HTTP handler → analyzeStock()
  ├─ stockAnalyzer.ts         # ← Core 10-stage engine
  ├─ sonarAICall.ts           # Perplexity helpers
  └─ jsonparseer.ts           # Robust JSON repair / extraction
public/
components/
styles/

🚀 Deployment

The app is Vercel-ready. Simply set the OPENROUTER_API secret in your Vercel dashboard and hit Deploy.



🛣️ Roadmap

  • 🔬 Real-time market data ingestion via Polygon / AlphaVantage
  • 💡 Reinforcement Learning feedback loop for verdict accuracy
  • 📝 PDF export & email digests for premium users
  • 📊 Portfolio dashboard with risk heat-maps

📜 License

MIT © 2024 — Plex al-gaib Team

About

Your personal Investment Advisor to help pick, understand, and predict stocks to help plan investments better

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages