Skip to content

Solid Portfolio (سهم واعد للمحافظ الاستثمارية): Stock Portfolio Tracker A clean, local-first stock portfolio tracking application with a microservice-style architecture. Features real-time portfolio tracking, transaction management, and performance analytics.

Notifications You must be signed in to change notification settings

amgad01/solid-portfolio

Repository files navigation

Solid Portfolio (سهم واعد)

A stock portfolio tracker built with React, FastAPI, and PostgreSQL. Track investments, analyze performance, manage historical market data, and perform advanced stock analysis with interactive charts and technical indicators.

Tech Stack React TypeScript PostgreSQL Docker

Features

  • Portfolio Management: Real-time valuation, P&L tracking, position analysis
  • Transaction Tracking: Complete buy/sell history with fees and multi-currency support
  • Stock Analysis: Interactive charts with multiple chart types, technical indicators, and historical data
  • Market Data: Live quotes, historical prices, automated backfilling, index synchronization
  • Analytics: Performance metrics, interactive charts, allocation visualization, sector analysis
  • Admin Tools: Data management dashboard with pagination, sorting, and bulk operations
  • Internationalization: English and Arabic with RTL layout support and localized formatting
  • Data Quality: Automated index synchronization, sector validation, market cap updates

Stock Analysis

Interactive stock analysis with comprehensive charting capabilities:

Chart Types

  • Line Charts: Clean price progression visualization
  • Area Charts: Filled price charts for better visual impact
  • Candlestick Charts: OHLC data with traditional candlestick representation

Technical Indicators

  • SMA 20/50: Simple Moving Averages for trend analysis
  • Volume: Trading volume visualization
  • OHLC Data: Open, High, Low, Close price data when available

Time Periods

  • Last 30 days to 10+ years of historical data
  • Daily, weekly, and monthly granularity options
  • Real-time data fetching and backfilling

Key Metrics Display

  • Current price and key financial ratios (P/E, EPS, dividend yield)
  • Market data source attribution
  • Localized formatting for international users

Access via: Analysis → Select ticker → Interactive chart controls

Quick Start

git clone https://github.com/amgad01/solid-portfolio.git
cd solid-portfolio
docker-compose up -d

Open http://localhost in your browser.

Development

Prerequisites

  • Docker & Docker Compose
  • Node 18+ (frontend)
  • Python 3.11+ and Poetry (backend)

Setup

# Start databases
docker-compose up -d local-db market-db

# Backend (terminal 1)
cd backend
poetry install
poetry run uvicorn src.main:app --reload --host 0.0.0.0 --port 8000

# Frontend (terminal 2)
cd frontend
npm install
npm run dev

Access:

Environment Variables

Create backend/.env:

DATABASE_URL=postgresql+asyncpg://<DB_USER>:<DB_PASS>@localhost:5433/solid_portfolio
MARKET_DATABASE_URL=postgresql+asyncpg://<DB_USER>:<DB_PASS>@localhost:5434/market_data
CORS_ORIGINS=http://localhost:5173,http://localhost:3000,http://localhost
LOG_LEVEL=INFO

Testing

# Backend
cd backend
poetry run pytest

# Frontend (with coverage)
cd frontend
npm test
npm run test:coverage  # Generate coverage reports

Quality Metrics:

  • Backend: Comprehensive test coverage with pytest-asyncio
  • Frontend: 113+ passing tests with Vitest and React Testing Library
  • Coverage Reporting: HTML reports generated for both frontend and backend
  • Type Safety: Full TypeScript coverage with strict type checking

Data Management

The project includes comprehensive scripts for managing market data:

Index Synchronization

Sync index constituents from authoritative sources and populate with company details:

# Sync S&P 500 and Nasdaq 100 data
./scripts/sync-indexes.sh

# Options:
# API_URL: Backend API URL (default: http://localhost:8000)
# FETCH_DETAILS: Whether to fetch company details (default: true)

Populate Market Data

Initial population of index constituents with company information:

# Populate S&P 500 and NASDAQ 100 data
./scripts/populate_market_data.sh

# Populate specific indices with timeout
./scripts/populate_market_data.sh --universes SP500 --timeout 600

# Options:
# --universes: Comma-separated list (SP500, NASDAQ100)
# --timeout: Timeout in seconds (default: 300)
# --max-workers: Concurrent workers (default: 10)
# --verbose: Enable verbose logging

Update Existing Assets

Refresh market cap and sector data for existing assets:

# Update assets missing data
./scripts/update_assets.sh

# Force update all assets
./scripts/update_assets.sh --force-update

# Options:
# --batch-size: Assets per batch (default: 10)
# --timeout: Timeout in seconds (default: 600)
# --max-workers: Concurrent workers (default: 5)
# --force-update: Update all assets, not just missing data
# --verbose: Enable verbose logging

Sector Validation

Validate and correct sector classifications:

# Validate sector data
./scripts/validate_sectors.sh

# Options:
# --fix: Automatically fix validation issues
# --verbose: Enable verbose logging

Architecture

The backend follows Clean Architecture + Hexagonal Architecture + Domain-Driven Design principles:

  • Domain Layer: Business entities with validation rules and core business logic
  • Application Layer: Use cases orchestrating business workflows
  • Ports Layer: Abstract interfaces defining contracts
  • Adapters Layer: Concrete implementations (REST API, databases, external services)

Tech Stack

  • Frontend: React 19 + TypeScript 5+, Vite, Tailwind CSS, SCSS Modules
  • Backend: FastAPI (async), SQLAlchemy 2.0, Pydantic v2, PostgreSQL
  • Database: PostgreSQL (dual database: portfolio + market data)
  • Testing: Vitest, pytest-asyncio, coverage reporting
  • Internationalization: i18next with RTL support
  • Charts: Recharts for interactive data visualization
  • Deployment: Docker Compose, nginx for static serving

Project Structure

backend/src/
├── domain/                    # 🏛️ BUSINESS ENTITIES & RULES
│   ├── portfolio/            # Portfolio domain entities
│   ├── transactions/         # Transaction domain entities
│   └── market_data/          # Market data domain entities
├── application/               # 🎯 USE CASES & BUSINESS LOGIC
│   ├── portfolio/            # Portfolio use cases
│   ├── transactions/         # Transaction use cases
│   └── market_data/          # Market data use cases
├── ports/                     # 🔌 ABSTRACT INTERFACES
│   ├── primary/              # Input ports (service interfaces)
│   └── secondary/            # Output ports (repository interfaces)
├── adapters/                  # 🔧 CONCRETE IMPLEMENTATIONS
│   ├── primary/              # REST API controllers
│   └── secondary/            # SQLAlchemy repositories, external APIs
├── shared/                    # Cross-cutting concerns (database, settings)
└── market_data/               # Legacy market data context (preserved)

frontend/src/
├── features/       # Feature modules (portfolio, transactions, dashboard)
├── components/     # Reusable UI components
├── api/           # API client functions
├── hooks/         # Custom React hooks
└── lib/           # Utilities and business logic

🏗️ Clean Architecture Implementation

The backend has been refactored to follow Clean Architecture + Hexagonal Architecture + Domain-Driven Design principles:

Architecture Benefits

  • Maintainability: Clear separation of concerns with inward-pointing dependencies
  • Testability: Each layer can be tested independently
  • Scalability: Easy to add new features without affecting existing code
  • Flexibility: Database, APIs, and UI frameworks can be swapped without business logic changes

Implementation Highlights

  • Domain Layer: Rich business entities with validation rules and business logic
  • Application Layer: Use cases orchestrating complex business workflows
  • Ports Layer: Abstract interfaces defining clear contracts
  • Adapters Layer: Concrete implementations (REST API, SQLAlchemy repositories)
  • Hexagonal Design: Business logic independent of infrastructure concerns

Quality Metrics

  • Type Safety: 62.5% reduction in type checking errors
  • Test Coverage: 100% coverage for core business domains
  • Code Organization: 9,383 lines of well-structured, maintainable code
  • API Compatibility: Zero functional regression - all existing APIs work unchanged

Bounded Contexts

  • Portfolio Context: Position management, P&L calculations, performance tracking
  • Transactions Context: Trade recording, transaction history, validation
  • Market Data Context: Price feeds, historical data (legacy structure preserved)

## API Documentation

- OpenAPI docs: http://localhost:8000/docs
- API endpoints: `/api/v1/portfolio`, `/api/v1/transactions`, `/api/v1/market-data`

## Future Features

### ✅ **Recently Implemented**
- **Stock Analysis Page**: Interactive charts with multiple chart types and technical indicators
- **Enhanced Admin Dashboard**: Pagination, sorting, bulk operations, detailed ticker information
- **Index Synchronization**: Automated syncing of S&P 500 and Nasdaq 100 constituents
- **Arabic Localization**: Complete RTL support with Eastern Arabic numerals
- **Data Quality Scripts**: Automated sector validation and market cap updates
- **Testing Infrastructure**: Comprehensive test coverage with reporting

### 🔄 **In Development**
- **Advanced Filtering**: Filter companies by index membership, sector, market cap ranges
- **Index Analysis**: Pie charts showing sector weightings within each index
- **Market Cap Visualization**: Charts displaying index composition by market capitalization
- **Company Overlap Analysis**: Visual representation of companies common across multiple indices
- **Data Management Tools**: User-triggered database repopulation and data refresh capabilities

### 📈 **Analytics & Reporting**
- **Index Performance Tracking**: Historical performance analysis of market indices
- **Sector Rotation Analysis**: Track sector performance and rotation strategies
- **Portfolio Benchmarking**: Compare portfolio performance against relevant indices
- **Advanced Technical Indicators**: RSI, MACD, Bollinger Bands, and more
- **Portfolio Optimization**: Risk-adjusted return analysis and rebalancing suggestions

## Contributing

See [CONTRIBUTING.md](./CONTRIBUTING.md) for development guidelines and code conventions.

## License

MIT License - See [LICENSE](LICENSE) for details.

## Contact

**Author**: Amgad Mahmoud
**GitHub**: [@amgad01](https://github.com/amgad01)
**LinkedIn**: [Amgad Mahmoud](https://www.linkedin.com/in/amgad-m/)

About

Solid Portfolio (سهم واعد للمحافظ الاستثمارية): Stock Portfolio Tracker A clean, local-first stock portfolio tracking application with a microservice-style architecture. Features real-time portfolio tracking, transaction management, and performance analytics.

Resources

Contributing

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 2

  •  
  •