4. 市场深度指标计算与可视化
任务目标
基于订单簿的限价单数据,计算各价位上的累计挂单量(市场深度),并绘制深度曲线图,直观展示买盘与卖盘在不同价格水平上的流动性分布。
数据与依赖
本案例使用Python标准库collections中的defaultdict进行数据聚合,使用matplotlib绘制深度图。输入数据为模拟的订单簿快照(含价格与数量),格式与真实交易所API返回的bids/asks数组一致。
核心实现
import matplotlib.pyplot as plt
from collections import defaultdict
# 模拟订单簿快照: [价格, 数量]
order_book = {
'bids': [
[99.5, 200], [99.4, 150], [99.3, 300],
[99.2, 100], [99.1, 250], [99.0, 180]
],
'asks': [
[100.5, 120], [100.6, 220], [100.7, 160],
[100.8, 90], [100.9, 310], [101.0, 140]
]
}
def compute_depth(orders):
"""按价格聚合挂单量,返回按价格升序排列的(价格, 累计量)列表"""
depth = defaultdict(float)
for price, qty in orders:
depth[price] += qty
return sorted(depth.items())
def cumulative_depth(sorted_orders):
"""将逐档深度转换为累计深度(从最优价向外累加)"""
result = []
cum = 0.0
for price, qty in sorted_orders:
cum += qty
result.append((price, cum))
return result
# 计算逐档深度与累计深度
bid_depth = compute_depth(order_book['bids'])
ask_depth = compute_depth(order_book['asks'])
bid_cum = cumulative_depth(bid_depth) # 买盘从最高买价向下累计
ask_cum = cumulative_depth(ask_depth) # 卖盘从最低卖价向上累计
# 绘制市场深度图
bid_prices = [p for p, _ in bid_cum]
bid_volumes = [v for _, v in bid_cum]
ask_prices = [p for p, _ in ask_cum]
ask_volumes = [v for _, v in ask_cum]
plt.figure(figsize=(10, 6))
plt.step(bid_prices, bid_volumes, where='post', label='Bid Depth', color='#2E86AB', linewidth=2)
plt.step(ask_prices, ask_volumes, where='post', label='Ask Depth', color='#A23B72', linewidth=2)
plt.xlabel('Price')
plt.ylabel('Cumulative Volume')
plt.title('Market Depth Chart')
plt.legend()
plt.grid(alpha=0.3)
plt.tight_layout()
plt.show()
# 控制台输出逐档深度(验证用)
print("=== Bid Depth (price: volume) ===")
for p, v in bid_depth:
print(f"{p}: {v}")
print("=== Ask Depth (price: volume) ===")
for p, v in ask_depth:
print(f"{p}: {v}")
运行与验证
运行方式:将代码保存为market_depth.py,在已安装matplotlib的环境中执行python market_depth.py。
预期输出:控制台打印逐档深度,例如买一档99.5: 200.0,卖一档100.5: 120.0;同时弹出深度曲线窗口,其中蓝色阶梯线(买盘)从最高买价向左下延伸,粉色阶梯线(卖盘)从最低卖价向右上延伸,两线在买卖价差处形成“凹”形深度剖面。
通过条件:若图中买盘累计量随价格下降单调不减、卖盘累计量随价格上升单调不减,且各价位累计值与订单簿数据一致,则实现正确。