File size: 12,580 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
344
345
346
347
348
349
350
"""
QuantLib Pro SDK β€” Main Client
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The primary interface for interacting with the QuantLib Pro API.

Usage::

    from quantlib_api import QuantLibClient

    client = QuantLibClient(auto_login=True)
    result = client.portfolio.optimize(tickers=["AAPL", "GOOGL"], budget=100000)
    print(result)
"""

import os
from typing import Optional

from quantlib_api._http import HTTPSession, AsyncHTTPSession
from quantlib_api.auth import AuthManager
from quantlib_api.exceptions import QuantLibAuthError


class QuantLibClient:
    """
    Synchronous client for the QuantLib Pro API.

    All domain resources are lazily initialized and accessible as properties.

    Parameters
    ----------
    base_url : str
        API base URL (default: from QUANTLIB_URL env var or localhost:8000)
    username : str, optional
        Username for JWT auth (or QUANTLIB_USERNAME env var)
    password : str, optional
        Password for JWT auth (or QUANTLIB_PASSWORD env var)
    api_key : str, optional
        API key for auth (alternative to username/password)
    auto_login : bool
        If True, automatically authenticate on client creation
    timeout : float
        Request timeout in seconds (default: 30)
    verbose : bool
        Enable debug logging of HTTP requests/responses
    """

    def __init__(
        self,
        base_url: Optional[str] = None,
        username: Optional[str] = None,
        password: Optional[str] = None,
        api_key: Optional[str] = None,
        auto_login: bool = False,
        timeout: float = 30.0,
        verbose: bool = False,
    ):
        self.base_url = base_url or os.getenv("QUANTLIB_URL", "http://localhost:8000")
        self._username = username or os.getenv("QUANTLIB_USERNAME")
        self._password = password or os.getenv("QUANTLIB_PASSWORD")
        self._api_key = api_key or os.getenv("QUANTLIB_API_KEY")

        # HTTP session
        self._http = HTTPSession(
            base_url=self.base_url,
            timeout=timeout,
            verbose=verbose,
        )

        # Auth manager
        self._auth = AuthManager(self._http)

        # Lazy-initialized resources
        self._portfolio = None
        self._risk = None
        self._options = None
        self._regime = None
        self._volatility = None
        self._macro = None
        self._backtesting = None
        self._analytics = None
        self._data = None
        self._market_analysis = None
        self._signals = None
        self._liquidity = None
        self._systemic_risk = None
        self._execution = None
        self._compliance = None
        self._uat = None
        self._health = None

        if auto_login:
            self.login()

    # ─────────────────────────────────────────────────────────────────────────
    # Authentication
    # ─────────────────────────────────────────────────────────────────────────

    def login(self, username: Optional[str] = None, password: Optional[str] = None) -> str:
        """
        Authenticate with username/password and obtain JWT token.

        Returns the JWT token string.
        """
        user = username or self._username
        pwd = password or self._password

        if not user or not pwd:
            raise QuantLibAuthError(
                "Username and password required. Set via constructor or "
                "QUANTLIB_USERNAME / QUANTLIB_PASSWORD environment variables."
            )

        token = self._auth.login(user, pwd)
        self._http.set_token(token)
        return token

    def set_api_key(self, api_key: str):
        """Use API key authentication instead of JWT."""
        self._http.set_api_key(api_key)

    @property
    def is_authenticated(self) -> bool:
        """Check if client has an active auth token."""
        return self._http._token is not None or self._http._api_key is not None

    # ─────────────────────────────────────────────────────────────────────────
    # Resource Properties (lazy initialization)
    # ─────────────────────────────────────────────────────────────────────────

    @property
    def portfolio(self):
        """Portfolio optimization and management."""
        if self._portfolio is None:
            from quantlib_api.resources.portfolio import PortfolioResource
            self._portfolio = PortfolioResource(self._http)
        return self._portfolio

    @property
    def risk(self):
        """Risk analysis: VaR, CVaR, stress testing."""
        if self._risk is None:
            from quantlib_api.resources.risk import RiskResource
            self._risk = RiskResource(self._http)
        return self._risk

    @property
    def options(self):
        """Options pricing and Greeks calculation."""
        if self._options is None:
            from quantlib_api.resources.options import OptionsResource
            self._options = OptionsResource(self._http)
        return self._options

    @property
    def regime(self):
        """Market regime detection and analysis."""
        if self._regime is None:
            from quantlib_api.resources.regime import RegimeResource
            self._regime = RegimeResource(self._http)
        return self._regime

    @property
    def volatility(self):
        """Volatility surface construction and analysis."""
        if self._volatility is None:
            from quantlib_api.resources.volatility import VolatilityResource
            self._volatility = VolatilityResource(self._http)
        return self._volatility

    @property
    def macro(self):
        """Macro analysis and economic indicators."""
        if self._macro is None:
            from quantlib_api.resources.macro import MacroResource
            self._macro = MacroResource(self._http)
        return self._macro

    @property
    def backtesting(self):
        """Strategy backtesting and performance analysis."""
        if self._backtesting is None:
            from quantlib_api.resources.backtesting import BacktestingResource
            self._backtesting = BacktestingResource(self._http)
        return self._backtesting

    @property
    def analytics(self):
        """Advanced analytics: correlation, PCA, factor analysis."""
        if self._analytics is None:
            from quantlib_api.resources.analytics import AnalyticsResource
            self._analytics = AnalyticsResource(self._http)
        return self._analytics

    @property
    def data(self):
        """Market data access and management."""
        if self._data is None:
            from quantlib_api.resources.data import DataResource
            self._data = DataResource(self._http)
        return self._data

    @property
    def market_analysis(self):
        """Technical indicators and market analysis."""
        if self._market_analysis is None:
            from quantlib_api.resources.market_analysis import MarketAnalysisResource
            self._market_analysis = MarketAnalysisResource(self._http)
        return self._market_analysis

    @property
    def signals(self):
        """Trading signal generation and backtesting."""
        if self._signals is None:
            from quantlib_api.resources.signals import SignalsResource
            self._signals = SignalsResource(self._http)
        return self._signals

    @property
    def liquidity(self):
        """Liquidity analysis and market microstructure."""
        if self._liquidity is None:
            from quantlib_api.resources.liquidity import LiquidityResource
            self._liquidity = LiquidityResource(self._http)
        return self._liquidity

    @property
    def systemic_risk(self):
        """Systemic risk and contagion analysis."""
        if self._systemic_risk is None:
            from quantlib_api.resources.systemic_risk import SystemicRiskResource
            self._systemic_risk = SystemicRiskResource(self._http)
        return self._systemic_risk

    @property
    def execution(self):
        """Execution optimization: VWAP, TWAP, market impact."""
        if self._execution is None:
            from quantlib_api.resources.execution import ExecutionResource
            self._execution = ExecutionResource(self._http)
        return self._execution

    @property
    def compliance(self):
        """Compliance checks and regulatory reporting."""
        if self._compliance is None:
            from quantlib_api.resources.compliance import ComplianceResource
            self._compliance = ComplianceResource(self._http)
        return self._compliance

    @property
    def uat(self):
        """UAT scenarios and stress monitoring."""
        if self._uat is None:
            from quantlib_api.resources.uat import UATResource
            self._uat = UATResource(self._http)
        return self._uat

    @property
    def health(self):
        """API health checks."""
        if self._health is None:
            from quantlib_api.resources.health import HealthResource
            self._health = HealthResource(self._http)
        return self._health

    # ─────────────────────────────────────────────────────────────────────────
    # Context Manager
    # ─────────────────────────────────────────────────────────────────────────

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.close()

    def close(self):
        """Close HTTP session and release resources."""
        self._http.close()


class AsyncQuantLibClient:
    """
    Async client for the QuantLib Pro API.

    Usage::

        async with AsyncQuantLibClient(auto_login=True) as client:
            result = await client.portfolio.aoptimize(tickers=["AAPL"], budget=100000)
    """

    def __init__(
        self,
        base_url: Optional[str] = None,
        username: Optional[str] = None,
        password: Optional[str] = None,
        api_key: Optional[str] = None,
        auto_login: bool = False,
        timeout: float = 30.0,
        verbose: bool = False,
    ):
        self.base_url = base_url or os.getenv("QUANTLIB_URL", "http://localhost:8000")
        self._username = username or os.getenv("QUANTLIB_USERNAME")
        self._password = password or os.getenv("QUANTLIB_PASSWORD")
        self._api_key = api_key or os.getenv("QUANTLIB_API_KEY")
        self._auto_login = auto_login

        self._http = AsyncHTTPSession(
            base_url=self.base_url,
            timeout=timeout,
            verbose=verbose,
        )

        # Lazy resources (async versions)
        self._portfolio = None
        self._risk = None
        # ... (other resources would be added)

    async def __aenter__(self):
        if self._auto_login:
            await self.login()
        return self

    async def __aexit__(self, exc_type, exc_val, exc_tb):
        await self._http.close()

    async def login(self, username: Optional[str] = None, password: Optional[str] = None) -> str:
        user = username or self._username
        pwd = password or self._password

        if not user or not pwd:
            raise QuantLibAuthError("Username and password required for async login.")

        response = await self._http.post(
            "/auth/login",
            json={"username": user, "password": pwd}
        )
        token = response.get("access_token")
        if not token:
            raise QuantLibAuthError("No access_token in login response")
        self._http.set_token(token)
        return token

    @property
    def portfolio(self):
        if self._portfolio is None:
            from quantlib_api.resources.portfolio import AsyncPortfolioResource
            self._portfolio = AsyncPortfolioResource(self._http)
        return self._portfolio