main_simple.py 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. import httpx
  2. import json
  3. from httpx import BasicAuth
  4. from time import sleep
  5. class WorldQuantBrainAPI:
  6. def __init__(self, credentials_file='brain_credentials.txt'):
  7. self.credentials_file = credentials_file
  8. self.client = None
  9. self.brain_api_url = 'https://api.worldquantbrain.com'
  10. def load_credentials(self):
  11. """读取本地账号密码"""
  12. with open(self.credentials_file) as f:
  13. credentials = eval(f.read())
  14. return credentials[0], credentials[1]
  15. def login(self):
  16. """登录认证"""
  17. username, password = self.load_credentials()
  18. self.client = httpx.Client(auth=BasicAuth(username, password))
  19. response = self.client.post(f'{self.brain_api_url}/authentication')
  20. print(f"登录状态: {response.status_code}")
  21. if response.status_code == 201:
  22. print("登录成功!")
  23. return True
  24. else:
  25. print(f"登录失败: {response.json()}")
  26. return False
  27. def simulate_alpha(self, expression, settings=None):
  28. """模拟Alpha因子"""
  29. if self.client is None:
  30. raise Exception("请先登录")
  31. default_settings = {
  32. 'instrumentType': 'EQUITY',
  33. 'region': 'USA',
  34. 'universe': 'TOP3000',
  35. 'delay': 1,
  36. 'decay': 0,
  37. 'neutralization': 'INDUSTRY',
  38. 'truncation': 0.08,
  39. 'pasteurization': 'ON',
  40. 'unitHandling': 'VERIFY',
  41. 'nanHandling': 'OFF',
  42. 'language': 'FASTEXPR',
  43. 'visualization': False,
  44. }
  45. if settings:
  46. default_settings.update(settings)
  47. simulation_data = {
  48. 'type': 'REGULAR',
  49. 'settings': default_settings,
  50. 'regular': expression
  51. }
  52. sim_resp = self.client.post(
  53. f'{self.brain_api_url}/simulations',
  54. json=simulation_data,
  55. )
  56. print(f"模拟提交状态: {sim_resp.status_code}")
  57. sim_progress_url = sim_resp.headers['location']
  58. print(f"进度URL: {sim_progress_url}")
  59. while True:
  60. sim_progress_resp = self.client.get(sim_progress_url)
  61. retry_after_sec = float(sim_progress_resp.headers.get("Retry-After", 0))
  62. if retry_after_sec == 0:
  63. break
  64. print(sim_progress_resp.json())
  65. print(f"等待 {retry_after_sec} 秒...")
  66. sleep(retry_after_sec)
  67. alpha_id = sim_progress_resp.json()["alpha"]
  68. print(f"生成的Alpha ID: {alpha_id}")
  69. return alpha_id
  70. def close(self):
  71. """关闭连接"""
  72. if self.client:
  73. self.client.close()
  74. if __name__ == "__main__":
  75. api = WorldQuantBrainAPI()
  76. try:
  77. # 读取账号密码并登录
  78. if api.login():
  79. # 模拟Alpha因子
  80. alpha_id = api.simulate_alpha("liabilities/assets")
  81. print(f"模拟完成,Alpha ID: {alpha_id}")
  82. finally:
  83. api.close()