File size: 8,589 Bytes
72fc0ee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
"""
Metrics collection and Prometheus integration.

Provides:
  - Counter, Gauge, Histogram, Summary metrics
  - Custom business metrics (trades, calculations, errors)
  - Prometheus exposition
  - Metric labels and aggregation
"""

from __future__ import annotations

import logging
import time
from contextlib import contextmanager
from dataclasses import dataclass, field
from typing import Any, Callable, Optional

from prometheus_client import (
    Counter,
    Gauge,
    Histogram,
    Summary,
    CollectorRegistry,
    generate_latest,
    CONTENT_TYPE_LATEST,
)

log = logging.getLogger(__name__)


# === Global Registry ===

# Custom registry to avoid conflicts with default
METRICS_REGISTRY = CollectorRegistry()


# === Core Business Metrics ===

# Calculation counters
calculations_total = Counter(
    'quantlib_calculations_total',
    'Total number of calculations performed',
    ['calculation_type', 'status'],
    registry=METRICS_REGISTRY,
)

calculation_duration = Histogram(
    'quantlib_calculation_duration_seconds',
    'Calculation duration in seconds',
    ['calculation_type'],
    buckets=[0.001, 0.01, 0.1, 0.5, 1.0, 5.0, 10.0],
    registry=METRICS_REGISTRY,
)

# Portfolio metrics
portfolio_value = Gauge(
    'quantlib_portfolio_value_usd',
    'Current portfolio value in USD',
    ['portfolio_id'],
    registry=METRICS_REGISTRY,
)

portfolio_var = Gauge(
    'quantlib_portfolio_var_usd',
    'Portfolio Value-at-Risk in USD',
    ['portfolio_id', 'confidence'],
    registry=METRICS_REGISTRY,
)

# Trade metrics
trades_executed = Counter(
    'quantlib_trades_executed_total',
    'Total number of trades executed',
    ['asset_class', 'side'],
    registry=METRICS_REGISTRY,
)

trade_slippage = Summary(
    'quantlib_trade_slippage_bps',
    'Trade slippage in basis points',
    ['asset_class'],
    registry=METRICS_REGISTRY,
)

# Data quality metrics
data_quality_score = Gauge(
    'quantlib_data_quality_score',
    'Data quality score [0, 1]',
    ['source', 'asset'],
    registry=METRICS_REGISTRY,
)

missing_data_points = Counter(
    'quantlib_missing_data_points_total',
    'Total missing data points detected',
    ['source', 'asset'],
    registry=METRICS_REGISTRY,
)

# Cache metrics
cache_hits = Counter(
    'quantlib_cache_hits_total',
    'Total cache hits',
    ['cache_name'],
    registry=METRICS_REGISTRY,
)

cache_misses = Counter(
    'quantlib_cache_misses_total',
    'Total cache misses',
    ['cache_name'],
    registry=METRICS_REGISTRY,
)

# Error metrics
errors_total = Counter(
    'quantlib_errors_total',
    'Total errors encountered',
    ['error_type', 'module'],
    registry=METRICS_REGISTRY,
)

# API metrics
api_requests = Counter(
    'quantlib_api_requests_total',
    'Total API requests',
    ['endpoint', 'method', 'status'],
    registry=METRICS_REGISTRY,
)

api_latency = Histogram(
    'quantlib_api_latency_seconds',
    'API request latency',
    ['endpoint'],
    buckets=[0.01, 0.05, 0.1, 0.5, 1.0, 5.0],
    registry=METRICS_REGISTRY,
)


# === Metric Helpers ===

@contextmanager
def track_calculation(calc_type: str):
    """
    Context manager to track calculation metrics.
    
    Usage:
        with track_calculation('black_scholes'):
            result = price_option(...)
    """
    start = time.perf_counter()
    status = 'success'
    
    try:
        yield
    except Exception as e:
        status = 'error'
        errors_total.labels(error_type=type(e).__name__, module='calculation').inc()
        raise
    finally:
        duration = time.perf_counter() - start
        calculations_total.labels(calculation_type=calc_type, status=status).inc()
        calculation_duration.labels(calculation_type=calc_type).observe(duration)


@contextmanager
def track_api_request(endpoint: str, method: str = 'GET'):
    """
    Context manager to track API request metrics.
    
    Usage:
        with track_api_request('/api/portfolio', 'GET'):
            response = handle_request()
    """
    start = time.perf_counter()
    status = '200'
    
    try:
        yield
    except Exception as e:
        status = '500'
        errors_total.labels(error_type=type(e).__name__, module='api').inc()
        raise
    finally:
        duration = time.perf_counter() - start
        api_requests.labels(endpoint=endpoint, method=method, status=status).inc()
        api_latency.labels(endpoint=endpoint).observe(duration)


def record_trade(asset_class: str, side: str, slippage_bps: float):
    """
    Record trade execution metrics.
    
    Parameters
    ----------
    asset_class : str
        Asset class ('equity', 'bond', 'option', etc.)
    side : str
        Trade side ('buy' or 'sell')
    slippage_bps : float
        Slippage in basis points
    """
    trades_executed.labels(asset_class=asset_class, side=side).inc()
    trade_slippage.labels(asset_class=asset_class).observe(slippage_bps)


def record_cache_access(cache_name: str, hit: bool):
    """
    Record cache access.
    
    Parameters
    ----------
    cache_name : str
        Name of cache
    hit : bool
        True if cache hit, False if miss
    """
    if hit:
        cache_hits.labels(cache_name=cache_name).inc()
    else:
        cache_misses.labels(cache_name=cache_name).inc()


def update_portfolio_metrics(portfolio_id: str, value: float, var_95: float, var_99: float):
    """
    Update portfolio metrics.
    
    Parameters
    ----------
    portfolio_id : str
        Portfolio identifier
    value : float
        Portfolio value (USD)
    var_95 : float
        95% VaR (USD)
    var_99 : float
        99% VaR (USD)
    """
    portfolio_value.labels(portfolio_id=portfolio_id).set(value)
    portfolio_var.labels(portfolio_id=portfolio_id, confidence='95').set(var_95)
    portfolio_var.labels(portfolio_id=portfolio_id, confidence='99').set(var_99)


def record_data_quality(source: str, asset: str, quality_score: float, missing_count: int = 0):
    """
    Record data quality metrics.
    
    Parameters
    ----------
    source : str
        Data source
    asset : str
        Asset identifier
    quality_score : float
        Quality score [0, 1]
    missing_count : int
        Number of missing data points
    """
    data_quality_score.labels(source=source, asset=asset).set(quality_score)
    
    if missing_count > 0:
        missing_data_points.labels(source=source, asset=asset).inc(missing_count)


def export_metrics() -> tuple[bytes, str]:
    """
    Export metrics in Prometheus format.
    
    Returns
    -------
    tuple[bytes, str]
        (metrics_data, content_type)
    """
    return generate_latest(METRICS_REGISTRY), CONTENT_TYPE_LATEST


@dataclass
class MetricSnapshot:
    """Snapshot of current metrics."""
    timestamp: float
    calculations_total: int = 0
    trades_total: int = 0
    errors_total: int = 0
    cache_hit_rate: float = 0.0
    avg_calculation_duration: float = 0.0
    
    def to_dict(self) -> dict[str, Any]:
        """Convert to dictionary."""
        return {
            'timestamp': self.timestamp,
            'calculations_total': self.calculations_total,
            'trades_total': self.trades_total,
            'errors_total': self.errors_total,
            'cache_hit_rate': self.cache_hit_rate,
            'avg_calculation_duration': self.avg_calculation_duration,
        }


def get_metrics_snapshot() -> MetricSnapshot:
    """
    Get current metrics snapshot.
    
    Returns
    -------
    MetricSnapshot
        Current metrics
    """
    # This is a simplified snapshot - in production would query actual metrics
    return MetricSnapshot(
        timestamp=time.time(),
        calculations_total=0,
        trades_total=0,
        errors_total=0,
        cache_hit_rate=0.0,
        avg_calculation_duration=0.0,
    )


# === Custom Metric Decorator ===

def measure_time(metric_name: str, labels: Optional[dict[str, str]] = None):
    """
    Decorator to measure function execution time.
    
    Usage:
        @measure_time('my_function', labels={'module': 'portfolio'})
        def my_function():
            ...
    """
    def decorator(func: Callable) -> Callable:
        def wrapper(*args, **kwargs):
            start = time.perf_counter()
            try:
                result = func(*args, **kwargs)
                return result
            finally:
                duration = time.perf_counter() - start
                log.debug(f"{metric_name} took {duration:.4f}s")
                # Could also record to a metric here
        return wrapper
    return decorator