-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbrain_client.py
More file actions
282 lines (229 loc) · 9.33 KB
/
brain_client.py
File metadata and controls
282 lines (229 loc) · 9.33 KB
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
"""
WorldQuant Brain API Client Library
A Python client for interacting with the WorldQuant Brain platform API.
Supports authentication, alpha simulation, and result retrieval.
"""
import json
import getpass
import requests
from time import sleep
from os.path import expanduser
from typing import Optional
BASE_URL = "https://api.worldquantbrain.com"
class BrainClient:
"""Client for the WorldQuant Brain API."""
def __init__(
self,
email: Optional[str] = None,
password: Optional[str] = None,
credentials_file: Optional[str] = None,
):
"""
Initialize the client. Credentials priority:
1. email + password passed directly
2. credentials_file path (JSON: ["email", "password"])
3. ~/.brain_credentials (if the file exists)
4. Interactive prompt (asks at runtime)
Args:
email: Brain platform email.
password: Brain platform password.
credentials_file: Path to a JSON credentials file.
"""
self._session = requests.Session()
self._authenticated = False
if email and password:
self._session.auth = (email, password)
return
if credentials_file:
with open(expanduser(credentials_file), "r") as f:
self._session.auth = tuple(json.load(f))
return
default_file = expanduser("~/.brain_credentials")
try:
with open(default_file, "r") as f:
self._session.auth = tuple(json.load(f))
except FileNotFoundError:
# Fall back to interactive prompt
email = input("WorldQuant Brain email: ").strip()
password = getpass.getpass("WorldQuant Brain password: ")
self._session.auth = (email, password)
@classmethod
def login(cls, email: Optional[str] = None, password: Optional[str] = None) -> "BrainClient":
"""
Create a BrainClient and authenticate in one step.
If email/password are not provided, prompts interactively.
Args:
email: Brain platform email (optional).
password: Brain platform password (optional).
Returns:
An authenticated BrainClient instance.
Example:
client = BrainClient.login() # interactive prompt
client = BrainClient.login("me@email.com", "pass") # direct
"""
client = cls(email=email, password=password)
client.authenticate()
return client
# -------------------------------------------------------------------------
# Authentication
# -------------------------------------------------------------------------
def authenticate(self) -> dict:
"""
Sign in and obtain a JWT token.
Returns:
Response JSON from the /authentication endpoint.
Raises:
requests.HTTPError: If authentication fails.
"""
response = self._session.post(f"{BASE_URL}/authentication")
response.raise_for_status()
self._authenticated = True
return response.json()
# -------------------------------------------------------------------------
# Simulations
# -------------------------------------------------------------------------
def simulate(self, expression: str, settings: dict = None, alpha_type: str = "REGULAR", regular: str = "close") -> "SimulationResult":
"""
Submit an alpha expression for simulation.
Args:
expression: The alpha expression string.
settings: Simulation settings dict. Defaults to standard equity settings.
alpha_type: Type of simulation, e.g. "REGULAR".
regular: Price field, e.g. "close".
Returns:
A SimulationResult object to poll for completion.
Raises:
requests.HTTPError: If the submission fails.
"""
default_settings = {
"instrumentType": "EQUITY",
"region": "USA",
"universe": "TOP3000",
"delay": 1,
"decay": 15,
"neutralization": "SUBINDUSTRY",
"truncation": 0.08,
"maxTrade": "ON",
"pasteurization": "ON",
"testPeriod": "P1Y6M",
"unitHandling": "VERIFY",
"nanHandling": "OFF",
"language": "FASTEXPR",
"visualization": False,
}
if settings:
default_settings.update(settings)
payload = {
"type": alpha_type,
"settings": default_settings,
"regular": expression if regular == "close" else regular,
}
# If expression is provided separately from regular field
if regular == "close":
payload["regular"] = expression
response = self._session.post(f"{BASE_URL}/simulations", json=payload)
response.raise_for_status()
progress_url = response.headers.get("Location")
return SimulationResult(self._session, progress_url)
# -------------------------------------------------------------------------
# Alphas
# -------------------------------------------------------------------------
def get_alpha(self, alpha_id: str) -> dict:
"""
Retrieve details of a completed alpha by ID.
Args:
alpha_id: The alpha ID string.
Returns:
Alpha details as a dict.
"""
response = self._session.get(f"{BASE_URL}/alphas/{alpha_id}")
response.raise_for_status()
return response.json()
def get_pnl(self, alpha_id: str, poll_interval: float = 5.0) -> dict:
"""
Retrieve PnL record set for an alpha, polling until ready.
Args:
alpha_id: The alpha ID string.
poll_interval: Fallback seconds to wait between polls if no Retry-After header.
Returns:
PnL record set as a dict.
"""
return self._poll_recordset(alpha_id, "pnl", poll_interval)
def get_recordset(self, alpha_id: str, record_set_name: str, poll_interval: float = 5.0) -> dict:
"""
Retrieve any named record set for an alpha, polling until ready.
Args:
alpha_id: The alpha ID string.
record_set_name: Name of the record set (e.g. "pnl", "sharpe").
poll_interval: Fallback seconds between polls if no Retry-After header.
Returns:
Record set data as a dict.
"""
return self._poll_recordset(alpha_id, record_set_name, poll_interval)
def _poll_recordset(self, alpha_id: str, record_set_name: str, poll_interval: float) -> dict:
url = f"{BASE_URL}/alphas/{alpha_id}/recordsets/{record_set_name}"
while True:
response = self._session.get(url)
retry_after = float(response.headers.get("Retry-After", 0))
if retry_after == 0:
response.raise_for_status()
return response.json()
print(f"Sleeping for {retry_after} seconds...")
sleep(retry_after)
class SimulationResult:
"""Represents a pending or completed alpha simulation."""
def __init__(self, session: requests.Session, progress_url: str):
self._session = session
self.progress_url = progress_url
self.alpha_id: str = None
self._result: dict = None
def wait(self, verbose: bool = True) -> dict:
"""
Poll until the simulation completes.
Args:
verbose: If True, print polling status messages.
Returns:
The completed simulation result JSON containing the alpha id.
"""
while True:
response = self._session.get(self.progress_url)
retry_after = float(response.headers.get("Retry-After", 0))
if retry_after == 0:
response.raise_for_status()
self._result = response.json()
self.alpha_id = self._result.get("alpha")
if verbose:
print(f"Alpha simulation complete. Alpha ID: {self.alpha_id}")
return self._result
if verbose:
print(f"Simulating... sleeping for {retry_after} seconds")
sleep(retry_after)
def get_alpha(self) -> dict:
"""
Fetch full alpha details after simulation completes.
Returns:
Alpha details dict.
Raises:
RuntimeError: If wait() has not been called yet.
"""
if not self.alpha_id:
raise RuntimeError("Simulation not complete. Call wait() first.")
response = self._session.get(f"{BASE_URL}/alphas/{self.alpha_id}")
response.raise_for_status()
return response.json()
def get_pnl(self, poll_interval: float = 5.0) -> dict:
"""
Retrieve PnL record set after simulation completes.
Args:
poll_interval: Fallback seconds between polls if no Retry-After header.
Returns:
PnL record set dict.
Raises:
RuntimeError: If wait() has not been called yet.
"""
if not self.alpha_id:
raise RuntimeError("Simulation not complete. Call wait() first.")
client = BrainClient.__new__(BrainClient)
client._session = self._session
client._authenticated = True
return client.get_pnl(self.alpha_id, poll_interval)