A revolutionary financial analytics platform combining AI-powered stock analysis with blockchain-verified portfolio management
Features - Demo - Installation - Usage - Architecture - Contributing
- Overview
- Key Features
- Technology Stack
- Project Architecture
- Installation Guide
- Configuration
- Usage Guide
- Smart Contract Details
- API Reference
- Security Considerations
- Testing
- Deployment
- Troubleshooting
- Roadmap
- Contributing
- License
The AI Stock Analyst with Blockchain Integration is a cutting-edge financial technology platform that bridges traditional stock market analysis with decentralized blockchain technology. Built for investors, traders, and financial analysts, this system provides:
- Real-time stock analysis powered by machine learning algorithms
- Technical indicators including RSI, MACD, Bollinger Bands, and ATR
- Immutable portfolio tracking on Ethereum blockchain
- AI-driven buy/sell recommendations with confidence scoring
- Multi-market support covering US and Indian stock exchanges
- Beautiful web interface built with Gradio for seamless user experience
Traditional portfolio management systems are centralized, prone to data manipulation, and lack transparency. This project solves these problems by:
- Decentralization: Investment records stored on blockchain cannot be altered or deleted
- Transparency: All transactions are verifiable and auditable
- AI Intelligence: Advanced algorithms provide data-driven investment insights
- Zero Trust: No central authority controls your portfolio data
- Real-time Data: Live stock prices and market data from Yahoo Finance API
- Smart Symbol Lookup: Fuzzy matching for company names (supports "Apple", "AAPL", etc.)
- Technical Indicators:
- RSI (Relative Strength Index) - Identifies overbought/oversold conditions
- MACD (Moving Average Convergence Divergence) - Trend momentum indicator
- SMA (Simple Moving Averages) - 20, 50, 200 day averages
- Bollinger Bands - Volatility and price level analysis
- ATR (Average True Range) - Volatility measurement
- AI Recommendation Engine: Buy/Hold/Sell signals with confidence scores (0-100%)
- Multi-factor Analysis: Combines technical, fundamental, and sentiment analysis
- Support for 80+ companies: Major US stocks and Indian NSE stocks
- Local Storage: Fast portfolio tracking with SQLite-like structure
- Blockchain Verification: Optional on-chain storage for immutable records
- Real-time Valuation: Live portfolio value updates using current market prices
- Gain/Loss Tracking: Detailed P&L calculations per investment
- Multi-investment Support: Track unlimited investments across different stocks
- Purchase History: Complete historical record with dates and prices
- Ethereum Smart Contract: Solidity 0.8.28 with gas-optimized code
- Web3.py Integration: Seamless Python-Ethereum communication
- Multi-network Support:
- Local Hardhat node (development)
- Sepolia testnet (testing)
- Ethereum mainnet (production)
- Transaction Verification: Real-time confirmation tracking
- Gas Reporting: Detailed gas usage analysis
- 20 Test Accounts: Pre-funded accounts with 10,000 ETH each (local development)
- Stock Comparison Tool: Side-by-side analysis of multiple stocks
- Market Overview Dashboard: Real-time indices (S&P 500, NASDAQ, NIFTY 50, SENSEX)
- Search Database: Searchable database of 80+ companies
- Volatility Analysis: Historical volatility calculations
- Volume Analysis: Trading volume patterns and anomalies
- Sector Performance: Industry-wise market trends
- Gradio Framework: Modern, responsive web interface
- Tab-based Navigation: Intuitive organization of features
- Real-time Updates: Auto-refreshing data displays
- Mobile-responsive: Works on all device sizes
- Dark Mode Compatible: Eye-friendly interface
- Interactive Charts: Visual representations of stock data
| Technology | Version | Purpose |
|---|---|---|
| Python | 3.9+ | Core application logic |
| Gradio | 4.44.0 | Web UI framework |
| yfinance | 0.2.46 | Stock market data API |
| pandas | 2.2.3 | Data manipulation |
| numpy | 2.1.2 | Numerical computations |
| Web3.py | 7.4.0 | Ethereum blockchain interaction |
| eth-account | 0.13.4 | Wallet management |
| plotly | 5.24.1 | Interactive visualizations |
| matplotlib | 3.9.2 | Static plots |
| seaborn | 0.13.2 | Statistical visualizations |
| Technology | Version | Purpose |
|---|---|---|
| Solidity | 0.8.28 | Smart contract language |
| Hardhat | 2.22.0 | Development environment |
| Ethers.js | 6.13.0 | Ethereum library |
| Chai | 4.3.10 | Testing framework |
| Hardhat Toolbox | 5.0.0 | Essential Hardhat plugins |
- Yahoo Finance API: Real-time stock data (free tier)
- Alchemy/Infura: Ethereum RPC providers (testnet/mainnet)
- Etherscan API: Contract verification (optional)
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β USER INTERFACE β
β (Gradio Web Application) β
β http://localhost:7860 β
βββββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββββ
β
βββββββββββββββββ΄ββββββββββββββββ
βΌ βΌ
βββββββββββββββββββββββ βββββββββββββββββββββββ
β Stock Advisor β β Portfolio Manager β
β (stock_advisor.py)β β(portfolio_manager.py)β
β β β β
β β’ Symbol lookup β β β’ Local storage β
β β’ Data fetching β β β’ Value calculation β
β β’ Technical analysisβ β β’ P&L tracking β
β β’ AI recommendationsβ β β’ Blockchain sync β
ββββββββββββ¬βββββββββββ βββββββββββ¬ββββββββββββ
β β
βΌ βΌ
ββββββββββββββββββββββββ ββββββββββββββββββββββββ
β Yahoo Finance API β β Blockchain Manager β
β (yfinance) β β(blockchain_integration)β
β β β β
β β’ Price data β β β’ Web3 connection β
β β’ Company info β β β’ Transaction signingβ
β β’ Historical data β β β’ Contract calls β
ββββββββββββββββββββββββ ββββββββββββ¬ββββββββββββ
β
βΌ
ββββββββββββββββββββββββ
β Ethereum Network β
β (Local/Testnet/Main)β
β β
β PortfolioTracker.sol β
β β’ addInvestment() β
β β’ getInvestments() β
β β’ removeInvestment()β
ββββββββββββββββββββββββ
ai-stock-analyst-blockchain/
β
βββ backend/ # Python application
β βββ __init__.py # Package initialization
β βββ app.py # Main Gradio application (500+ lines)
β βββ blockchain_integration.py # Web3 blockchain manager (350+ lines)
β βββ portfolio_manager.py # Portfolio logic (300+ lines)
β βββ stock_advisor.py # Stock analysis engine (400+ lines)
β βββ requirements.txt # Python dependencies
β βββ .env # Backend configuration
β βββ contract_abi.json # Smart contract ABI (auto-generated)
β βββ contract_info.json # Deployment info (auto-generated)
β
βββ blockchain/ # Smart contract project
β βββ contracts/
β β βββ PortfolioTracker.sol # Main smart contract (250+ lines)
β β
β βββ scripts/
β β βββ deploy.js # Deployment automation (150+ lines)
β β βββ interact.js # Contract testing script (200+ lines)
β β
β βββ test/
β β βββ PortfolioTracker.test.js # 20+ test cases (300+ lines)
β β
β βββ deployments/ # Deployment records (auto-generated)
β βββ hardhat.config.js # Hardhat configuration
β βββ package.json # Node.js dependencies
β βββ .env # Blockchain configuration
β
βββ artifacts/ # Compiled contracts (auto-generated)
β βββ contracts/
β βββ PortfolioTracker.sol/
β βββ PortfolioTracker.json # Contract ABI + bytecode
β βββ PortfolioTracker.dbg.json # Debug information
β
βββ .env # Root environment variables
βββ .gitignore # Git ignore rules
βββ README.md # This file
Total Lines of Code: ~2,500+ lines across 15+ files
Ensure you have these installed:
- Node.js 16.0.0 or higher (Download)
- Python 3.9 or higher (Download)
- npm or yarn package manager
- Git for version control
- MetaMask browser extension (optional, for mainnet)
Verify installations:
node --version # Should show v16.x.x or higher
python --version # Should show Python 3.9.x or higher
npm --version # Should show 8.x.x or higher
# OR
yarn --version # Should show 1.x.x or 3.x.x# 1. Clone or create project directory
mkdir ai-stock-analyst-blockchain && cd ai-stock-analyst-blockchain
# 2. Create folder structure
mkdir -p backend blockchain/contracts blockchain/scripts blockchain/test artifacts
# 3. Copy all provided code files into respective folders
# 4. Install blockchain dependencies
cd blockchain
npm install
# OR
yarn install
# 5. Install Python dependencies
cd ../backend
pip install -r requirements.txt
# 6. Configure environment variables (see Configuration section)
# 7. Start local blockchain (Terminal 1)
cd ../blockchain
npx hardhat node
# 8. Deploy smart contract (Terminal 2)
npx hardhat compile
npx hardhat run scripts/deploy.js --network localhost
# 9. Update backend/.env with contract address and private key
# 10. Run application (Terminal 3)
cd ../backend
python app.py
# 11. Open browser
# Navigate to http://localhost:7860# Create main directory
mkdir ai-stock-analyst-blockchain
cd ai-stock-analyst-blockchain
# Create all subdirectories
mkdir -p backend blockchain/contracts blockchain/scripts blockchain/test artifacts/contracts/PortfolioTracker.solPlace the provided code files in their respective locations:
- Backend Python files β
backend/ - Smart contracts β
blockchain/contracts/ - Scripts β
blockchain/scripts/ - Tests β
blockchain/test/ - Configuration files β Root and respective folders
Blockchain (Node.js):
cd blockchain
# Using npm
npm install
# OR using yarn
yarn install
# Verify installation
ls node_modules | wc -l
# Should show 200+ packagesBackend (Python):
cd ../backend
pip install -r requirements.txt
# Verify installation
pip list | grep -E "gradio|yfinance|web3"
# Should show all three packagesPROJECT_NAME=ai-stock-analyst-blockchain
ENVIRONMENT=development
BLOCKCHAIN_ENABLED=True
CONTRACT_ADDRESS= # Filled after deployment
RPC_URL=http://127.0.0.1:8545 # Local node
NETWORK=localhost
GRADIO_PORT=7860
GRADIO_SHARE=False
DEBUG_MODE=True# For testnet/mainnet deployment
SEPOLIA_RPC_URL=https://eth-sepolia.g.alchemy.com/v2/YOUR_KEY
MAINNET_RPC_URL=https://eth-mainnet.g.alchemy.com/v2/YOUR_KEY
PRIVATE_KEY=your_private_key_here
ETHERSCAN_API_KEY=your_etherscan_key
REPORT_GAS=falseBLOCKCHAIN_ENABLED=True
CONTRACT_ADDRESS=0x5FbDB2315678afecb367f032d93F642f64180aa3 # From deployment
RPC_URL=http://127.0.0.1:8545
WALLET_PRIVATE_KEY=0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80 # Test account
GRADIO_PORT=7860
GRADIO_SHARE=False
DEBUG_MODE=True| Network | RPC URL | Chain ID | Cost |
|---|---|---|---|
| Hardhat (Local) | http://127.0.0.1:8545 | 1337 | Free |
| Sepolia Testnet | alchemy.com/sepolia | 11155111 | Free (testnet ETH) |
| Ethereum Mainnet | alchemy.com/mainnet | 1 | Real ETH required |
Terminal 1: Blockchain Node
cd blockchain
npx hardhat nodeThis provides 20 test accounts with 10,000 ETH each.
Terminal 2: Deploy Contract
cd blockchain
npx hardhat compile
npx hardhat run scripts/deploy.js --network localhostCopy the contract address and Account #0 private key.
Terminal 3: Run Application
cd backend
python app.pyOpen http://localhost:7860 in your browser.
Steps:
- Navigate to "Stock Analysis" tab
- Enter company name (e.g., "Apple", "Microsoft") or symbol (e.g., "AAPL", "MSFT")
- Click "Analyze Stock" button
- Wait 5-10 seconds for analysis
Output includes:
- Current price and daily change
- 52-week high/low
- AI recommendation (BUY/HOLD/SELL) with confidence score
- Technical indicators (RSI, MACD, Bollinger Bands)
- Buy/sell signals based on indicators
- Volume analysis
- Company information (sector, industry, market cap)
Add Investment:
- Go to "Portfolio Management" β "Add Investment" tab
- Fill in details:
- Company Name:
Apple - Shares:
10 - Price:
175.50 - Date:
2025-10-28
- Company Name:
- Click "Add to Portfolio"
- If blockchain enabled: Transaction executes on-chain (~10-15 seconds)
View Portfolio:
- Go to "View Portfolio" tab
- Click "Refresh Portfolio"
- See:
- Total invested amount
- Current portfolio value
- Overall gain/loss percentage
- Individual holdings with real-time prices
- Blockchain verification badges (π) for on-chain investments
Remove Investment:
- Go to "Remove Investment" tab
- Copy investment ID from portfolio view
- Paste ID and click "Remove Investment"
Connect Wallet:
- Navigate to "Blockchain" β "Connect Wallet" tab
- Enter:
- Private Key:
0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80 - Contract Address:
0x5FbDB2315678afecb367f032d93F642f64180aa3
- Private Key:
- Click "Connect Blockchain"
- Confirmation shows wallet address, contract address, chain ID
Sync from Blockchain:
- Go to "Sync Portfolio" tab
- Click "Sync from Blockchain"
- All on-chain investments load into local database
View Statistics:
- Go to "Blockchain Stats" tab
- Click "Get Statistics"
- See:
- Active investment count
- Total invested amount (from blockchain)
- Wallet and contract addresses
- Navigate to "Compare Stocks" tab
- Enter two stock symbols (e.g., "AAPL" and "MSFT")
- Click "Compare Stocks"
- View side-by-side comparison table with:
- Current prices
- 6-month returns
- Volatility comparison
- Market caps
- P/E ratios
- Performance winner
- Go to "Market Overview" tab
- Click "Refresh Market Data"
- See real-time prices and changes for:
- S&P 500
- Dow Jones
- NASDAQ
- NIFTY 50
- SENSEX
Contract Address (Local): 0x5FbDB2315678afecb367f032d93F642f64180aa3
struct Investment {
string company;
string symbol;
uint256 shares;
uint256 purchasePrice;
uint256 timestamp;
address investor;
bool active;
}| Function | Parameters | Returns | Gas Cost | Description |
|---|---|---|---|---|
addInvestment |
company, symbol, shares, price | investmentId | ~245K | Adds new investment |
removeInvestment |
investmentId | - | ~45K | Marks investment inactive |
getInvestment |
investmentId | Investment details | View | Gets single investment |
getMyInvestmentIds |
- | uint256[] | View | Gets all user IDs |
getActiveInvestmentCount |
- | uint256 | View | Counts active investments |
getTotalInvested |
- | uint256 | View | Calculates total invested |
getAllMyInvestments |
- | Multiple arrays | View | Batch retrieval |
event InvestmentAdded(
address indexed investor,
uint256 indexed investmentId,
string company,
string symbol,
uint256 shares,
uint256 price,
uint256 timestamp
);
event InvestmentRemoved(
address indexed investor,
uint256 indexed investmentId,
uint256 timestamp
);- Access Control: Each user can only access their own investments
- Input Validation: Checks for empty strings and zero values
- Gas Optimization: Efficient storage patterns and minimal loops
- Event Logging: All state changes emit events for tracking
- Reentrancy Protection: No external calls in state-changing functions
Run all tests:
cd blockchain
npx hardhat testTest Coverage:
- β Deployment verification (1 test)
- β Investment addition (4 tests)
- β Investment retrieval (2 tests)
- β Investment removal (4 tests)
- β Portfolio statistics (3 tests)
- β Batch operations (2 tests)
- β Multi-user isolation (1 test)
Total: 20+ tests covering all contract functionality
Sample output:
PortfolioTracker
Deployment
β Should deploy with investment counter at 0 (45ms)
Adding Investments
β Should add investment successfully (67ms)
β Should emit InvestmentAdded event (54ms)
β Should revert with empty company name (31ms)
β Should revert with zero shares (28ms)
...
20 passing (3.5s)
cd backend
pytestAlready configured! Run:
# Terminal 1
npx hardhat node
# Terminal 2
npx hardhat run scripts/deploy.js --network localhost
# Terminal 3
python app.pyStep 1: Get Testnet ETH
Visit Sepolia Faucet and request testnet ETH.
Step 2: Configure Environment
Update blockchain/.env:
SEPOLIA_RPC_URL=https://eth-sepolia.g.alchemy.com/v2/YOUR_ALCHEMY_KEY
PRIVATE_KEY=your_wallet_private_keyStep 3: Deploy
cd blockchain
npx hardhat run scripts/deploy.js --network sepoliaStep 4: Verify on Etherscan
npx hardhat verify --network sepolia CONTRACT_ADDRESSStep 5: Update Backend
Update backend/.env with new contract address and Sepolia RPC URL.
- Security Audit: Have smart contract professionally audited
- Test Thoroughly: Run extensive tests on testnet for weeks
- Update Configuration: Use mainnet RPC URLs
- Deploy: Use production private key (NEVER commit to Git)
- Verify: Verify contract on Etherscan for transparency
- Monitor: Set up monitoring for unusual activity
Problem: Python app can't reach Hardhat node
Solution:
# Ensure Hardhat node is running
cd blockchain
npx hardhat node
# Check if port 8545 is available
lsof -i :8545Problem: Wrong contract address in .env
Solution:
# Redeploy contract
npx hardhat run scripts/deploy.js --network localhost
# Copy new contract address to backend/.envProblem: Test account out of ETH (unlikely in local development)
Solution:
# Restart Hardhat node to reset balances
# Stop node (Ctrl+C) and restart
npx hardhat nodeProblem: Missing Python or Node packages
Solution:
# Reinstall Python dependencies
pip install -r backend/requirements.txt
# Reinstall Node dependencies
cd blockchain
npm installProblem: Smart contract execution error
Solution:
# Check Hardhat node terminal for error details
# Common causes:
# - Invalid parameters (empty strings, zero values)
# - Gas limit too low
# - Wrong network selected- Stock analysis with technical indicators
- Portfolio management (local + blockchain)
- Smart contract deployment
- Gradio web interface
- Multi-network support
- Advanced charting with Plotly
- Historical backtesting engine
- More technical indicators (Fibonacci, Ichimoku Cloud)
- Sentiment analysis from news articles
- Custom alert system
- Multi-chain support (Polygon, BSC, Arbitrum)
- NFT certificates for investments
- DAO governance for platform decisions
- Token-based rewards system
- Layer 2 scaling solutions
- Social trading features
- Portfolio sharing and comparison
- Community stock ratings
- Expert analyst integration
- Educational resources
- Mobile app (React Native)
- REST API for third-party integration
- Webhook notifications
- Desktop application
- Browser extension
We welcome contributions! Please follow these guidelines:
- Fork the repository
- Create a feature branch (
git checkout -b feature/AmazingFeature) - Commit your changes (
git commit -m 'Add AmazingFeature') - Push to branch (
git push origin feature/AmazingFeature) - Open a Pull Request
Python:
- Follow PEP 8 style guide
- Use type hints where possible
- Write docstrings for all functions
- Add unit tests for new features
Solidity:
- Follow Solidity style guide
- Use NatSpec comments
- Write comprehensive tests
- Gas optimization is priority
JavaScript:
- Use ES6+ features
- Follow Airbnb style guide
- Add JSDoc comments
- Test all scripts
All PRs must:
- Pass all existing tests
- Include tests for new features
- Maintain or improve code coverage
- Pass linting checks
This project is licensed under the MIT License - see the LICENSE file for details.
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
- Yahoo Finance for providing free stock market data API
- Hardhat team for excellent Ethereum development tools
- Gradio for the intuitive UI framework
- OpenZeppelin for secure smart contract patterns
- Ethereum Foundation for blockchain innovation
- Community Contributors for feedback and improvements
Bhoomika M
- GitHub: [@Bhoomika M](https://github.com/Bhoomika M)
- Project: AI Stock Analyst with Blockchain Integration
- Version: 1.0.0
- Contact: Via GitHub Issues
For issues, questions, or suggestions:
- π§ Email: Create a GitHub Issue
- π¬ Discord: Coming soon
- π Bug Reports: [GitHub Issues](https://github.com/Bhoomika M/ai-stock-analyst-blockchain/issues)
- π‘ Feature Requests: [GitHub Discussions](https://github.com/Bhoomika M/ai-stock-analyst-blockchain/discussions)
- Total Lines of Code: ~2,500+
- Programming Languages: Python, Solidity, JavaScript
- Smart Contract Functions: 9
- Test Coverage: 20+ tests
- Supported Companies: 80+
- Supported Markets: NYSE, NASDAQ, NSE (India)
- Development Time: Ongoing
- Contributors: Open for contributions!
If you discover a security vulnerability, please:
- DO NOT open a public issue
- Email details to: [Create private security advisory on GitHub]
- Include steps to reproduce
- Allow time for fix before disclosure
- β
Never commit
.envfiles - β Use separate wallets for dev/test/prod
- β Enable 2FA on all accounts
- β Regular security audits for smart contracts
- β Keep dependencies updated
- β Use hardware wallets for mainnet
- β Test extensively on testnet first
Built with β€οΈ using Python, Solidity, and Blockchain Technology
β Star this repo if you find it useful!
Last Updated: October 28, 2025