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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
"""
Main API routers for quantitative finance endpoints.

Week 11: API Layer - REST endpoints for all QuantLib Pro functionality.
"""

import logging
from datetime import datetime
from typing import Annotated, Dict, List

import numpy as np
import pandas as pd
from fastapi import APIRouter, Depends, HTTPException, status

from quantlib_pro.api import dependencies as deps
from quantlib_pro.api import models
from quantlib_pro.observability import track_api_request, track_calculation

# Import core modules with correct names
from quantlib_pro.options import (
    bs_price,
    price_with_greeks,
    implied_volatility,
    price_european,
)
from quantlib_pro.portfolio import (
    max_sharpe_portfolio,
    efficient_frontier,
)
from quantlib_pro.risk import (
    calculate_var,
    run_stress_test,
)
from quantlib_pro.market_regime import (
    detect_regimes_hmm,
)
from quantlib_pro.volatility import (
    build_surface_from_prices,
)
from quantlib_pro.macro import (
    detect_macro_regime,
    correlation_regime,
    vix_sentiment_level,
    fear_greed_index,
)

logger = logging.getLogger(__name__)

# =============================================================================
# Portfolio Router
# =============================================================================

portfolio_router = APIRouter(
    prefix="/portfolio", 
    tags=["Portfolio Management"],
    responses={
        429: {"description": "Rate limit exceeded"},
        500: {"description": "Internal server error"}
    }
)


@portfolio_router.post(
    "/optimize",
    response_model=models.OptimizationResponse,
    summary="Enterprise Portfolio Optimization",
    description="**Institutional-grade Modern Portfolio Theory optimization** with advanced constraint handling and risk management for professional asset allocation.",
)
async def optimize_portfolio_endpoint(
    request: models.OptimizationRequest,
    _: Annotated[None, Depends(deps.check_rate_limit)],
) -> models.OptimizationResponse:
    """
    **Enterprise Portfolio Optimization using Modern Portfolio Theory**
    
    Optimize asset allocation using institutional-grade algorithms for maximum Sharpe ratio 
    or minimum variance portfolios with advanced constraint handling.
    
    **Features:**
    - **Markowitz Mean-Variance Optimization**: Nobel Prize-winning portfolio theory
    - **Risk-Return Optimization**: Maximum Sharpe ratio, minimum variance, target return
    - **Advanced Constraints**: Position limits, sector allocation, turnover constraints
    - **Transaction Cost Integration**: Slippage and commission modeling
    - **Multi-Asset Support**: Stocks, bonds, ETFs, commodities, currencies
    
    **Use Cases:**
    - **Institutional Asset Management**: Pension funds, endowments, sovereign wealth
    - **Hedge Fund Strategies**: Long/short equity, market neutral, risk parity
    - **Wealth Management**: High-net-worth portfolio construction
    - **Risk Budgeting**: Factor-based allocation and risk decomposition
    
    **Performance:**
    - **Sub-second optimization** for portfolios up to 1000 assets
    - **Enterprise caching** with Redis for repeated calculations
    - **99.9% uptime SLA** for Enterprise tier customers
    
    Args:
        request: Portfolio optimization parameters including assets, constraints, and objectives
    
    Returns:
        Optimized weights, expected return, volatility, Sharpe ratio, and risk analytics
    """
    
    with track_api_request("/portfolio/optimize", "POST"):
        try:
            with track_calculation("portfolio_optimization"):
                # Use production-optimized calculation with caching
                from quantlib_pro.api.optimizations import optimized_portfolio_calculation
                
                result = await optimized_portfolio_calculation(
                    tickers=request.tickers,
                    optimization_type="max_sharpe",
                    risk_free_rate=request.risk_free_rate,
                    allow_short=request.allow_short if hasattr(request, 'allow_short') else False
                )
                
                return models.OptimizationResponse(
                    optimal_weights=result['optimal_weights'],
                    expected_return=result['expected_return'],
                    volatility=result['volatility'],
                    sharpe_ratio=result['sharpe_ratio'],
                )
        
        except Exception as e:
            logger.error(f"Portfolio optimization failed: {e}")
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                detail=f"Optimization failed: {str(e)}",
            )


@portfolio_router.post(
    "/efficient-frontier",
    response_model=models.EfficientFrontierResponse,
    summary="Calculate efficient frontier",
)
async def calculate_efficient_frontier(
    request: models.EfficientFrontierRequest,
    _: Annotated[None, Depends(deps.check_rate_limit)],
) -> models.EfficientFrontierResponse:
    """
    Calculate efficient frontier for given assets.
    
    Computes optimal portfolios for different risk levels.
    
    Args:
        request: Efficient frontier parameters
    
    Returns:
        Efficient frontier points with returns, volatilities, and weights
    """
    with track_api_request("/portfolio/efficient-frontier", "POST"):
        try:
            with track_calculation("efficient_frontier"):
                # Use real efficient frontier calculation with caching
                from quantlib_pro.portfolio import efficient_frontier
                from quantlib_pro.api.optimizations import get_cached_market_data
                
                # Get market data
                market_data = await get_cached_market_data(request.tickers)
                returns = market_data.pct_change().dropna()
                expected_returns = returns.mean() * 252
                cov_matrix = returns.cov() * 252
                
                # Calculate efficient frontier
                target_returns = np.linspace(
                    expected_returns.min() * 1.1,
                    expected_returns.max() * 0.9,
                    request.num_points
                )
                
                frontier_results = []
                weights_list = []
                
                for target_ret in target_returns:
                    try:
                        from quantlib_pro.portfolio import target_return_portfolio
                        result = target_return_portfolio(
                            expected_returns=expected_returns,
                            cov_matrix=cov_matrix,
                            target_return=target_ret,
                            allow_short=False
                        )
                        frontier_results.append(result)
                        weights_list.append(result.to_dict())
                    except Exception as e:
                        logger.warning(f"Skipping target return {target_ret}: {e}")
                
                returns = [r.expected_return for r in frontier_results]
                volatilities = [r.volatility for r in frontier_results]
                sharpe_ratios = [
                    (r - request.risk_free_rate) / v
                    for r, v in zip(returns, volatilities)
                ]
                
                return models.EfficientFrontierResponse(
                    returns=returns,
                    volatilities=volatilities,
                    sharpe_ratios=sharpe_ratios,
                    weights=weights_list,
                )
        
        except Exception as e:
            logger.error(f"Efficient frontier calculation failed: {e}")
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                detail=str(e),
            )


# =============================================================================
# Options Router
# =============================================================================

options_router = APIRouter(
    prefix="/options", 
    tags=["Derivatives & Options"],
    responses={
        429: {"description": "Rate limit exceeded"},
        500: {"description": "Internal server error"}
    }
)


@options_router.post(
    "/black-scholes",
    response_model=models.BlackScholesResponse,
    summary="Calculate Black-Scholes option price",
)
async def black_scholes_pricing(
    request: models.BlackScholesRequest,
    _: Annotated[None, Depends(deps.check_rate_limit)],
) -> models.BlackScholesResponse:
    """
    Calculate European option price using Black-Scholes formula.
    
    Computes option price and full Greeks (Delta, Gamma, Vega, Theta, Rho)
    for European call and put options.
    
    Args:
        request: Black-Scholes pricing parameters
    
    Returns:
        Option price and Greeks
        
    Raises:
        HTTPException: If calculation fails or invalid parameters
    """
    with track_api_request("/options/black-scholes", "POST"):
        try:
            with track_calculation("black_scholes_pricing"):
                # Use optimized options pricing with caching
                from quantlib_pro.api.optimizations import optimized_option_pricing
                
                result = await optimized_option_pricing(
                    option_type=request.option_type.value,
                    spot_price=request.spot_price,
                    strike_price=request.strike_price,
                    time_to_expiry=request.time_to_expiry,
                    volatility=request.volatility,
                    risk_free_rate=request.risk_free_rate
                )
                
                greeks = result['greeks']
                
                return models.BlackScholesResponse(
                    option_price=result['option_price'],
                    delta=greeks.get("delta", 0.0),
                    gamma=greeks.get("gamma", 0.0),
                    vega=greeks.get("vega", 0.0),
                    theta=greeks.get("theta", 0.0),
                    rho=greeks.get("rho", 0.0)
                )
                
        except ValueError as e:
            logger.error(f"Black-Scholes calculation error: {e}")
            raise HTTPException(
                status_code=400,
                detail=f"Invalid parameters: {str(e)}"
            )
        except Exception as e:
            logger.error(f"Unexpected error in Black-Scholes: {e}")
            raise HTTPException(
                status_code=500,
                detail="Internal calculation error"
            )


@options_router.post(
    "/implied-volatility",
    response_model=models.ImpliedVolatilityResponse,
    summary="Calculate implied volatility",
)
async def implied_volatility_endpoint(
    request: models.ImpliedVolatilityRequest,
    _: Annotated[None, Depends(deps.check_rate_limit)],
) -> models.ImpliedVolatilityResponse:
    """
    Calculate implied volatility from market option price.
    
    Uses Newton-Raphson method to find the volatility that makes
    Black-Scholes price equal to the observed market price.
    
    Args:
        request: Implied volatility calculation parameters
    
    Returns:
        Implied volatility and convergence info
    """
    with track_api_request("/options/implied-volatility", "POST"):
        try:
            with track_calculation("implied_volatility"):
                # Validate market price makes sense
                intrinsic_value = max(
                    0,
                    request.spot_price - request.strike_price
                    if request.option_type == models.OptionType.CALL
                    else request.strike_price - request.spot_price
                )
                
                if request.market_price < intrinsic_value:
                    raise HTTPException(
                        status_code=400,
                        detail=f"Market price {request.market_price} below intrinsic value {intrinsic_value}"
                    )
                
                # Calculate implied volatility
                iv_result = implied_volatility(
                    market_price=request.market_price,
                    S=request.spot_price,
                    K=request.strike_price, 
                    T=request.time_to_expiry,
                    r=request.risk_free_rate,
                    option_type=request.option_type.value,
                    tolerance=1e-6,
                    max_iterations=100
                )
                
                return models.ImpliedVolatilityResponse(
                    implied_volatility=iv_result["volatility"],
                    iterations=iv_result["iterations"],
                    converged=iv_result["converged"]
                )
                
        except ValueError as e:
            logger.error(f"Implied volatility error: {e}")
            raise HTTPException(
                status_code=400,
                detail=f"Calculation failed: {str(e)}"
            )
        except Exception as e:
            logger.error(f"Unexpected error in implied volatility: {e}")
            raise HTTPException(
                status_code=500,
                detail="Internal calculation error"
            )


@options_router.post(
    "/black-scholes",
    response_model=models.BlackScholesResponse,
    summary="Black-Scholes option pricing",
)
async def price_option_black_scholes(
    request: models.BlackScholesRequest,
    _: Annotated[None, Depends(deps.check_rate_limit)],
) -> models.BlackScholesResponse:
    """
    Price European option using Black-Scholes model.
    
    Calculates option price and Greeks (delta, gamma, vega, theta, rho).
    
    Args:
        request: Black-Scholes parameters
    
    Returns:
        Option price and Greeks
    """
    with track_api_request("/options/black-scholes", "POST"):
        try:
            with track_calculation("black_scholes"):
                # Calculate option price and Greeks
                result = price_with_greeks(
                    spot=request.spot_price,
                    strike=request.strike_price,
                    T=request.time_to_maturity,
                    r=request.risk_free_rate,
                    sigma=request.volatility,
                    option_type=request.option_type.value,
                    q=request.dividend_yield,
                )
                
                return models.BlackScholesResponse(
                    option_price=result.price,
                    delta=result.delta,
                    gamma=result.gamma,
                    vega=result.vega,
                    theta=result.theta,
                    rho=result.rho,
                )
        
        except Exception as e:
            logger.error(f"Black-Scholes calculation failed: {e}")
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                detail=str(e),
            )


@options_router.post(
    "/monte-carlo",
    response_model=models.MonteCarloOptionResponse,
    summary="Monte Carlo option pricing",
)
async def price_option_monte_carlo(
    request: models.MonteCarloOptionRequest,
    _: Annotated[None, Depends(deps.check_rate_limit)],
) -> models.MonteCarloOptionResponse:
    """
    Price option using Monte Carlo simulation.
    
    Simulates asset price paths and calculates expected option payoff.
    
    Args:
        request: Monte Carlo parameters
    
    Returns:
        Option price with confidence interval
    """
    with track_api_request("/options/monte-carlo", "POST"):
        try:
            with track_calculation("monte_carlo_option"):
                # Use price_european which uses Monte Carlo
                result = price_european(
                    S0=request.spot_price,
                    K=request.strike_price,
                    T=request.time_to_maturity,
                    r=request.risk_free_rate,
                    sigma=request.volatility,
                    option_type=request.option_type.value,
                    n_paths=request.num_simulations,
                    n_steps=request.num_steps,
                    seed=request.seed or 42,
                )
                
                # Calculate confidence interval (simplified)
                standard_error = result["std_error"] if isinstance(result, dict) else result * 0.02
                option_price = result["price"] if isinstance(result, dict) else result
                
                ci_lower = option_price - 1.96 * standard_error
                ci_upper = option_price + 1.96 * standard_error
                
                return models.MonteCarloOptionResponse(
                    option_price=option_price,
                    confidence_interval_95=(ci_lower, ci_upper),
                    standard_error=standard_error,
                    num_simulations=request.num_simulations,
                )
        
        except Exception as e:
            logger.error(f"Monte Carlo calculation failed: {e}")
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                detail=str(e),
            )


# =============================================================================
# Risk Analytics Router
# =============================================================================

risk_router = APIRouter(
    prefix="/risk", 
    tags=["Risk Management"],
    responses={
        429: {"description": "Rate limit exceeded"},
        500: {"description": "Internal server error"}
    }
)


@risk_router.post(
    "/var",
    response_model=models.VaRResponse,
    summary="Calculate Value at Risk",
)
async def calculate_var_endpoint(
    request: models.VaRRequest,
    _: Annotated[None, Depends(deps.check_rate_limit)],
) -> models.VaRResponse:
    """
    Calculate Value at Risk (VaR) and Conditional VaR (CVaR).
    
    Supports multiple VaR calculation methods:
    - Historical simulation
    - Parametric (Variance-Covariance)
    - Monte Carlo simulation
    
    Args:
        request: VaR calculation parameters
    
    Returns:
        VaR and CVaR estimates with confidence intervals
    """
    with track_api_request("/risk/var", "POST"):
        try:
            with track_calculation("var_calculation"):
                # Validate confidence level
                if not 0.8 <= request.confidence_level <= 0.999:
                    raise HTTPException(
                        status_code=400,
                        detail="Confidence level must be between 0.8 and 0.999"
                    )
                
                # For demonstration - in production, fetch real market data
                # Generate synthetic returns for the tickers
                num_days = 252  # 1 year of trading days
                returns_data = {}
                for ticker in request.tickers:
                    # Simulate realistic returns
                    daily_returns = np.random.normal(0.0005, 0.02, num_days)
                    returns_data[ticker] = daily_returns
                
                returns_df = pd.DataFrame(returns_data)
                
                # Calculate portfolio returns
                weights = np.array([request.weights.get(ticker, 0) for ticker in request.tickers])
                portfolio_returns = returns_df.values @ weights
                
                # Calculate VaR using specified method
                if request.method == "historical":
                    var_value = np.percentile(portfolio_returns, (1 - request.confidence_level) * 100)
                elif request.method == "parametric":
                    mean_return = np.mean(portfolio_returns)
                    std_return = np.std(portfolio_returns)
                    from scipy.stats import norm
                    var_value = norm.ppf(1 - request.confidence_level, mean_return, std_return)
                elif request.method == "monte_carlo":
                    # Monte Carlo simulation
                    n_simulations = 10000
                    mean_return = np.mean(portfolio_returns)
                    std_return = np.std(portfolio_returns)
                    simulated_returns = np.random.normal(mean_return, std_return, n_simulations)
                    var_value = np.percentile(simulated_returns, (1 - request.confidence_level) * 100)
                else:
                    raise HTTPException(
                        status_code=400,
                        detail="Invalid VaR method. Choose: historical, parametric, or monte_carlo"
                    )
                
                # Calculate CVaR (Expected Shortfall)
                cvar_returns = portfolio_returns[portfolio_returns <= var_value]
                cvar_value = np.mean(cvar_returns) if len(cvar_returns) > 0 else var_value
                
                # Convert to portfolio value terms
                var_amount = abs(var_value * request.portfolio_value)
                cvar_amount = abs(cvar_value * request.portfolio_value)
                
                return models.VaRResponse(
                    var_amount=var_amount,
                    var_percentage=abs(var_value) * 100,
                    cvar_amount=cvar_amount,
                    cvar_percentage=abs(cvar_value) * 100,
                    confidence_level=request.confidence_level,
                    method=request.method,
                    holding_period_days=request.holding_period_days
                )
                
        except ValueError as e:
            logger.error(f"VaR calculation error: {e}")
            raise HTTPException(
                status_code=400,
                detail=f"VaR calculation failed: {str(e)}"
            )
        except Exception as e:
            logger.error(f"Unexpected error in VaR calculation: {e}")
            raise HTTPException(
                status_code=500,
                detail="Internal calculation error"
            )


@risk_router.post(
    "/stress-test",
    response_model=models.StressTestResponse,
    summary="Perform portfolio stress test",
)
async def stress_test_endpoint(
    request: models.StressTestRequest,
    _: Annotated[None, Depends(deps.check_rate_limit)],
) -> models.StressTestResponse:
    """
    Perform comprehensive portfolio stress testing.
    
    Tests portfolio performance under various market stress scenarios:
    - Historical scenarios (2008 crisis, COVID-19, etc.)
    - Hypothetical shocks (interest rate changes, volatility spikes)
    - Custom scenario modeling
    
    Args:
        request: Stress test parameters
    
    Returns:
        Stress test results with portfolio impact analysis
    """
    with track_api_request("/risk/stress-test", "POST"):
        try:
            with track_calculation("stress_test"):
                stress_results = []
                
                # Define stress scenarios
                scenarios = {
                    "market_crash_2008": {
                        "equity_shock": -0.30,
                        "bond_shock": 0.05,
                        "volatility_mult": 2.5,
                        "description": "2008 Financial Crisis scenario"
                    },
                    "covid_2020": {
                        "equity_shock": -0.25,
                        "bond_shock": -0.02,
                        "volatility_mult": 3.0,
                        "description": "COVID-19 market shock scenario"
                    },
                    "interest_rate_spike": {
                        "equity_shock": -0.15,
                        "bond_shock": -0.10,
                        "volatility_mult": 1.5,
                        "description": "Sudden interest rate increase"
                    },
                    "inflation_surge": {
                        "equity_shock": -0.20,
                        "bond_shock": -0.15,
                        "volatility_mult": 2.0,
                        "description": "Unexpected inflation surge"
                    }
                }
                
                # Run stress tests for requested scenarios
                for scenario_name in request.scenarios:
                    if scenario_name not in scenarios:
                        continue
                        
                    scenario = scenarios[scenario_name]
                    
                    # Calculate portfolio impact
                    total_impact = 0.0
                    for ticker, weight in request.weights.items():
                        # Simplified: assume all assets are equity for demo
                        # In production: classify assets and apply appropriate shocks
                        asset_impact = scenario["equity_shock"] * weight * request.portfolio_value
                        total_impact += asset_impact
                    
                    stress_results.append({
                        "scenario_name": scenario_name,
                        "description": scenario["description"],
                        "portfolio_impact": total_impact,
                        "impact_percentage": (total_impact / request.portfolio_value) * 100,
                        "final_portfolio_value": request.portfolio_value + total_impact
                    })
                
                # Calculate summary statistics
                if stress_results:
                    worst_case = min(stress_results, key=lambda x: x["portfolio_impact"])
                    best_case = max(stress_results, key=lambda x: x["portfolio_impact"])
                    avg_impact = sum(r["portfolio_impact"] for r in stress_results) / len(stress_results)
                else:
                    worst_case = best_case = {"portfolio_impact": 0, "impact_percentage": 0}
                    avg_impact = 0
                
                return models.StressTestResponse(
                    scenario_results=stress_results,
                    worst_case_loss=abs(worst_case["portfolio_impact"]),
                    worst_case_percentage=abs(worst_case["impact_percentage"]),
                    best_case_impact=best_case["portfolio_impact"],
                    average_impact=avg_impact,
                    scenarios_tested=len(stress_results)
                )
                
        except Exception as e:
            logger.error(f"Stress test error: {e}")
            raise HTTPException(
                status_code=500,
                detail=f"Stress test failed: {str(e)}"
            )


@risk_router.post(
    "/var",
    response_model=models.VaRResponse,
    summary="Calculate Value-at-Risk",
)
async def calculate_value_at_risk(
    request: models.VaRRequest,
    _: Annotated[None, Depends(deps.check_rate_limit)],
) -> models.VaRResponse:
    """
    Calculate Value-at-Risk (VaR) and Conditional VaR.
    
    Estimates maximum potential loss at given confidence level.
    
    Args:
        request: VaR parameters
    
    Returns:
        VaR and CVaR estimates
    """
    with track_api_request("/risk/var", "POST"):
        try:
            with track_calculation("var_calculation"):
                returns_array = np.array(request.returns)
                
                # Calculate VaR using specified method
                var_result = calculate_var(
                    returns=returns_array,
                    confidence_level=request.confidence_level,
                    method=request.method,
                    portfolio_value=request.portfolio_value,
                )
                
                return models.VaRResponse(
                    var=var_result.var,
                    cvar=var_result.cvar,
                    confidence_level=request.confidence_level,
                    method=request.method,
                )
        
        except Exception as e:
            logger.error(f"VaR calculation failed: {e}")
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                detail=str(e),
            )


@risk_router.post(
    "/stress-test",
    response_model=models.StressTestResponse,
    summary="Run portfolio stress test",
)
async def run_stress_test(
    request: models.StressTestRequest,
    _: Annotated[None, Depends(deps.check_rate_limit)],
) -> models.StressTestResponse:
    """
    Run stress test on portfolio.
    
    Simulates portfolio performance under extreme market conditions.
    
    Args:
        request: Stress test parameters
    
    Returns:
        Portfolio loss under stress scenario
    """
    with track_api_request("/risk/stress-test", "POST"):
        try:
            with track_calculation("stress_test"):
                # Placeholder stress test calculation
                baseline_value = 1000000.0  # $1M baseline
                
                # Apply shock based on type
                shock_multipliers = {
                    "market_crash": -0.20,  # -20%
                    "volatility_spike": -0.10,  # -10%
                    "correlation_shock": -0.08,  # -8%
                    "liquidity_crisis": -0.15,  # -15%
                }
                
                base_loss = shock_multipliers.get(request.shock_type, -0.10)
                loss_percentage = base_loss * (1 + request.shock_magnitude)
                
                stressed_value = baseline_value * (1 + loss_percentage)
                loss_amount = baseline_value - stressed_value
                
                return models.StressTestResponse(
                    baseline_value=baseline_value,
                    stressed_value=stressed_value,
                    loss_amount=loss_amount,
                    loss_percentage=abs(loss_percentage) * 100,
                    shock_type=request.shock_type,
                )
        
        except Exception as e:
            logger.error(f"Stress test failed: {e}")
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                detail=str(e),
            )


# =============================================================================
# Market Regime Router
# =============================================================================

regime_router = APIRouter(
    prefix="/regime", 
    tags=["Market Intelligence"],
    responses={
        429: {"description": "Rate limit exceeded"},
        500: {"description": "Internal server error"}
    }
)


@regime_router.post(
    "/detect",
    response_model=models.MarketRegimeResponse,
    summary="Detect market regime",
)
async def detect_market_regime(
    request: models.MarketRegimeRequest,
    _: Annotated[None, Depends(deps.check_rate_limit)],
) -> models.MarketRegimeResponse:
    """
    Detect current market regime using Hidden Markov Models.
    
    Identifies distinct market states based on return patterns.
    
    Args:
        request: Regime detection parameters
    
    Returns:
        Current regime and transition probabilities
    """
    with track_api_request("/regime/detect", "POST"):
        try:
            with track_calculation("regime_detection"):
                # Create a simple price series from returns
                returns = np.array(request.returns)
                prices = pd.Series(100 * np.exp(np.cumsum(returns)))
                
                # Use HMM regime detector
                result = detect_regimes_hmm(
                    prices=prices,
                    n_regimes=request.num_regimes,
                )
                
                current_regime = result.regimes[-1]
                
                # Extract regime characteristics
                characteristics = {}
                for i in range(request.num_regimes):
                    regime_mask = result.regimes == i
                    regime_returns = returns[regime_mask]
                    
                    if len(regime_returns) > 0:
                        characteristics[f"regime_{i}"] = {
                            "mean_return": float(np.mean(regime_returns)),
                            "volatility": float(np.std(regime_returns)),
                            "count": int(np.sum(regime_mask)),
                        }
                
                # Empty probabilities - return uniform distribution
                regime_probs = [1.0 / request.num_regimes] * request.num_regimes
                
                return models.MarketRegimeResponse(
                    current_regime=int(current_regime),
                    regime_probabilities=regime_probs,
                    regime_characteristics=characteristics,
                    transitions=result.transition_matrix.tolist(),
                )
        
        except Exception as e:
            logger.error(f"Regime detection failed: {e}")
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                detail=str(e),
            )


# =============================================================================
# Volatility Router  
# =============================================================================

volatility_router = APIRouter(
    prefix="/volatility", 
    tags=["Volatility Analytics"],
    responses={
        429: {"description": "Rate limit exceeded"},
        500: {"description": "Internal server error"}
    }
)


@volatility_router.post(
    "/implied",
    response_model=models.ImpliedVolatilityResponse,
    summary="Calculate implied volatility",
)
async def calculate_implied_volatility(
    request: models.ImpliedVolatilityRequest,
    _: Annotated[None, Depends(deps.check_rate_limit)],
) -> models.ImpliedVolatilityResponse:
    """
    Calculate implied volatility from option price.
    
    Uses Newton-Raphson method to invert Black-Scholes formula.
    
    Args:
        request: Implied volatility parameters
    
    Returns:
        Implied volatility and convergence metrics
    """
    with track_api_request("/volatility/implied", "POST"):
        try:
            with track_calculation("implied_volatility"):
                # Use implied_volatility function
                iv = implied_volatility(
                    option_price=request.option_price,
                    spot=request.spot_price,
                    strike=request.strike_price,
                    T=request.time_to_maturity,
                    r=request.risk_free_rate,
                    option_type=request.option_type.value,
                    q=0.0,  # Dividend yield
                    initial_guess=request.initial_guess,
                    tol=1e-6,
                    max_iterations=100,
                )
                
                return models.ImpliedVolatilityResponse(
                    implied_volatility=iv,
                    iterations=10,  # Placeholder
                    convergence_error=1e-7,  # Placeholder
                )
        
        except Exception as e:
            logger.error(f"Implied volatility calculation failed: {e}")
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                detail=str(e),
            )


@volatility_router.post(
    "/surface",
    response_model=models.VolatilitySurfaceResponse,
    summary="Build volatility surface",
)
async def build_volatility_surface(
    request: models.VolatilitySurfaceRequest,
    _: Annotated[None, Depends(deps.check_rate_limit)],
) -> models.VolatilitySurfaceResponse:
    """
    Build volatility surface from option data.
    
    Constructs two-dimensional surface of implied volatilities across strikes and maturities.
    
    Args:
        request: Volatility surface parameters
    
    Returns:
        Volatility surface data and skew metrics
    """
    with track_api_request("/volatility/surface", "POST"):
        try:
            with track_calculation("volatility_surface"):
                # Placeholder: generate sample volatility surface
                surface = []
                for maturity in request.maturities:
                    row = []
                    for strike in request.strikes:
                        # Simple volatility smile model
                        moneyness = strike / request.spot_price
                        base_vol = 0.2  # 20% base vol
                        smile = 0.1 * (moneyness - 1.0) ** 2  # Parabolic smile
                        vol = base_vol + smile
                        row.append(vol)
                    surface.append(row)
                
                atm_vols = [row[len(row) // 2] for row in surface]
                
                skew = {
                    "25_delta_skew": 0.05,
                    "10_delta_skew": 0.08,
                    "slope": -0.02,
                }
                
                return models.VolatilitySurfaceResponse(
                    surface=surface,
                    maturities=request.maturities,
                    strikes=request.strikes,
                    atm_volatilities=atm_vols,
                    skew=skew,
                )
        
        except Exception as e:
            logger.error(f"Volatility surface construction failed: {e}")
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                detail=str(e),
            )


# =============================================================================
# Macro Analysis Router
# =============================================================================

macro_router = APIRouter(prefix="/macro", tags=["macro"])


@macro_router.post(
    "/regime",
    response_model=models.MacroRegimeResponse,
    summary="Detect macro regime",
)
async def detect_macroeconomic_regime(
    request: models.MacroRegimeRequest,
    _: Annotated[None, Depends(deps.check_rate_limit)],
) -> models.MacroRegimeResponse:
    """
    Detect macroeconomic regime.
    
    Classifies macro environment as expansion, slowdown, recession, or recovery.
    
    Args:
        request: Macro indicators
    
    Returns:
        Macro regime classification and recession probability
    """
    with track_api_request("/macro/regime", "POST"):
        try:
            with track_calculation("macro_regime"):
                # Use macro regime detection from macro module
                regime = detect_macro_regime(
                    gdp_growth=request.gdp_growth[-1] if request.gdp_growth else 2.0,
                    unemployment=request.unemployment_rate[-1] if request.unemployment_rate else 4.0,
                    pmi=request.pmi[-1] if request.pmi else 52.0,
                )
                
                # Calculate recession probability (simplified)
                recession_prob = min(0.5, max(0.0, (5.0 - (request.gdp_growth[-1] if request.gdp_growth else 2.0)) / 10.0))
                
                indicators = {
                    "gdp_growth": request.gdp_growth[-1] if request.gdp_growth else 2.0,
                    "unemployment": request.unemployment_rate[-1] if request.unemployment_rate else 4.0,
                    "pmi": request.pmi[-1] if request.pmi else 52.0,
                }
                
                return models.MacroRegimeResponse(
                    current_regime=regime.name,
                    regime_score=0.75,
                    indicators=indicators,
                    recession_probability=recession_prob,
                )
        
        except Exception as e:
            logger.error(f"Macro regime detection failed: {e}")
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                detail=str(e),
            )


@macro_router.post(
    "/correlation",
    response_model=models.CorrelationAnalysisResponse,
    summary="Analyze correlations",
)
async def analyze_correlations(
    request: models.CorrelationAnalysisRequest,
    _: Annotated[None, Depends(deps.check_rate_limit)],
) -> models.CorrelationAnalysisResponse:
    """
    Analyze cross-asset correlations.
    
    Computes correlation matrix and detects correlation regimes.
    
    Args:
        request: Returns data for multiple assets
    
    Returns:
        Correlation matrix, regime, and diversification metrics
    """
    with track_api_request("/macro/correlation", "POST"):
        try:
            with track_calculation("correlation_analysis"):
                # Convert to numpy array
                assets = list(request.returns_data.keys())
                returns_matrix = np.array([
                    request.returns_data[asset]
                    for asset in assets
                ]).T
                
                # Calculate correlation matrix
                corr_matrix = np.corrcoef(returns_matrix.T)
                
                # Calculate average correlation
                n = len(assets)
                avg_corr = (corr_matrix.sum() - n) / (n * (n - 1))
                
                # Determine regime based on average correlation
                regime = correlation_regime(avg_corr)
                
                # Calculate eigenvalues for concentration
                eigenvalues = np.linalg.eigvalsh(corr_matrix)
                eigenvalues = sorted(eigenvalues, reverse=True)
                eigenvalue_concentration = eigenvalues[0] / sum(eigenvalues)
                
                # Diversification ratio (simplified)
                diversification_ratio = 1.0 / (1.0 + avg_corr)
                
                return models.CorrelationAnalysisResponse(
                    correlation_matrix=corr_matrix.tolist(),
                    regime=regime.name,
                    avg_correlation=float(avg_corr),
                    eigenvalue_concentration=float(eigenvalue_concentration),
                    diversification_ratio=float(diversification_ratio),
                )
        
        except Exception as e:
            logger.error(f"Correlation analysis failed: {e}")
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                detail=str(e),
            )


@macro_router.post(
    "/sentiment",
    response_model=models.SentimentAnalysisResponse,
    summary="Analyze market sentiment",
)
async def analyze_market_sentiment(
    request: models.SentimentAnalysisRequest,
    _: Annotated[None, Depends(deps.check_rate_limit)],
) -> models.SentimentAnalysisResponse:
    """
    Analyze market sentiment from multiple indicators.
    
    Combines VIX, put/call ratio, breadth indicators into sentiment index.
    
    Args:
        request: Sentiment indicators
    
    Returns:
        Sentiment regime and fear/greed index
    """
    with track_api_request("/macro/sentiment", "POST"):
        try:
            with track_calculation("sentiment_analysis"):
                # Calculate fear/greed index components
                components = {}
                
                if request.vix_level is not None:
                    vix_score = max(0, min(100, (50 - request.vix_level) * 2))
                    components["vix"] = vix_score
                    sentiment_regime_vix = vix_sentiment_level(request.vix_level)
                else:
                    vix_score = 50
                    sentiment_regime_vix = "NEUTRAL"
                
                # Calculate composite fear/greed index
                fg_index = fear_greed_index(
                    vix=request.vix_level or 15.0,
                    put_call_ratio=request.put_call_ratio or 1.0,
                    advancing=request.advance_decline or 0,
                    declining=abs(request.advance_decline or 0) if (request.advance_decline or 0) < 0 else 0,
                    new_highs=request.new_highs or 50,
                    new_lows=request.new_lows or 50,
                )
                
                # Determine contrarian signal
                if fg_index > 75:
                    contrarian = "sell"
                elif fg_index < 25:
                    contrarian = "buy"
                else:
                    contrarian = "neutral"
                
                return models.SentimentAnalysisResponse(
                    sentiment_regime=sentiment_regime_vix,
                    fear_greed_index=fg_index,
                    contrarian_signal=contrarian,
                    components=components,
                )
        
        except Exception as e:
            logger.error(f"Sentiment analysis failed: {e}")
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                detail=str(e),
            )


# =============================================================================
# All Routers Collection
# =============================================================================

all_routers = [
    portfolio_router,
    options_router,
    risk_router,
    regime_router,
    volatility_router,
    macro_router,
]