A comprehensive, modern, multi-asset financial dashboard built with Next.js 16, React 19, and Tailwind CSS v4. Tracks equities and bonds directly from your personal Google Sheets, integrates live bond coupon schedules from NSDL, provides a 5-node agentic AI portfolio analyst, and runs an automated multilingual financial news engine powered by Supabase pgvector and Google Gemini.
Important
This project was completely built using "vibe coding" and AI-assisted development.
The author possesses foundational full-stack web development knowledge and directed AI agents (such as Google Gemini and Anthropic Claude) to architect, scaffold, implement, and refine the application. The author may not have deep, line-by-line theoretical knowledge of every complex pattern utilized in this codebase (including low-level vector similarity search SQL functions, agentic LLM fallback queues, and AST parsing).
As a consequence:
- The codebase, architecture, dependency choices, API integrations, and security practices may contain undiscovered bugs, inefficiencies, suboptimal patterns, or security gaps.
- Do not use this codebase in high-stakes production or mission-critical financial environments without conducting an independent code audit, rigorous testing, and validation by experienced software engineers and cybersecurity professionals.
- This project serves primarily as an exploration of how modern AI coding workflows can bridge domain intent and full-stack software delivery.
- Live Application: portfolio-tracker-kishoreabcs-projects.vercel.app
- Demo Credentials: Username:
test| Password:test
- Demo Credentials: Username:
- Google Sheets Data Template: View Reference Google Sheet
- Make a copy of this sheet to format your personal portfolio for seamless integration.
Traditional portfolio management software often comes with significant downsides: it stores sensitive financial records in proprietary third-party databases, locks users into rigid data schemas, lacks native support for Indian fixed-income bonds/debentures, and provides generic market news detached from an individual's actual holdings.
Portfolio Tracker Dashboard was engineered to solve these problems by:
- Ensuring Data Privacy & Control: Using a personal Google Sheet as a headless database. You own and control your data; the dashboard operates on read-only API access.
- Supporting Multi-Asset Classes: Native tracking for both Equities (stocks) and Fixed Income (Bonds, NCDs, SGBs) with credit ratings, face value, yield-to-maturity (YTM), and automated coupon schedules.
- Automating Fixed-Income Due Diligence: Fetching official coupon payment dates and cashflow schedules for Indian bonds using direct ISIN lookup against the NSDL Bond Information database.
- Delivering Contextual AI Intelligence: Running a 5-node agentic AI pipeline that analyzes your portfolio's health, checks diversification, cross-references macroeconomic market trends via live web grounding, and conducts stress-testing simulations.
- Connecting Breaking News to Your Holdings: Scraping regional RSS financial feeds, translating non-English news (e.g., Tamil financial articles) into English via LLMs, creating vector embeddings, and automatically tagging articles that mention companies currently in your portfolio.
- Executive Overview: Real-time net worth calculation, total equity value, total bond value, day's P&L, and cashflow allocations.
- Top Movers & Performance: Automatic computation of daily top gainers and losers.
- Asset & Sector Breakdown: Interactive Recharts charts detailing sector concentration and asset class distributions.
- Zero-Rigidity Column Matching: Flexible synonym-based header detection (
lib/sheets/parser.ts). Recognizes varied column headers such ascmp,ltp,current price,qty,shares,units,isin,coupon, etc. - In-Memory Caching: 15-minute server-side caching with instant cache invalidation via
/api/sheets?force=true.
- Bond Portfolio Analytics: Track total bond holdings, weighted coupon rates, yield to maturity (YTM), duration, and credit rating distributions (AAA down to NR).
- NSDL API Cashflow Sync: Direct HTTPS integration with the National Securities Depository Limited (
indiabondinfo.nsdl.com) to extract verified historical and upcoming coupon payout dates for 12-character ISINs. - Maturity Calendar & Cashflow Forecasting: Monthly visual timeline of upcoming interest payouts and principal redemptions.
A sequential multi-agent pipeline (lib/ai/pipeline.ts) that orchestrates specialized AI analysis:
- Node 1 β Portfolio Analyzer: Computes quantitative portfolio metrics, Herfindahl-Hirschman Index (HHI), and diversification scores.
- Node 2 β Macro Analyst: Grounds analysis with live web search via Tavily, scraped RSS headlines, and live Yahoo Finance benchmark index quotes (^NSEI, ^BSESN).
- Node 3 β Strategy Node: Identifies tactical opportunities, rebalancing needs, and asset allocation advice.
- Node 4 β Risk Engine: Performs stress-scenario simulations (e.g., interest rate shifts, equity drawdowns).
- Node 5 β Report Generator: Synthesizes analysis into a clean, structured JSON response consumed by the dashboard UI.
- Circular Model Failover: Automatically switches across configured models (
gemini-3.1-flash-lite,gemini-3.5-flash-lite, Groqllama-3.1,qwen3.6,gpt-oss-120b) with inter-call pacing delays and auto-cooldown blacklisting when encountering 429 quota limits or 503 upstream congestion.
- Automated RSS Ingestion: Scrapes financial RSS feeds and strips HTML artifacts.
- Regional Language Translation: Translates non-English financial news into English via strict financial-preserving prompts (preserving INR values, company names, percentages, and fiscal dates).
- Automated Portfolio Tagging: Extracts mentioned Indian companies and matches them against active portfolio holdings using alias mapping.
- Supabase pgvector Search: Generates 3072-dimensional embeddings via Google Gemini embeddings, stored in a PostgreSQL database with an optimized cosine distance function (
match_newsRPC) for semantic natural-language searches.
- Search, filter, and sort stocks by sector, valuation, and percentage change.
- Interactive modal with historical price charts powered by Lightweight Charts and real-time quotes from Yahoo Finance.
- Export full portfolio summaries, equity holdings, bond schedules, and AI insight reports to structured CSV or styled PDF documents via
pdfmake.
- Dual Authentication Modes: NextAuth v5 supporting Google OAuth and local Credentials.
- Access Control: Restricts access using an email allowlist (
ALLOWED_EMAILS). - Concurrent Session Protection: Enforces single active user sessions, invalidating stale JWT sessions upon new login.
flowchart TD
subgraph Client["Client Browser (Next.js 16 + React 19)"]
UI["Modern Glassmorphism UI\n(Tailwind CSS v4 + Framer Motion)"]
RQ["React Query (@tanstack/react-query)\nClient-side Cache & Prefetching"]
end
subgraph API["Next.js Server Route Handlers"]
Auth["Auth.js v5 (NextAuth)\nJWT Session Guard & Allowlist"]
SheetsRoute["/api/sheets\nHeuristic Parser & 15m Cache"]
BondsRoute["/api/bonds/cashflow\nNSDL ISIN Integration"]
InsightsRoute["/api/insights\n5-Node Agentic AI Pipeline"]
NewsRoute["/api/news\nIngest, Translate & Search"]
ReportsRoute["/api/reports/pdf\npdfmake Document Builder"]
end
subgraph DataSources["External Data & Database Layer"]
GSheets[("Google Sheets API v4\n(Headless Portfolio DB)")]
NSDL["NSDL Bond Portal\n(indiabondinfo.nsdl.com)"]
Yahoo["Yahoo Finance API\n(Live Quotes & Historical Data)"]
Tavily["Tavily Search API\n(Live Web Grounding)"]
Supabase[("Supabase PostgreSQL\n+ pgvector (news table)")]
end
subgraph LLMLayer["AI & Model Layer"]
ModelMgr["Circular Model Manager\n(Pacing Delay + 429 Blacklist)"]
Gemini["Google Gemini API\n(Flash / Flash-Lite / Embeddings)"]
Groq["Groq Cloud\n(Llama / Qwen / GPT-OSS Fallback)"]
end
UI --> RQ
RQ --> Auth
Auth --> SheetsRoute
Auth --> BondsRoute
Auth --> InsightsRoute
Auth --> NewsRoute
Auth --> ReportsRoute
SheetsRoute --> GSheets
BondsRoute --> NSDL
InsightsRoute --> ModelMgr
InsightsRoute --> Yahoo
InsightsRoute --> Tavily
NewsRoute --> Supabase
NewsRoute --> ModelMgr
ModelMgr --> Gemini
ModelMgr --> Groq
| Category | Technologies / Libraries | Purpose |
|---|---|---|
| Framework | Next.js 16.2.10 (App Router), React 19.2.4 | Server components, client rendering, streaming, and API route handlers. |
| Language | TypeScript 5 | End-to-end type safety across portfolio models, sheets, and AI agents. |
| Styling & Animation | Tailwind CSS v4, Framer Motion, Lucide React, Radix UI | Modern responsive dark UI, micro-animations, accessible primitives. |
| State Management | TanStack React Query v5 | Server-state caching, automatic revalidation, and optimistic loading states. |
| Primary Data Source | Google Sheets API v4 | Read-only access to user-owned portfolio spreadsheets. |
| Database & Vector Store | Supabase (PostgreSQL + pgvector extension) |
Storage of financial news articles with 3072-dimensional vector similarity search. |
| AI Framework | LangChain (@langchain/google-genai, @langchain/groq, @langchain/core) |
Agent abstractions, structured prompts, output parsing, and model switching. |
| LLM Providers | Google Gemini (Gemini 3.1 Flash Lite, 2.5 Flash, 3.7 Flash) & Groq | News translation, summarization, and multi-node portfolio analysis. |
| Market & Bond APIs | yahoo-finance2, NSDL BDS API |
Real-time equity market quotes and official bond coupon schedule queries. |
| Charts & Visualizations | Recharts, Lightweight Charts (lightweight-charts) |
Financial asset allocation charts, yield curves, and interactive candlesticks. |
| Authentication | Auth.js (NextAuth v5 beta) | Google OAuth 2.0 and Credentials authentication with session concurrency control. |
| Document Export | pdfmake |
Server-rendered high-resolution PDF financial reports. |
| DevOps & Container | Docker (Alpine 3-stage build), Docker Compose | Production-ready containerization. |
Portfolio Tracker/
βββ dashboard/
βββ .dockerignore
βββ Dockerfile # Multi-stage container build (deps -> builder -> runner)
βββ docker-compose.yml # Single-command Docker container orchestration
βββ env_example.txt # Master environment variable template
βββ package.json # Project metadata and dependencies
βββ tsconfig.json # TypeScript compiler configuration
βββ next.config.ts # Next.js runtime configuration
βββ auth.ts # NextAuth v5 configuration & session handlers
βββ middleware.ts # Route protection middleware
β
βββ app/ # Next.js App Router
β βββ page.tsx # Executive Portfolio Dashboard (Home)
β βββ layout.tsx # Root layout, fonts, and global metadata
β βββ globals.css # Tailwind CSS v4 directives & theme tokens
β βββ providers.tsx # QueryClientProvider & SessionProvider wrapper
β βββ login/ # Authentication screen (Google OAuth & Credentials)
β βββ portfolio/ # Unified equity & bond holdings table
β βββ stocks/ # Stock watchlist, sector sorting & search
β βββ bonds/ # Bond yield-to-maturity, credit ratings & cashflow
β βββ calendar/ # Monthly coupon payment & bond maturity schedule
β βββ cashflow/ # Income, expense & monthly savings analytics
β βββ analytics/ # Diversification scores & sector allocations
β βββ insights/ # 5-Node Agentic AI Insights execution dashboard
β βββ news/ # AI Financial News Hub with pgvector semantic search
β βββ reports/ # CSV and PDF export generator
β βββ api/ # Internal Serverless Route Handlers
β βββ auth/[...nextauth]/ # NextAuth OAuth callback handler
β βββ sheets/ # Google Sheets discovery, fetcher & parser
β βββ bonds/cashflow/ # NSDL bond API proxy
β βββ insights/ # Multi-agent LLM pipeline trigger
β βββ news/ # News listing & filtering
β β βββ sync/ # Manual & Cron RSS sync worker
β β βββ search/ # Cosine similarity vector search
β β βββ portfolio/ # Portfolio-filtered news stream
β βββ market-data/ # Live index quotes (NIFTY 50, SENSEX)
β βββ stocks/[symbol]/ # Yahoo Finance quote, profile & history
β βββ reports/pdf/ # pdfmake PDF compilation route
β
βββ components/ # Modular UI Components
β βββ layout/ # Sidebar, Topbar, Navigation items
β βββ shared/ # KpiCard, EmptyState, SectionHeader
β βββ ui/ # Accessible UI primitives (Button, Card, Dialog, Table)
β βββ charts/ # Recharts wrappers (Allocation, Performance)
β βββ bonds/ # BondCashflowDialog, MaturityTimeline
β βββ insights/ # AgentExecutionPanel, HealthCard, StrategyCard
β βββ news/ # NewsCard, SearchBar, SentimentBadge
β
βββ hooks/ # Custom React Query Hooks
β βββ usePortfolioData.ts # Central data hook for portfolio and sheets
β βββ useAiInsights.ts # Hook managing agentic execution state
β βββ useNews.ts # Hook for news feed, search, and pagination
β
βββ lib/ # Business Logic & Infrastructure Layer
β βββ ai/ # Agent pipeline nodes, circular model manager & Tavily
β βββ sheets/ # Google Sheets client, tab discovery, heuristic parser
β βββ bonds/ # NSDL HTTPS client
β βββ calc/ # Math for HHI index, risk, diversification, forecasts
β βββ news/ # RSS fetcher, translation, embeddings, company extraction
β βββ mappers/ # Normalizers converting raw Sheet cells to typed models
β βββ supabase.ts # Supabase client singleton
β βββ utils.ts # ClassName helper (clsx + twMerge)
β
βββ types/ # TypeScript Interfaces & Types
β βββ holdings.ts # Equity holding types
β βββ bonds.ts # Bond holding & NSDL response types
β βββ sheets.ts # Raw and parsed sheet cell representations
β βββ insights.ts # Structured AI Insights output schema
β βββ news.ts # News article, company tag, and search query types
β βββ agent-activity.ts # Agent pipeline event stream types
β
βββ supabase/ # Supabase Database Schemas
βββ migrations/
βββ 001_create_news.sql # News table schema with vector extension
βββ 002_create_news_vector_search.sql # match_news cosine similarity function
βββ 003_news_cron_sync.sql # Scheduled sync triggers
Before getting started, make sure you have:
- Node.js: Version
20.xor higher (v22+recommended). - Package Manager:
npm(v10+) orpnpm. - Google Cloud Console Account:
- A Google Cloud Project with the Google Sheets API v4 enabled.
- A Google Sheets API Key.
- (Optional for Google Sign-in) OAuth 2.0 Client ID & Client Secret.
- Supabase Project (Required for the News module):
- A free Supabase PostgreSQL database with the
pgvectorextension enabled.
- A free Supabase PostgreSQL database with the
- AI API Keys:
- Google Gemini API Key (from Google AI Studio).
- (Optional Fallback) Groq API Key (from Groq Console).
- (Optional Grounding) Tavily API Key (from Tavily AI).
git clone https://github.com/kishoreabc/Portfolio_Tracker.git
cd Portfolio_Tracker/dashboardnpm installCopy the template configuration to create your local environment file:
cp env_example.txt .env.localOpen .env.local in your editor and provide the necessary API keys and configuration values (refer to the Environment Variables Reference below).
Generate a secure NextAuth secret by running:
npx auth secretCopy the generated secret and set it as AUTH_SECRET in .env.local.
- Open your Supabase project dashboard and navigate to the SQL Editor.
- Run the migration scripts located in
supabase/migrations/in order:- Run
001_create_news.sql: Installs thevectorextension and creates thepublic.newstable. - Run
002_create_news_vector_search.sql: Creates thepublic.match_newsstored procedure for cosine similarity vector search.
- Run
npm run devOpen http://localhost:3000 in your browser.
| Variable | Required | Default / Example | Description |
|---|---|---|---|
GOOGLE_SHEET_ID |
Yes | 1uDp-iC8BJYWLzDH... |
The unique ID of your Google Sheet (from its URL). |
GOOGLE_SHEETS_API_KEY |
Yes | AIzaSy... |
Google Cloud API key with access to Google Sheets API v4. |
AUTH_SECRET |
Yes | 32-byte-hex-string |
Secret key used to encrypt NextAuth JWT session tokens. |
AUTH_URL |
Yes | http://localhost:3000 |
Canonical base URL of the deployment. |
LOGIN_USERNAME |
Yes | test |
Username for Credentials-based login. |
LOGIN_PASSWORD |
Yes | test |
Password for Credentials-based login. |
GOOGLE_CLIENT_ID |
No | *.apps.googleusercontent.com |
Google OAuth client ID for Google sign-in. |
GOOGLE_CLIENT_SECRET |
No | GOCSPX-... |
Google OAuth client secret. |
ALLOWED_EMAILS |
No | user@example.com,admin@example.com |
Comma-separated list of emails permitted to authenticate via Google. |
GEMINI_API_KEY |
Yes | AIzaSy... |
Primary Google Gemini API key for translation, summarization, and AI Insights. |
GEMINI_INSIGHTS_API_KEY |
No | AIzaSy... |
Dedicated Gemini key for the agentic pipeline (falls back to GEMINI_API_KEY). |
GEMINI_EMBEDDING_API_KEY |
No | AIzaSy... |
Dedicated Gemini key for embedding generation (falls back to GEMINI_API_KEY). |
GROQ_API_KEY |
No | gsk_... |
Groq Cloud API key for high-speed fallback LLM calls. |
TAVILY_API_KEY |
No | tvly-... |
Tavily search API key for live web grounding in the Macro Analyst node. |
GEMINI_MODEL |
No | gemini-3.1-flash-lite, gemini-3.5-flash-lite |
Comma-separated list of Gemini model tiers to rotate through. |
FALLBACK_MODELS |
No | openai/gpt-oss-120b, qwen/qwen3.6-27b |
Comma-separated list of Groq models to use upon Gemini quota exhaustion. |
SUPABASE_URL |
Yes | https://xxxx.supabase.co |
Your Supabase project URL. |
SUPABASE_SERVICE_ROLE_KEY |
Yes | eyJhbGciOi... |
Supabase service role secret (backend only; bypasses Row Level Security). |
RSS_URL |
Yes | https://example.com/rss |
RSS feed URL providing financial news articles for ingestion. |
NEWS_SYNC_BATCH_SIZE |
No | 5 |
Batch size for concurrent news translation and embedding. |
NEWS_SEARCH_TOP_K |
No | 20 |
Maximum number of matched news articles returned from vector search. |
The application includes an optimized multi-stage Dockerfile (based on Node 22 Alpine) and a docker-compose.yml for local containerized development or production VPS hosting.
docker compose up --build -dThe application will build, configure environment variables from .env.local or .env, and start listening on http://localhost:3000.
To view container logs:
docker compose logs -fTo stop the container:
docker compose down| Route | Method | Description | Query / Body Parameters |
|---|---|---|---|
/api/sheets |
GET |
Fetches, parses, and maps all configured Google Sheets tabs. | ?force=true (bypasses in-memory 15-minute cache) |
/api/bonds/cashflow |
GET |
Queries the NSDL BDS service for coupon and redemption schedules. | ?isin=INE002A08018 |
/api/insights |
POST |
Triggers the 5-node agentic AI portfolio analysis pipeline. | Body: { equity, bonds, cashFlow, ... } |
/api/news |
GET |
Returns paginated news articles with company tags. | ?page=1&limit=20&portfolioOnly=true |
/api/news/search |
GET |
Performs vector semantic search or full-text search across news articles. | ?q=interest+rate&semantic=true |
/api/news/sync |
POST |
Triggers the RSS ingestion, translation, embedding, and company-tagging pipeline. | Authorization: Bearer <CRON_SECRET> or Admin Session |
/api/news/[id]/reprocess |
POST |
Re-translates, re-embeds, and re-tags a specific news record. | URL param: id |
/api/market-data |
GET |
Fetches live market indices (NIFTY 50, SENSEX, USD/INR). | None |
/api/stocks/[symbol]/quote |
GET |
Fetches real-time price quote from Yahoo Finance. | URL param: symbol (e.g., TCS.NS) |
/api/stocks/[symbol]/history |
GET |
Fetches historical price bars for candlestick charts. | ?range=1y&interval=1d |
/api/reports/pdf |
POST |
Generates a downloadable PDF report using pdfmake. |
Body: { reportType: 'portfolio' | 'ai', data } |
In the dashboard/ directory, you can run:
# Run local development server
npm run dev
# Run ESLint validation
npm run lint
# Build production bundle with Next.js App Router
npm run build
# Start the compiled production build
npm start- Google Sheets API Rate Limits:
- The Google Sheets API v4 enforces a free tier quota of 300 requests per minute per project. The dashboard includes a 15-minute server-side in-memory cache to stay well below this limit during normal usage.
- LLM Quota (HTTP 429) & Model Cooldowns:
- Free-tier Google Gemini API keys may occasionally encounter strict RPM/TPM limits during news sync or when executing the full 5-agent AI pipeline.
- The built-in
ModelManagerautomatically blacklists saturated models for 60 seconds, gracefully shifts traffic to alternate Gemini tiers, and falls back to configured Groq models.
- ISIN Format Verification:
- The NSDL cashflow API endpoint expects a valid 12-character Indian ISIN (e.g.,
INE...). If an invalid ISIN is provided in your Google Sheet, the cashflow dialog will display an error for that specific holding without breaking the rest of the dashboard.
- The NSDL cashflow API endpoint expects a valid 12-character Indian ISIN (e.g.,
- Single Active Session Behavior:
- If you sign in on a new device or browser window using the same account credentials, any previous active sessions will be invalidated on their next API request.
This project is open-source and maintained for personal portfolio tracking and educational purposes.