prometheus-qengine 1.0.1__tar.gz → 1.0.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: prometheus-qengine
3
- Version: 1.0.1
3
+ Version: 1.0.2
4
4
  Summary: Official Python SDK for the Prometheus Quant Engine (HPC Monte Carlo)
5
5
  Author-email: Prometheus Quant Engineering <dev@prometheusquantengine.com>
6
6
  Project-URL: Homepage, https://prometheusquantengine.com
@@ -0,0 +1,116 @@
1
+ import requests
2
+ import uuid
3
+ import time
4
+ import logging
5
+ from typing import Optional, Union
6
+
7
+ from .models import EuropeanOption, AsianOption, BarrierOption, SimulationResult
8
+ from .exceptions import (
9
+ AuthenticationError,
10
+ InsufficientCreditsError,
11
+ EngineComputationError,
12
+ PrometheusError,
13
+ )
14
+
15
+ logger = logging.getLogger(__name__)
16
+ logger.addHandler(logging.NullHandler())
17
+
18
+
19
+ class PrometheusClient:
20
+ def __init__(
21
+ self,
22
+ api_key: str,
23
+ base_url: str = "https://api.prometheusquantengine.com/api/v1",
24
+ timeout: int = 60,
25
+ ):
26
+ if not api_key:
27
+ raise AuthenticationError("API Key is required to instantiate the Prometheus Client.")
28
+
29
+ self.api_key = api_key
30
+ self.base_url = base_url.rstrip("/")
31
+ self.timeout = timeout
32
+ self._session = requests.Session()
33
+ self._session.headers.update({"X-API-Key": self.api_key})
34
+
35
+ def price(
36
+ self,
37
+ option: Union[EuropeanOption, AsianOption, BarrierOption],
38
+ idempotency_key: Optional[str] = None,
39
+ poll_interval: int = 2,
40
+ ) -> SimulationResult:
41
+ """
42
+ Submits the mathematical payload to the C++ Engine.
43
+ Automatically handles synchronous routing and asynchronous HPC polling.
44
+ """
45
+ idem_key = idempotency_key or str(uuid.uuid4())
46
+
47
+ headers = {
48
+ "Idempotency-Key": idem_key,
49
+ "Content-Type": "application/json",
50
+ }
51
+
52
+ url = f"{self.base_url}/simulations"
53
+ payload = option.model_dump(mode="json", exclude_none=True)
54
+
55
+ response = self._session.post(url, json=payload, headers=headers, timeout=self.timeout)
56
+ self._handle_http_errors(response)
57
+ data = response.json()
58
+
59
+ # 1. Asynchronous HPC Offload Detected
60
+ if "task_id" in data:
61
+ task_id = data["task_id"]
62
+ logger.info("Massive workload detected. Delegated to Celery HPC. Task ID: %s", task_id)
63
+ return self._poll_hpc_cluster(task_id, poll_interval)
64
+
65
+ # 2. Synchronous Execution
66
+ return SimulationResult(**data)
67
+
68
+ def _poll_hpc_cluster(self, task_id: str, poll_interval: int) -> SimulationResult:
69
+ """Polls the task status endpoint and fetches the full SimulationResponse upon completion."""
70
+ task_url = f"{self.base_url}/simulations/task/{task_id}"
71
+
72
+ while True:
73
+ response = self._session.get(task_url, timeout=self.timeout)
74
+ self._handle_http_errors(response)
75
+ data = response.json()
76
+ status = data.get("status")
77
+
78
+ if status == "SUCCESS":
79
+ sim_id = data.get("simulation_id")
80
+ if not sim_id:
81
+ raise EngineComputationError("Task succeeded but returned no simulation_id.")
82
+ return self._fetch_simulation_result(sim_id)
83
+
84
+ if status in ("FAILURE", "REVOKED"):
85
+ raise EngineComputationError("C++ Engine collapsed during execution. Credits refunded.")
86
+
87
+ time.sleep(poll_interval)
88
+
89
+ def _fetch_simulation_result(self, simulation_id: str, retries: int = 4) -> SimulationResult:
90
+ """Retrieves the complete persisted simulation matrix by UUID with brief retry tolerance."""
91
+ detail_url = f"{self.base_url}/simulations/{simulation_id}"
92
+
93
+ for attempt in range(retries):
94
+ response = self._session.get(detail_url, timeout=self.timeout)
95
+ if response.status_code == 404 and attempt < retries - 1:
96
+ time.sleep(1.5)
97
+ continue
98
+ self._handle_http_errors(response)
99
+ return SimulationResult(**response.json())
100
+
101
+ raise EngineComputationError(f"Simulation {simulation_id} completed but could not be retrieved.")
102
+
103
+ def _handle_http_errors(self, response: requests.Response) -> None:
104
+ """Translates REST errors into Pythonic Exceptions safely."""
105
+ if response.status_code >= 400:
106
+ try:
107
+ body = response.json()
108
+ error_msg = body.get("detail", response.text) if isinstance(body, dict) else response.text
109
+ except ValueError:
110
+ error_msg = response.text
111
+
112
+ if response.status_code == 401:
113
+ raise AuthenticationError("Invalid API Key.")
114
+ if response.status_code == 402:
115
+ raise InsufficientCreditsError(f"Insufficient Compute Credits: {error_msg}")
116
+ raise PrometheusError(f"HTTP {response.status_code}: {error_msg}")
@@ -3,6 +3,7 @@ from typing import Optional, Literal
3
3
  from .enums import OptionType, BarrierType, SimulationType
4
4
  import pandas as pd
5
5
 
6
+
6
7
  class BaseSimulationPayload(BaseModel):
7
8
  s_0: float = Field(..., gt=0.0, description="Initial Asset Price (Spot)")
8
9
  strike: float = Field(..., gt=0.0, description="Strike Price")
@@ -10,25 +11,39 @@ class BaseSimulationPayload(BaseModel):
10
11
  time_to_maturity: float = Field(..., gt=0.0, description="Time to maturity in years")
11
12
  risk_free_rate: float = Field(..., description="Annualized Risk-Free Rate")
12
13
  option_type: OptionType
13
- n_simulations: int = Field(..., ge=10000, le=1000000000)
14
- label: Optional[str] = None
15
-
16
- simulation_type: SimulationType
14
+ n_simulations: int = Field(..., ge=10_000, le=1_000_000_000)
15
+ label: Optional[str] = Field(default=None, max_length=50)
16
+
17
+ simulation_type: SimulationType
18
+
19
+ @model_validator(mode="after")
20
+ def validate_matrix_cap(self):
21
+ m = getattr(self, "m_steps", 1)
22
+ total_steps = self.n_simulations * m
23
+ if total_steps > 2_000_000_000:
24
+ raise ValueError(
25
+ f"Matrix exceeds maximum allowance (2,000,000,000 steps). "
26
+ f"Requested N={self.n_simulations} * M={m} = {total_steps}."
27
+ )
28
+ return self
29
+
17
30
 
18
31
  class EuropeanOption(BaseSimulationPayload):
19
32
  simulation_type: Literal[SimulationType.EUROPEAN] = SimulationType.EUROPEAN
20
33
 
34
+
21
35
  class AsianOption(BaseSimulationPayload):
22
36
  simulation_type: Literal[SimulationType.ASIAN] = SimulationType.ASIAN
23
- m_steps: int = Field(..., gt=0, description="Number of temporal observation steps")
37
+ m_steps: int = Field(..., ge=1, le=10_000, description="Number of temporal observation steps")
38
+
24
39
 
25
40
  class BarrierOption(BaseSimulationPayload):
26
41
  simulation_type: Literal[SimulationType.BARRIER] = SimulationType.BARRIER
27
- m_steps: int = Field(..., gt=0)
42
+ m_steps: int = Field(..., ge=1, le=10_000)
28
43
  barrier_type: BarrierType
29
44
  barrier_level: float = Field(..., gt=0.0)
30
45
 
31
- @model_validator(mode='after')
46
+ @model_validator(mode="after")
32
47
  def validate_barrier_logic(self):
33
48
  """Mathematically validates that the barrier makes logical sense before computing."""
34
49
  if self.barrier_type in [BarrierType.DOWN_AND_OUT, BarrierType.DOWN_AND_IN]:
@@ -39,6 +54,7 @@ class BarrierOption(BaseSimulationPayload):
39
54
  raise ValueError("For Up barriers, barrier_level must be strictly above s_0.")
40
55
  return self
41
56
 
57
+
42
58
  class SimulationResult(BaseModel):
43
59
  id: str
44
60
  user_id: str
@@ -47,8 +63,8 @@ class SimulationResult(BaseModel):
47
63
  created_at: str
48
64
  label: Optional[str] = None
49
65
  fair_value: float
50
- ci_lower: float
51
- ci_upper: float
66
+ ci_lower: Optional[float] = None
67
+ ci_upper: Optional[float] = None
52
68
  delta: Optional[float] = None
53
69
  gamma: Optional[float] = None
54
70
  vega: Optional[float] = None
@@ -58,6 +74,5 @@ class SimulationResult(BaseModel):
58
74
  def to_pandas(self) -> pd.DataFrame:
59
75
  """Transforms the payload into a clean Pandas DataFrame for quant analysis."""
60
76
  df = pd.DataFrame([self.model_dump()])
61
- # Optional: Set 'id' as index for cleaner display
62
- df.set_index('id', inplace=True)
77
+ df.set_index("id", inplace=True)
63
78
  return df
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: prometheus-qengine
3
- Version: 1.0.1
3
+ Version: 1.0.2
4
4
  Summary: Official Python SDK for the Prometheus Quant Engine (HPC Monte Carlo)
5
5
  Author-email: Prometheus Quant Engineering <dev@prometheusquantengine.com>
6
6
  Project-URL: Homepage, https://prometheusquantengine.com
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "prometheus-qengine"
7
- version = "1.0.1"
7
+ version = "1.0.2"
8
8
  authors = [
9
9
  { name="Prometheus Quant Engineering", email="dev@prometheusquantengine.com" },
10
10
  ]
@@ -1,84 +0,0 @@
1
- import requests
2
- import uuid
3
- import time
4
- import logging
5
- from typing import Union
6
-
7
- from .models import EuropeanOption, AsianOption, BarrierOption, SimulationResult
8
- from .exceptions import AuthenticationError, InsufficientCreditsError, EngineComputationError, PrometheusError
9
-
10
- logging.basicConfig(format='%(levelname)s: %(message)s')
11
- logger = logging.getLogger(__name__)
12
-
13
- class PrometheusClient:
14
- def __init__(self, api_key: str, base_url: str = "https://api.prometheusquantengine.com/api/v1"):
15
- if not api_key:
16
- raise AuthenticationError("API Key is required to instantiate the Prometheus Client.")
17
-
18
- self.api_key = api_key
19
- self.base_url = base_url.rstrip("/")
20
- self._session = requests.Session()
21
- self._session.headers.update({"X-API-Key": self.api_key})
22
-
23
- def price(
24
- self,
25
- option: Union[EuropeanOption, AsianOption, BarrierOption],
26
- idempotency_key: str = None,
27
- poll_interval: int = 2
28
- ) -> SimulationResult:
29
- """
30
- Submits the mathematical payload to the C++ Engine.
31
- Automatically handles synchronous routing and asynchronous HPC polling.
32
- """
33
- # Auto-generate idempotency protection if not explicitly provided
34
- idem_key = idempotency_key or str(uuid.uuid4())
35
-
36
- headers = {
37
- "Idempotency-Key": idem_key,
38
- "Content-Type": "application/json"
39
- }
40
-
41
- url = f"{self.base_url}/simulations"
42
- payload = option.model_dump(mode='json', exclude_none=True)
43
-
44
- response = self._session.post(url, json=payload, headers=headers)
45
-
46
- self._handle_http_errors(response)
47
- data = response.json()
48
-
49
- # 1. Asynchronous HPC Offload Detected
50
- if "task_id" in data:
51
- task_id = data["task_id"]
52
- logger.info(f"Massive workload detected. Delegated to Celery HPC. Task ID: {task_id}")
53
- return self._poll_hpc_cluster(task_id, poll_interval)
54
-
55
- # 2. Synchronous Execution
56
- return SimulationResult(**data)
57
-
58
- def _poll_hpc_cluster(self, task_id: str, poll_interval: int) -> SimulationResult:
59
- """Internal method to abstract the long-polling architecture from the developer."""
60
- url = f"{self.base_url}/simulations/task/{task_id}"
61
-
62
- while True:
63
- response = self._session.get(url)
64
- self._handle_http_errors(response)
65
- data = response.json()
66
- status = data.get("status")
67
-
68
- if status == "SUCCESS":
69
- return SimulationResult(**data)
70
- elif status in ["FAILURE", "REVOKED"]:
71
- raise EngineComputationError("C++ Engine collapsed during execution. Credits refunded.")
72
-
73
- time.sleep(poll_interval)
74
-
75
- def _handle_http_errors(self, response: requests.Response):
76
- """Translates REST errors into Pythonic Exceptions."""
77
- if response.status_code >= 400:
78
- if response.status_code == 401:
79
- raise AuthenticationError("Invalid API Key.")
80
- elif response.status_code == 402:
81
- raise InsufficientCreditsError("Insufficient Compute Credits. Please recharge your ledger.")
82
- else:
83
- error_msg = response.json().get("detail", response.text)
84
- raise PrometheusError(f"HTTP {response.status_code}: {error_msg}")