api.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. import random
  2. import string
  3. import time
  4. import base64
  5. from hashlib import sha256
  6. from hmac import HMAC
  7. import http.client
  8. import requests
  9. import pandas as pd
  10. APPID = "tubmafwrzhpgfiuf"
  11. SECRET = "eotpcqbvhycdshwscqnytiwzbgonposs"
  12. def generate_nonce(length=32):
  13. """Generate a random nonce."""
  14. return ''.join(random.choices(string.ascii_letters + string.digits, k=length))
  15. def get_timestamp():
  16. """Get the current timestamp."""
  17. return int(time.time())
  18. def build_sign_str(appid, nonce, timestamp):
  19. """Build the string to be signed."""
  20. return f'appid={appid}&nonce={nonce}&timestamp={timestamp}'
  21. def calculate_signature(secret, message):
  22. """Calculate the HMAC SHA-256 signature."""
  23. return base64.urlsafe_b64encode(HMAC(secret.encode('utf-8'), message.encode('utf-8'), sha256).digest()).decode('utf-8')
  24. def fetch_indicator_details(indicator_id):
  25. """Fetch the details for a specific indicator ID."""
  26. nonce = generate_nonce()
  27. timestamp = get_timestamp()
  28. sign_str = build_sign_str(APPID, nonce, timestamp)
  29. signature = calculate_signature(SECRET, sign_str)
  30. headers = {
  31. 'nonce': nonce,
  32. 'timestamp': str(timestamp),
  33. 'appid': APPID,
  34. 'signature': signature,
  35. 'Accept': "*/*",
  36. 'Accept-Encoding': "gzip, deflate, br",
  37. 'User-Agent': "PostmanRuntime-ApipostRuntime/1.1.0",
  38. 'Connection': "keep-alive",
  39. }
  40. url = f"https://etahub.hzinsights.com/v1/edb/data?EdbCode={indicator_id}"
  41. response = requests.get(url, headers=headers)
  42. if response.status_code == 200:
  43. return response.json().get('Data')
  44. else:
  45. print(
  46. f"Failed to fetch data for ID {indicator_id}, status code: {response.status_code}")
  47. return None
  48. def fetch_indicator_name(indicator_id):
  49. """Fetch the name for a specific indicator ID."""
  50. nonce = generate_nonce()
  51. timestamp = get_timestamp()
  52. sign_str = build_sign_str(APPID, nonce, timestamp)
  53. signature = calculate_signature(SECRET, sign_str)
  54. headers = {
  55. 'nonce': nonce,
  56. 'timestamp': str(timestamp),
  57. 'appid': APPID,
  58. 'signature': signature,
  59. 'Accept': "*/*",
  60. 'Accept-Encoding': "gzip, deflate, br",
  61. 'User-Agent': "PostmanRuntime-ApipostRuntime/1.1.0",
  62. 'Connection': "keep-alive",
  63. }
  64. url = f"https://etahub.hzinsights.com/v1/edb/detail?EdbCode={indicator_id}"
  65. response = requests.get(url, headers=headers)
  66. if response.status_code == 200:
  67. return response.json().get('Data').get('EdbName')
  68. else:
  69. print(
  70. f"Failed to fetch data for ID {indicator_id}, status code: {response.status_code}")
  71. return None
  72. def fetch_data_by_indicators(indicator_ids, output_path=None):
  73. """
  74. 根据提供的indicator IDs获取数据并返回DataFrame
  75. 参数:
  76. indicator_ids (list): 指标ID列表
  77. output_path (str, optional): 如果提供,将结果保存为Excel文件的路径
  78. 返回:
  79. pandas.DataFrame: 包含所有指标数据的DataFrame
  80. """
  81. # Dictionary to store DataFrames for each indicator
  82. data_frames = {}
  83. for indicator_id in indicator_ids:
  84. data = fetch_indicator_details(indicator_id)
  85. if data:
  86. df = pd.DataFrame(data)
  87. df['DataTime'] = pd.to_datetime(df['DataTime'])
  88. df.set_index('DataTime', inplace=True)
  89. df.sort_index(inplace=True)
  90. df = df[['Value']].rename(columns={'Value': fetch_indicator_name(indicator_id)})
  91. data_frames[indicator_id] = df
  92. # Concatenate all DataFrames along the columns
  93. if data_frames:
  94. result_df = pd.concat(data_frames.values(), axis=1)
  95. if output_path:
  96. result_df.to_excel(output_path)
  97. print(f"Data saved successfully as '{output_path}'")
  98. return result_df
  99. return None
  100. '''
  101. # 示例用法
  102. if __name__ == "__main__":
  103. example_indicators = ["RBWTICKMc1", "C2406121350446455"]
  104. df = fetch_data_by_indicators(example_indicators, "data_input/RBOB.xlsx")
  105. print(df.info())
  106. '''