Skip to content

kklmfao/stock-analyzer

Repository files navigation

Stock Analyzer Web App

A comprehensive web application for analyzing stocks, managing portfolios, and tracking watchlists. Built with Python and Flask, this project provides a modern, responsive interface for stock analysis and portfolio management.

Features

  • Real-time Stock Analysis: Get live stock data and analysis using the Yahoo Finance API
  • Advanced Caching: TTL-based caching system for optimal performance and data freshness
  • Async Data Fetching: Concurrent data retrieval for improved response times
  • Portfolio Management: Track your stock holdings, view performance metrics, and analyze returns
  • Watchlist: Monitor potential investments with a customizable watchlist
  • Interactive Charts: View historical price data with interactive charts
  • Responsive Design: Modern, mobile-friendly interface
  • User Preferences: Customizable settings for theme, currency, and notifications
  • Modular Architecture: Blueprint-based structure for easy maintenance and scalability

Tech Stack

  • Backend: Python, Flask
  • Data Source: yfinance (Yahoo Finance API)
  • Frontend: HTML5, CSS3, JavaScript
  • Charts: Chart.js
  • Template Engine: Jinja2
  • Environment Management: python-dotenv
  • Caching: cachetools
  • Async Support: aiohttp, asyncio

Project Structure

stock-analyzer/
├── app.py                    # Main Flask application
├── config.py                 # Configuration management
├── modules/
│   ├── analysis.py          # Stock analysis logic
│   ├── stock_data.py        # Stock data fetching service with caching
│   ├── exceptions.py        # Custom exceptions and logging
│   └── data_store.py        # Data management
├── routes/
│   ├── __init__.py          # Routes package
│   ├── analysis.py          # Analysis routes
│   ├── dashboard.py         # Dashboard routes
│   ├── portfolio.py         # Portfolio routes
│   ├── settings.py          # Settings routes
│   └── watchlist.py         # Watchlist routes
├── templates/
│   ├── base.html            # Base template
│   ├── dashboard.html       # Dashboard view
│   ├── index.html           # Analysis form
│   ├── portfolio.html       # Portfolio view
│   ├── result.html          # Analysis results
│   ├── settings.html        # Settings page
│   └── watchlist.html       # Watchlist view
├── static/
│   └── css/
│       └── style.css        # Application styles
├── logs/                    # Application logs directory
├── .env.example             # Example environment variables
├── .gitignore              # Git ignore file
├── README.md               # Documentation
└── requirements.txt        # Python dependencies

Environment Setup

  1. Create a .env file in the project root:

    cp .env.example .env
  2. Update the .env file with your configuration:

    • SECRET_KEY: Generate a secure random key for session management
    • FLASK_ENV: Set to 'development' or 'production'
    • FLASK_HOST: Host address (default: 0.0.0.0)
    • FLASK_PORT: Port number (default: 8000)
    • CACHE_TIMEOUT: Data cache timeout in seconds (default: 60)
  3. Generate a secure secret key:

    python -c "import secrets; print(secrets.token_hex(32))"

    Copy the output and use it as your SECRET_KEY in the .env file.

Installation

  1. Clone the Repository:

    git clone <repository-url>
    cd stock-analyzer
  2. Create and activate a virtual environment:

    python -m venv venv
    source venv/bin/activate  # On Windows: venv\Scripts\activate
  3. Install dependencies:

    pip install -r requirements.txt

Running the Application

  1. Ensure your .env file is properly configured
  2. Activate the virtual environment if not already active
  3. Start the application:
    python app.py
  4. Access the application at http://localhost:8000

Features in Detail

Performance Optimizations

  • TTL-Based Caching: Implements time-based caching for stock data and historical information
  • Concurrent Data Fetching: Uses async/await for parallel data retrieval
  • Cache Configuration: Configurable cache timeouts and size limits
  • Memory Management: Automatic cache cleanup for optimal memory usage

Dashboard

  • Overview of portfolio performance
  • Quick access to all major functions
  • Real-time portfolio value and returns

Portfolio Management

  • Track multiple stock holdings
  • View individual stock performance
  • Calculate returns and total value
  • Sector allocation visualization

Stock Analysis

  • Real-time stock data
  • Historical price charts
  • Key metrics and indicators
  • Interactive period selection

Watchlist

  • Track potential investments
  • Quick access to stock analysis
  • Real-time price updates

Settings

  • Theme customization
  • Currency preference
  • Notification settings
  • Data refresh interval

Security Notes

  • Never commit the .env file to version control
  • Use strong, unique secret keys in production
  • Keep dependencies up to date
  • Review security settings before deploying to production
  • Implement rate limiting for API calls
  • Monitor API usage to stay within limits

Future Improvements

  • User authentication and multiple portfolios
  • Advanced technical analysis indicators
  • Export functionality for portfolio data
  • Email notifications for price alerts
  • Integration with additional data sources
  • Mobile app version
  • Social sharing features
  • Backtesting capabilities
  • Distributed caching support
  • Real-time WebSocket updates

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

This project is open-source and available under the MIT License.

Testing

Running Tests

To run the test suite:

# Run all tests
pytest

# Run with coverage report
pytest --cov=. --cov-report=html

# Run specific test file
pytest tests/modules/test_stock_data.py

# Run tests matching a pattern
pytest -k "test_stock_data"

Test Structure

The test suite follows the same structure as the source code:

tests/
├── conftest.py              # Shared test fixtures
├── modules/
│   ├── test_stock_data.py   # StockDataService tests
│   └── test_analysis.py     # Analysis module tests
└── routes/
    ├── test_analysis.py     # Analysis routes tests
    ├── test_dashboard.py    # Dashboard routes tests
    ├── test_portfolio.py    # Portfolio routes tests
    └── test_watchlist.py    # Watchlist routes tests

Code Quality Tools

The project uses several tools to maintain code quality:

  1. Ruff: For linting and code formatting

    # Check code style
    ruff check .
    
    # Format code
    ruff format .
  2. MyPy: For static type checking

    mypy .
  3. Coverage: For test coverage reporting

    • View the HTML coverage report in htmlcov/index.html
    • Minimum coverage threshold: 80%

Writing Tests

When writing new tests:

  1. Follow the existing test structure
  2. Include docstrings with Args/Returns sections
  3. Use type hints consistently
  4. Create fixtures for reusable test data
  5. Mock external dependencies
  6. Test both success and error cases
  7. Verify edge cases and boundary conditions

Continuous Integration

The test suite runs automatically on:

  • Every pull request
  • Merges to main branch
  • Daily scheduled runs

Builds will fail if:

  • Any test fails
  • Coverage drops below 80%
  • Type checking errors exist
  • Linting errors are present

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors