Stock Analytics is a comprehensive web application for stock traders and investors. It combines a powerful trading calculator (Buy/Sell/Stop Loss) with technical analysis tools (Indicators) and deep dividend history analytics.
π Designed for the Thai market (SET) and US Stocks (Wall St.), supporting automatic currency detection (THB/USD).
π Live Demo: https://stock-calculator-xxxx.onrender.com (Replace with your deployed URL)
| Feature | Description |
|---|---|
| Position Sizing | Calculate profit/loss, fees (VAT included), and net return |
| Risk Management | Define Buy, Sell, and Stop Loss points |
| Visual Graph | Interactive chart showing Buy/Sell/Stop levels relative to historical price |
| Risk Reward Ratio | Real-time RR calculation to evaluate trade quality |
Visualize market trends with interactive charts:
- π Price Action β Candlestick/Line chart with SMA/EMA overlays
- π RSI (Relative Strength Index) β Identify Overbought/Oversold conditions
- π MACD β Trend and momentum analysis with histogram
- π Volume β Trading volume bars
Deep dive into a company's dividend payouts:
- π Calendar View β See payouts on a calendar
- π Yield Analysis β Calculate historical Dividend Yield at time of payout
- π TTM Yield β Trailing Twelve Months dividend accumulation
- π₯ CSV Export β Download dividend data for analysis
- Auto-Detection β Automatically detects currency based on ticker
(e.g.,PTT.BKβ THB,AAPLβ USD) - Backend Driven β Uses metadata from Yahoo Finance/Twelve Data API
| Layer | Technology |
|---|---|
| Frontend | React 19, Vite, Recharts, CSS3 (Dark Theme) |
| Backend | Node.js, Express 5 |
| Data Sources | Yahoo Finance API (Primary), Twelve Data API (Fallback) |
| Caching | JSON File-based In-Memory Cache |
| Resilience | Circuit Breaker Pattern |
| Security | Helmet, CORS Whitelist, Rate Limiting, Input Validation |
- Node.js v18 or higher
- npm or yarn
git clone https://github.com/PhantomOutBreak/Stock-Calculator.git
cd Stock-Calculatornpm installCreate a .env file inside the Backend/ folder:
# Backend/.env
PORT=7860
TWELVE_DATA_API_KEY=your_api_key_here
NODE_ENV=developmentπ‘ Tip: Get a free API key from Twelve Data for backup data fetching.
π Security: Set
NODE_ENV=productionin your hosting platform (e.g., Render.com) to disable debug routes and enable production error handling.
Option A: Two Terminals
# Terminal 1 - Backend
cd Backend && node index.js
# Terminal 2 - Frontend
npm run devOption B: Concurrent (Recommended)
npm run start:dev # Uses nodemon for auto-reload
npm run dev # Vite dev serverAccess the app at: http://localhost:5173
# 1. Build frontend
npm run build
# 2. Start server (serves both API and static files)
npm start| Platform | Build Command | Start Command |
|---|---|---|
| Render.com | npm install && npm run build |
npm start |
| Railway | npm install && npm run build |
npm start |
| Heroku | npm install && npm run build |
npm start |
| Method | Endpoint | Description |
|---|---|---|
GET |
/api/stock/:ticker |
Get current quote for a stock |
GET |
/api/stock/history/:ticker |
Get historical price data |
GET |
/api/stock/dividends/:ticker |
Get dividend history |
GET |
/api/forex/usd-thb |
Get current USD/THB exchange rate |
GET |
/health |
Health check endpoint |
Example:
curl http://localhost:7860/api/stock/AAPL
curl http://localhost:7860/api/stock/history/PTT.BK?startDate=2025-01-01This application implements multiple layers of security following OWASP Top 10 (2021) guidelines:
| Layer | Implementation | OWASP Reference |
|---|---|---|
| HTTP Security Headers | Helmet.js β CSP, HSTS, X-Frame-Options, X-Content-Type-Options | A05:2021 β Security Misconfiguration |
| CORS Whitelist | Only allows requests from whitelisted origins (localhost + production domain) | CWE-942 β Overly Permissive CORS |
| Rate Limiting | Global: 100 req/15min per IP, API: 30 req/min per IP via express-rate-limit |
A04:2021 β Insecure Design |
| Input Validation | Ticker regex ^[A-Za-z0-9.\-]{1,20}$ + Date format validation + SSRF pattern blocking |
A03:2021 β Injection |
| Debug Route Guard | /api/debug/info hidden when NODE_ENV=production |
A05:2021 β Security Misconfiguration |
| Secret Protection | API keys never logged (even partially); env variables loaded securely | A09:2021 β Logging Failures |
| Error Handling | Generic error messages in production; full details only in server logs | CWE-209 β Sensitive Error Info |
Stock-Calculator/
βββ Backend/ # Node.js API Server
β βββ index.js # Main server entry point
β βββ envLoader.js # Smart .env loader (UTF-16 support)
β βββ yahooDirect.js # Direct Yahoo Finance fetch
β βββ stock_data_cache.json # Local cache (gitignored)
β
βββ src/ # React Frontend
β βββ Component/ # Reusable UI Components
β β βββ Indicators/ # Chart Components (RSI, MACD, Volume)
β β βββ DividendCalendar.jsx
β β βββ Layout.jsx
β β βββ Sidebar.jsx
β β βββ StockChart.jsx
β β
β βββ pages/ # Route Pages
β β βββ CalculatorPage.jsx # Trade Calculator
β β βββ IndicatorsPage.jsx # Technical Analysis
β β βββ Return Calculator.jsx # Dividend History
β β
β βββ utils/ # Helper utilities
β β βββ api.js # API fetch wrapper
β β βββ indicators/ # Calculation functions
β β
β βββ css/ # Stylesheets
β
βββ hooks/ # Custom React Hooks
β βββ useIndicators.js
β
βββ public/ # Static assets (source)
βββ dist/ # Production build (generated)
βββ package.json
βββ vite.config.js
βββ README.md
Contributions are welcome! Please follow these steps:
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
- π Security Enhancements (OWASP Top 10 Compliance):
- Added Helmet.js for automatic HTTP security headers (CSP, HSTS, X-Frame-Options)
- Implemented CORS Whitelist β only whitelisted origins can call the API
- Added Rate Limiting β Global (100 req/15min) + API-specific (30 req/min) per IP
- Added Input Validation Middleware β Ticker format regex + Date format validation
- Added SSRF/Path Traversal Protection β Blocks dangerous patterns in ticker input
- Debug route (
/api/debug/info) now hidden in production (NODE_ENV=production) - API key protection β Keys are no longer logged, even partially
- Added Global Error Handler β Generic error messages in production to prevent info leakage
- Added Trust Proxy setting for correct IP detection behind Render.com reverse proxy
- π¦ New Dependencies:
helmet,express-rate-limit
- π¨ Rebranding: Renamed from "Stock Calculator" to "Stock Analytics"
- β‘ Performance Optimizations:
- Implemented
React.memofor all indicator chart components - Added
requestAnimationFramethrottling for smooth chart panning - Optimized callback stability with
useCallback
- Implemented
- π― UI/UX Enhancements:
- Redesigned Indicator Panel with premium glassmorphism design
- Added iOS-style toggle switches with neon glow effects
- Fixed layout stretching issue (panel now absolutely positioned)
- Improved indicator categorization (Trends, Key Levels, Oscillators)
- π
Date Range Logic Improvements:
- Extended all preset ranges (1m, 3m, 6m, 1y, 5y) to ensure sufficient trading days
- Added weekend filtering (Saturday/Sunday exclusion)
- Compensates for holidays and non-trading days automatically
- π§ Technical Improvements:
- Enhanced zoom controls stability
- Improved chart rendering performance
- Better state management for interactive charts
- β Added Technical Indicators (RSI, MACD, Volume charts)
- β Added Dividend Calendar component
- β Improved currency detection (backend-driven)
- β Added Twelve Data API as fallback
- β Performance: JSON file-based caching
- β Fixed static serving for production deployment
- Trade Calculator with Risk Reward Ratio
- Basic stock price fetching
- Yahoo Finance β Primary data source
- Twelve Data β Backup data provider
- Recharts β Charting library
- Vite β Lightning-fast build tool
This project is licensed under the MIT License β see the LICENSE file for details.
Developed with β€οΈ by PhantomOutBreak