data_processing.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. import json
  2. from decimal import Decimal, getcontext
  3. import pandas as pd
  4. import threading
  5. from collections import deque
  6. from scipy.integrate import trapz
  7. import numpy as np
  8. from scipy.optimize import minimize
  9. from logger_config import logger
  10. # 设置全局精度
  11. getcontext().prec = 28
  12. # 假设我们有一个数据流,订单簿和成交数据
  13. order_book_snapshots = deque(maxlen=100) # 存储订单簿快照
  14. spread_delta_snapshots = deque(maxlen=100) # 存储价差数据(最小变动价格的倍数)
  15. trade_snapshots = deque(maxlen=1000) # 存储成交数据
  16. stop_event = threading.Event()
  17. # 初始参数
  18. k_initial = 6
  19. A_initial = 140
  20. # 定义参数范围
  21. bounds = [(10, 1000.0), # A 的范围
  22. (0.01, 100.0)] # k 的范围
  23. # 假设S0是初始的参考价格
  24. S0 = -1
  25. # 记录最大挂单距离,并实时刷新
  26. max_delta_sum = 0
  27. def get_tick_size_from_prices(ask_price, bid_price):
  28. # 获取价格的小数位数
  29. ask_decimal_places = len(str(ask_price).split('.')[1])
  30. bid_decimal_places = len(str(bid_price).split('.')[1])
  31. # 确定最小变动单元
  32. tick_size = 10 ** -max(ask_decimal_places, bid_decimal_places)
  33. return tick_size
  34. def on_message_trade(_ws, message):
  35. global trade_snapshots
  36. json_message = json.loads(message)
  37. trade = {
  38. 'price': float(json_message['data']['p']),
  39. 'qty': float(json_message['data']['q']),
  40. 'timestamp': pd.to_datetime(json_message['data']['T'], unit='ms'),
  41. 'side': 'sell' if json_message['data']['m'] else 'buy'
  42. }
  43. trade_snapshots.append(trade)
  44. process_depth_data()
  45. def on_message_depth(_ws, message):
  46. global order_book_snapshots, spread_delta_snapshots
  47. json_message = json.loads(message)
  48. bids = [[float(price), float(quantity)] for price, quantity in json_message['data']['b'][:10]]
  49. asks = [[float(price), float(quantity)] for price, quantity in json_message['data']['a'][:10]]
  50. timestamp = pd.to_datetime(json_message['data']['E'], unit='ms')
  51. depth = {
  52. 'bids': bids,
  53. 'asks': asks,
  54. 'timestamp': timestamp
  55. }
  56. order_book_snapshots.append(depth)
  57. # 求价差
  58. ask_price = Decimal(str(asks[0][0]))
  59. bid_price = Decimal(str(bids[0][0]))
  60. tick_size = get_tick_size_from_prices(ask_price, bid_price)
  61. spread = float(ask_price - bid_price)
  62. spread_delta = int(spread / tick_size)
  63. spread_delta_snapshots.append(spread_delta)
  64. process_depth_data()
  65. def calculate_phi(prices, k, S0):
  66. """
  67. 计算 φ(k, ξ) 的值
  68. :param prices: 时间序列的价格数据
  69. :param k: 参数 k
  70. :param S0: 初始价格
  71. :return: φ(k, ξ) 的值
  72. """
  73. price_changes_pct = (np.array(prices) - S0) / np.array(prices)
  74. exponentials = np.exp(k * price_changes_pct)
  75. phi = np.mean(exponentials)
  76. return phi
  77. def calculate_integral_phi(prices, k, S0, time_points):
  78. """
  79. 计算 ∫ φ(k, ξ) dξ 的值,越大说明波动率也越大(价格波动)。
  80. :param prices: 时间序列的价格数据
  81. :param k: 参数 k
  82. :param S0: 初始价格
  83. :param time_points: 时间点数组
  84. :return: ∫ φ(k, ξ) dξ 的值
  85. """
  86. # 计算每个时间点的 φ(k, ξ) 值
  87. phi_values = [calculate_phi(prices[:i + 1], k, S0) for i in range(len(prices))]
  88. # 使用梯形法计算积分
  89. integral_phi = trapz(phi_values, time_points)
  90. return integral_phi
  91. def estimate_lambda(waiting_times, T):
  92. """
  93. 通过等待时间估计 λ(δ)
  94. :param waiting_times: 等待时间的数组
  95. :param T: 时间窗口的大小
  96. :return: λ(δ) 的估计值
  97. """
  98. # 将 waiting_times 转换为 NumPy 数组
  99. waiting_times = np.array(waiting_times)
  100. sum_indicator = np.sum(waiting_times < T)
  101. sum_waiting_times = int(np.sum(waiting_times).total_seconds() * 1000)
  102. lambda_hat = sum_indicator / sum_waiting_times
  103. return lambda_hat
  104. def objective_function(params, delta_max, log_lambda_hat_value, log_integral_phi_value):
  105. """
  106. 目标函数 r(A, k)
  107. :param params: 包含 A 和 k 的数组
  108. :param delta_max: 最大的价格偏移
  109. :param log_lambda_hat_value: log(λ(δ)) 的值
  110. :param log_integral_phi_value: log(∫ φ(k, ξ) dξ) 的值
  111. :return: 目标函数值
  112. """
  113. A, k = params
  114. residuals = []
  115. for delta in range(1, delta_max + 1):
  116. rst = (log_lambda_hat_value + k * delta - np.log(A) - log_integral_phi_value)
  117. residual = rst ** 2
  118. residuals.append(residual)
  119. return np.sum(residuals)
  120. def calculate_delta_sum(gamma, sigma_squared, T_minus_t, k):
  121. term1 = gamma * sigma_squared * T_minus_t
  122. term2 = (2 / gamma) * np.log(1 + (gamma / k))
  123. delta_sum = term1 + term2
  124. return delta_sum
  125. def calculate_sigma_squared(prices, timestamps):
  126. """
  127. 计算 σ^2 的值
  128. :param prices: 时间序列的价格数据
  129. :param timestamps: 时间戳数组
  130. :return: σ^2 的值
  131. """
  132. n = len(prices)
  133. if n < 2:
  134. return 0.0
  135. time_diff = int(int((timestamps[-1] - timestamps[0]).total_seconds() * 1000) / 100)
  136. price_diff_squared = [(1 - prices[i] / prices[i - 1]) ** 2 for i in range(1, n)]
  137. sigma_squared = np.sum(price_diff_squared) / time_diff
  138. return sigma_squared
  139. def process_depth_data():
  140. global order_book_snapshots, trade_snapshots, spread_delta_snapshots
  141. global k_initial, A_initial, S0
  142. global max_delta_sum
  143. # 数据预热,至少3条深度数据以及10条成交数据才能用于计算
  144. if len(order_book_snapshots) < 3 or len(trade_snapshots) < 10:
  145. return
  146. S_values = [((snapshot['bids'][0][0] + snapshot['asks'][0][0]) / 2) for snapshot in order_book_snapshots]
  147. if S0 < 0:
  148. S0 = S_values[0]
  149. # ========================= 计算 log(∫ φ(k, ξ) dξ) ==================
  150. # 提取时间戳并计算时间间隔
  151. order_book_timestamps = [snapshot['timestamp'] for snapshot in order_book_snapshots]
  152. order_book_time_points = [(timestamp - order_book_timestamps[0]).total_seconds() for timestamp in order_book_timestamps]
  153. # 计算 ∫ φ(k, ξ) dξ
  154. integral_phi_value = calculate_integral_phi(S_values, k_initial, S0, order_book_time_points)
  155. # 计算 log(∫ φ(k, ξ) dξ)
  156. log_integral_phi_value = np.log(integral_phi_value)
  157. # ========================== 估计 λ(δ) ==============================
  158. # 计算等待时间
  159. trade_timestamps = [snapshot['timestamp'] for snapshot in trade_snapshots]
  160. waiting_times = [trade_timestamps[i] - trade_timestamps[i - 1] for i in range(1, len(trade_timestamps))]
  161. # 时间窗口的大小
  162. T = pd.to_datetime(100, unit='ms') - pd.to_datetime(0, unit='ms')
  163. # 计算 λ(δ) 的估计值
  164. lambda_hat = estimate_lambda(waiting_times, T)
  165. # 计算 log(λ(δ))
  166. log_lambda_hat_value = np.log(lambda_hat)
  167. # ========================== 校准 A 和 k =============================
  168. delta_max = np.max(spread_delta_snapshots)
  169. # 优化目标函数以找到最优的 A 和 k
  170. result = minimize(objective_function, np.array([A_initial, k_initial]),
  171. args=(delta_max, log_lambda_hat_value, log_integral_phi_value),
  172. bounds=bounds)
  173. if result.success:
  174. A_initial, k_initial = result.x
  175. # logger.info(f"Optimal k: {k_initial}, delta_max: {delta_max}")
  176. # ========================== 计算 σ^2 ==========================
  177. sigma_squared = calculate_sigma_squared(S_values, order_book_timestamps)
  178. # ========================== 计算 δ^a + δ^b ==========================
  179. gamma = 1.0
  180. T_minus_t = 1.0
  181. delta_sum = calculate_delta_sum(gamma, sigma_squared, T_minus_t, k_initial)
  182. if delta_sum > max_delta_sum and len(trade_snapshots) > 70:
  183. logger.info(f"δ^a + δ^b: {delta_sum}, k: {k_initial}, dm: {delta_max}, λ(δ): {lambda_hat}, ∫ φ(k, ξ) dξ: {integral_phi_value}")
  184. max_delta_sum = delta_sum