Quotes Analytics API

Quotes Analytics API - Market Data Analytics & Reporting

Overview

The QuotesAnalyticsController is a C++ REST API controller that generates comprehensive market analytics reports by analyzing quote data across multiple asset classes. It provides insights into market movements, top performers, and statistical summaries.

Features

  • Multi-Asset Coverage: Analyzes stocks, crypto, ETFs, commodities, currencies, and more
  • Top Performers Analysis: Identifies top gainers, losers, and most active assets
  • Market Statistics: Calculates aggregate metrics by asset type
  • Real-time Reporting: Generates JSON reports from current market data
  • MongoDB Integration: Queries quote data from multiple collections

Architecture

Data Models

QuoteData

struct QuoteData {
    std::string sravz_id;
    std::string symbol;
    std::string name;
    std::string asset_type;  // stocks, crypto, etf, etc.
    double last_price;
    double change;
    double change_percent;
    double volume;
    double open;
    double high;
    double low;
    double previous_close;
    std::string price_capture_time;
};

AnalyticsSummary

struct AnalyticsSummary {
    int total_assets;
    std::vector<QuoteData> top_gainers;
    std::vector<QuoteData> top_losers;
    std::vector<QuoteData> most_active;
    std::map<std::string, int> asset_type_counts;
    std::map<std::string, double> avg_change_by_type;
    double overall_market_change;
    std::string report_timestamp;
};

API Endpoint

Generate Quotes Analytics Report

Endpoint: GET /api/analytics/quotes?top_count=10

Generates a comprehensive market analytics report.

Query Parameters:

  • top_count (optional): Number of top performers to include (default: 10)

Response:

{
    "report_timestamp": "2024-11-24T10:30:00Z",
    "total_assets": 5247,
    "overall_market_change": 0.45,
    "top_gainers": [
        {
            "sravz_id": "NVDA",
            "symbol": "NVDA",
            "name": "NVIDIA Corporation",
            "asset_type": "stocks",
            "last_price": 485.50,
            "change": 25.30,
            "change_percent": 5.50,
            "volume": 45000000
        }
    ],
    "top_losers": [
        {
            "sravz_id": "XYZ",
            "symbol": "XYZ",
            "name": "XYZ Corp",
            "asset_type": "stocks",
            "last_price": 45.20,
            "change": -3.50,
            "change_percent": -7.20,
            "volume": 12000000
        }
    ],
    "most_active": [
        {
            "sravz_id": "TSLA",
            "symbol": "TSLA",
            "name": "Tesla Inc",
            "asset_type": "stocks",
            "last_price": 245.00,
            "volume": 125000000
        }
    ],
    "asset_type_counts": {
        "stocks": 3500,
        "crypto": 250,
        "etf": 1200,
        "commodities": 50,
        "currency": 200,
        "index": 25,
        "futures": 22
    },
    "avg_change_by_type": {
        "stocks": 0.35,
        "crypto": 1.25,
        "etf": 0.28,
        "commodities": -0.15,
        "currency": 0.05
    }
}

Supported Asset Classes

The controller analyzes quotes from the following MongoDB collections:

  1. quotes_stocks - Stock market quotes
  2. quotes_crypto - Cryptocurrency quotes
  3. quotes_etf - ETF quotes
  4. quotes_commodities - Commodity quotes
  5. quotes_currency - Foreign exchange quotes
  6. quotes_index - Market index quotes
  7. quotes_futures - Futures contracts
  8. quotes_mortgage - Mortgage rates
  9. quotes_rates - Interest rates
  10. quotes_vix - Volatility index

Implementation Details

Analytics Calculation Workflow

  1. Load All Quotes: Query all quote collections from MongoDB
  2. Parse Quote Data: Convert MongoDB documents to QuoteData structures
  3. Calculate Top Gainers: Sort by change_percent (descending)
  4. Calculate Top Losers: Sort by change_percent (ascending)
  5. Calculate Most Active: Sort by volume (descending)
  6. Aggregate by Type: Count and average changes by asset type
  7. Calculate Overall Market: Weighted average of all asset changes
  8. Generate Report: Serialize analytics to JSON

Top Performers Logic

// Top Gainers: Sort by change_percent descending
std::sort(quotes.begin(), quotes.end(), 
    [](const QuoteData& a, const QuoteData& b) {
        return a.change_percent > b.change_percent;
    });

// Top Losers: Sort by change_percent ascending
std::sort(quotes.begin(), quotes.end(), 
    [](const QuoteData& a, const QuoteData& b) {
        return a.change_percent < b.change_percent;
    });

// Most Active: Sort by volume descending
std::sort(quotes.begin(), quotes.end(), 
    [](const QuoteData& a, const QuoteData& b) {
        return a.volume > b.volume;
    });

Usage Example

Generate Analytics Report

#include <quotes_analytics_controller.hpp>

auto mongoClient = std::make_shared<MongoClient>();
auto analyticsController = std::make_shared<QuotesAnalyticsController>(mongoClient);

// Generate report with top 10 performers
std::string report = analyticsController->generateQuotesReport(10);

// Generate report with top 25 performers
std::string detailed_report = analyticsController->generateQuotesReport(25);

Integration with Router

// In router.cpp
void router::handle_get_analytics_quotes(http::request<http::string_body> &req, 
                                         http::response<http::string_body> &res) {
    // Parse top_count from query parameters (default: 10)
    int top_count = extract_query_param(req.target(), "top_count", 10);
    
    std::string report = quotesAnalyticsController_->generateQuotesReport(top_count);
    
    res.body() = report;
    res.set(http::field::content_type, "application/json");
    res.result(http::status::ok);
}

Performance Considerations

Optimization Strategies

  1. Efficient Queries: Use MongoDB projection to fetch only needed fields
  2. Parallel Collection Queries: Query multiple collections concurrently
  3. In-Memory Sorting: All sorting done in-memory for speed
  4. Minimal Allocations: Reuse vectors and avoid unnecessary copies
  5. Lazy Evaluation: Only calculate requested analytics

Scaling for Large Datasets

// For very large datasets, consider:
// 1. Pagination
// 2. MongoDB aggregation pipelines
// 3. Pre-calculated daily summaries
// 4. Caching frequent reports

Error Handling

try {
    std::string report = analyticsController->generateQuotesReport(10);
} catch (const std::exception& e) {
    BOOST_LOG_TRIVIAL(error) << "Analytics generation failed: " << e.what();
    // Return error response
}

Use Cases

1. Market Dashboard

Display real-time market overview with top movers:

fetch('/api/analytics/quotes?top_count=10')
    .then(response => response.json())
    .then(data => {
        displayMarketOverview(data);
        displayTopGainers(data.top_gainers);
        displayTopLosers(data.top_losers);
    });

2. Alerts & Notifications

Monitor for significant market movements:

auto report = generateQuotesReport(50);
auto summary = parseReport(report);

if (summary.overall_market_change > 2.0) {
    sendAlert("Significant market rally: +" + 
              std::to_string(summary.overall_market_change) + "%");
}

3. Research & Analysis

Analyze sector performance:

auto report = generateQuotesReport(100);
// Filter by asset_type
auto tech_stocks = filterByType(report, "tech_stocks");
// Calculate sector metrics
auto sector_analytics = calculateSectorMetrics(tech_stocks);

4. Trading Signals

Identify trading opportunities:

auto report = generateQuotesReport(25);
// Find high-volume gainers
auto signals = findHighVolumeGainers(report.most_active, report.top_gainers);

Testing

Unit Tests

TEST_F(QuotesAnalyticsTest, GenerateReport) {
    auto controller = createQuotesAnalyticsController();
    std::string report = controller->generateQuotesReport(10);
    ASSERT_FALSE(report.empty());
    
    // Validate JSON structure
    auto json_report = boost::json::parse(report);
    ASSERT_TRUE(json_report.is_object());
}

TEST_F(QuotesAnalyticsTest, TopGainers) {
    auto summary = loadTestData();
    ASSERT_EQ(summary.top_gainers.size(), 10);
    ASSERT_GT(summary.top_gainers[0].change_percent, 
              summary.top_gainers[1].change_percent);
}

Integration Tests

Tests verify:

  • Correct data loading from all quote collections
  • Accurate sorting of top performers
  • Proper JSON serialization
  • Error handling for missing data

Monitoring & Logging

The controller logs important metrics:

[INFO] Loading quotes from 10 collections...
[INFO] Loaded 5247 total quotes
[INFO] Calculated analytics: Top 10 performers
[INFO] Generated analytics report (12.5KB)
[DEBUG] Top gainer: NVDA +5.50%
[DEBUG] Top loser: XYZ -7.20%
[DEBUG] Overall market change: +0.45%

Future Enhancements

  1. Historical Trends: Track and compare analytics over time
  2. Sector Analysis: Group stocks by industry/sector
  3. Correlation Analysis: Find correlated asset movements
  4. Volatility Metrics: Calculate standard deviation and beta
  5. Custom Filters: Allow filtering by market cap, sector, etc.
  6. Real-time Streaming: WebSocket updates for live analytics
  7. Machine Learning: Predictive analytics using historical data
  8. Alerts Configuration: User-defined alert thresholds

See Also