Skip to content

About

AI-powered tokenized asset investment platform: FastAPI backend, Solidity contracts, Next.js web and mobile PWA.

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

161 Commits

Folders and files

Repository files navigation

QuantumNest

CI/CD Status License: MIT Python 3.11+ Node 20+

QuantumNest is a tokenized asset investment platform: a FastAPI backend for users, portfolios, market data, blockchain, and admin, Hardhat smart contracts, and two Next.js frontends. A library of ML models (LSTM, GARCH, sentiment analysis, portfolio optimization) sits alongside the backend, and an /ai router exposes task endpoints for forecasts, optimization, sentiment, risk, and market recommendations.

QuantumNest HomePage

Table of Contents

Overview

Topic Summary
Application tier FastAPI backend, Hardhat smart contracts, and two Next.js frontends. All four are wired together and covered by tests.
AI endpoints The /ai router runs through an in-process task queue. predict/asset/{symbol} trains the LSTM on a generated demonstration series, and the optimize, sentiment, risk, and recommendation endpoints return fixed demonstration payloads.
AI library Modules in code/backend/app/ai (GARCH, sentiment, portfolio optimization, PCA, risk profiling, fraud detection, financial advisor) are implemented for use in code. The live app imports only the LSTM.
Mobile frontend mobile-frontend is a second Next.js application deployed to Cloudflare Workers through OpenNext. It is not a native mobile app.
Tests 110 backend, 87 smart contract, 14 web, and 14 mobile-frontend tests. All four suites run in CI.

Architecture

flowchart TD
    web["web-frontend (Next.js)"] -->|"HTTP/JSON"| api
    mobile["mobile-frontend (Next.js, Cloudflare Workers)"] -->|"HTTP/JSON"| api
    api["FastAPI backend: users, portfolio, market, ai, blockchain, admin"] --> db[("PostgreSQL, SQLite for local dev")]
    api --> redis[("Redis")]
    api -->|"web3.py"| chain["Hardhat contracts: PortfolioManager, TokenizedAsset, TradingPlatform, DeFiIntegration, TestToken"]
    api --> queue["In-process task queue: ai_tasks"]
    queue -->|"LSTM"| ai["app/ai library"]
Loading
Compose service Image or build Host port Role
backend code/backend/Dockerfile 8000 FastAPI app served by Gunicorn with uvicorn workers
web-frontend web-frontend/Dockerfile 3000 Next.js dashboard
mobile-frontend mobile-frontend/Dockerfile 3001 Second Next.js app
db postgres:16-alpine 5432 (localhost) Primary database
redis redis:7-alpine 6379 (localhost) Cache
blockchain code/blockchain/Dockerfile 8545 (localhost) Hardhat node
blockchain-deploy code/blockchain/Dockerfile None One-shot contract deployment (Compose profile blockchain-deploy)
migrate code/backend/Dockerfile None One-shot database initialization (Compose profile migrate)

See docs/ARCHITECTURE.md for detail.

Project Structure

Path Purpose
code/backend FastAPI application: routers, auth, services, AI library, workers, models, and tests
code/blockchain Hardhat project: Solidity contracts, deploy scripts, and tests
web-frontend Next.js dashboard
mobile-frontend Second Next.js app, deployed to Cloudflare Workers
infrastructure Docker, Kubernetes, Terraform, Ansible, and monitoring configuration
scripts Setup, run, build, test, lint, and dependency-check scripts
docs Project documentation
.github CI/CD workflow and its documentation

Feature Status

Application tier

Component Details
API FastAPI backend with six routers (users, portfolio, market, ai, blockchain, admin), an OAuth2 /token endpoint, and a /health check, run by uvicorn.
Auth JWT sessions (python-jose), bcrypt password hashing, and TOTP-based MFA (pyotp). SECRET_KEY must be at least 32 characters, and both signing keys default to random per-process values when unset. The Compose file requires both to be set.
Market data Yfinance and Alpha Vantage integrations for prices and history.
Smart contracts Hardhat-managed PortfolioManager, TokenizedAsset, TradingPlatform, DeFiIntegration, and TestToken, read and written through a web3.py service. Write operations are opt-in and need PRIVATE_KEY.
Data layer SQLAlchemy 2 over PostgreSQL, or SQLite for local development, with tables created by init_db. Redis is used for caching.
Task queue An in-process MockCeleryApp mimics the Celery API and runs tasks immediately in the same process, so the /ai endpoints need no broker.
Web frontend Next.js 15, React 19, and TypeScript, with Tailwind CSS, Recharts, and ethers.js 5. Pages: Home, Dashboard, Portfolio, Market Analysis, Blockchain Explorer, Recommendations, Admin, Profile, Settings, authentication, Terms, and Privacy.
Mobile frontend Next.js 15 and TypeScript app with the same page set, deployed separately to Cloudflare Workers via OpenNext.

AI tier

Component Details Live API
LSTM price prediction TensorFlow/Keras LSTM. TensorFlow is imported when the model loads and is installed separately from requirements.txt. predict/asset/{symbol}, on a demo series
Sentiment, portfolio optimization, risk, and recommendations Task functions in app/workers/ai_tasks.py that return fixed demonstration payloads. /ai endpoints, demonstration payloads
GARCH, sentiment analyzer, portfolio optimizer, PCA, risk profiler, fraud detection Implemented with arch, scikit-learn and NLTK, and cvxpy, and available to import. Library
Anomaly detection, recommendation engine, financial advisor (OpenAI-backed) Implemented as standalone classes. Library

Technology Stack

Area Technology
Backend API Python 3.11, FastAPI, uvicorn, Gunicorn, Pydantic v2
Auth python-jose (JWT), passlib and bcrypt, pyotp (MFA)
Data layer SQLAlchemy 2, PostgreSQL (SQLite for local development), Redis
ML and quant scikit-learn, arch (GARCH), cvxpy, xgboost, statsmodels; TensorFlow/Keras for the LSTM
Market data yfinance, Alpha Vantage
AI text OpenAI API (used by the financial-advisor module)
Blockchain Solidity, OpenZeppelin, Hardhat, web3.py
Web frontend Next.js 15, React 19, TypeScript, Tailwind CSS, Recharts, ethers.js 5
Mobile frontend Next.js 15, React 19, TypeScript, Tailwind CSS, OpenNext on Cloudflare Workers
Infrastructure Docker, Docker Compose, Kubernetes (Kustomize), Terraform, Ansible
Monitoring Prometheus, Grafana, structlog, Sentry SDK, prometheus-client
CI/CD GitHub Actions
Testing pytest (backend), Hardhat (contracts), Jest (web and mobile frontend)

Installation and Setup

Prerequisites: Python 3.11+ and Node.js 20+. Docker is optional.

git clone https://github.com/quantsingularity/QuantumNest.git
cd QuantumNest

# Blockchain
cd code/blockchain
npm install

# Backend
cd ../backend
python -m venv .venv && source .venv/bin/activate
pip install -r requirements.txt

# Web frontend
cd ../../web-frontend
npm install --legacy-peer-deps

# Mobile frontend
cd ../mobile-frontend
npm install --legacy-peer-deps

To use the LSTM price prediction, also install TensorFlow in the backend environment (pip install tensorflow).

For an automated setup:

git clone https://github.com/quantsingularity/QuantumNest.git
cd QuantumNest
./scripts/setup_quantumnest_env.sh
./scripts/run_quantumnest.sh

Full, environment-specific instructions are in docs/INSTALLATION.md.

Running the Stack

# 1) Local chain (from code/blockchain)
npx hardhat node                   # http://127.0.0.1:8545

# 2) Backend (from code/backend, venv active)
python run_flask.py                # FastAPI via uvicorn at http://127.0.0.1:8000, docs at /docs

# 3) Web frontend (from web-frontend)
npm run dev

# 4) Mobile frontend (from mobile-frontend)
npm run dev

The development entry point uses SQLite, so no database is needed locally. The backend reads the chain address from ETHEREUM_RPC_URL (default http://localhost:8545) and the deployed contract addresses from BLOCKCHAIN_DEPLOYMENTS_DIR.

Or run the whole stack in Docker (from code/). Both secrets must be 32 or more characters:

cd code
export SECRET_KEY="$(openssl rand -hex 32)"
export API_SECRET_KEY="$(openssl rand -hex 32)"
docker compose up --build

The frontends are built against NEXT_PUBLIC_API_URL, which defaults to http://localhost:8000. See docs/USAGE.md and docs/CONFIGURATION.md.

API Surface

Base URL http://127.0.0.1:8000. Interactive docs at /docs (Swagger) and /redoc.

Group Prefix Endpoints
Health Site root GET /, GET /health, POST /token
Users /users login, me, password-reset/request, password-reset/confirm, list and create, {user_id} (GET, PUT, DELETE)
Portfolio /portfolio List and create, {id} (GET, PUT, DELETE), assets/{id}, performance/{id}, summary/{id}
Market /market assets, assets/{id}, assets/symbol/{symbol}, assets/{id}/price, assets/{id}/price_history, market_summary, market_news, sector_performance, transactions
AI /ai models, predictions, predict/asset/{symbol}, tasks/{task_id}, sentiment/asset/{symbol}, optimize/portfolio/{id}, risk/portfolio/{id}, recommendations/market
Blockchain /blockchain contracts, transactions, wallet/{address}/balance, deploy/contract, execute/contract/{id}, tokenization/assets, networks
Admin /admin dashboard, users, users/{id}/status, users/{id}/role, system/logs, system/performance, system/backup, analytics/user-activity, announcements

Full request and response shapes are in docs/API.md.

Testing

Suite Directory Tests Run locally
Backend code/backend 110 pytest tests/
Contracts code/blockchain 87 npx hardhat test
Web web-frontend 14 npm test
Mobile mobile-frontend 14 npm test

Run each command from the directory shown. All four suites run in CI, and ./scripts/run_all_tests.sh runs them together. See CI/CD Pipeline.

CI/CD Pipeline

GitHub Actions (.github/workflows/cicd.yml) runs on pushes and pull requests to main and develop, and on manual dispatch. Every job after the first depends on Code Quality Checks, so the other seven run in parallel once formatting passes.

# Job Depends on What it does
1 Code Quality Checks None autoflake and black --check on Python, plus a repository-wide Prettier check (JS, TS, JSON, HTML, CSS, Markdown, Solidity, YAML)
2 Backend Test & Build Code Quality Checks Runs pytest with coverage, byte-compiles the sources, verifies the app imports, builds the backend image, and smoke tests /health
3 Smart Contract Tests Code Quality Checks Compiles the contracts with Hardhat, runs the contract tests, runs coverage, and uploads the coverage report
4 Web-Frontend Test & Build Code Quality Checks npm ci, the Jest suite, the production Next.js build, and a build upload
5 Mobile-Frontend Test & Build Code Quality Checks npm ci, the Jest suite with coverage, the Next.js build, and a build upload
6 Docs Validation Code Quality Checks markdownlint, offline link and anchor checks, code-sample syntax checks, docs and scripts consistency checks, and an advisory external link check
7 Infrastructure Validation Code Quality Checks Terraform, Kubernetes (base and all three overlays), and Ansible validation, plus yamllint, Compose and Dockerfile checks, an image build, and a secret scan
8 Scripts Validation Code Quality Checks ShellCheck, syntax, shebang, and executable-bit checks on every shell script, plus a --help smoke test for the CLI scripts

Coverage reports are kept for 30 days and build artifacts for 7 days. The step-by-step breakdown of each job is in .github/readme/README.md.

Documentation

Document Contents
docs/README.md Documentation index
docs/ARCHITECTURE.md System architecture
docs/API.md REST API reference
docs/INSTALLATION.md Setup for all components
docs/CONFIGURATION.md Environment variables and config
docs/USAGE.md Running and using the platform
docs/CLI.md Helper scripts reference
docs/FEATURE_MATRIX.md Feature status, implemented vs planned
docs/TROUBLESHOOTING.md Common issues and fixes
docs/CONTRIBUTING.md Contribution guide
docs/examples/ai-model-usage.md Example: using the AI endpoints
docs/examples/blockchain-integration.md Example: working with the contracts
docs/examples/portfolio-management.md Example: creating and managing portfolios

Contributing

See docs/CONTRIBUTING.md.

License

This project is licensed under the MIT License. See the LICENSE file for details.

About

AI-powered tokenized asset investment platform: FastAPI backend, Solidity contracts, Next.js web and mobile PWA.

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Used by

Contributors

Languages