DỰ ÁN 06: KIỂM ĐỊNH COINTEGRATION CRYPTO CÙNG BINANCE API VÀ KALMAN FILTER
I. Ý tưởng chính
Trong bài viết này tôi sẽ kiểm định cointegration, tính hedging ratio tĩnh và động bằng bộ lọc Kalman.
II. Kiểm định cointegration
Dữ liệu được sử dụng trong bài viết là chuỗi dữ liệu của 2 symbol là ATOMUSDT và NEARUSDT từ 1/1/2021 đến 1/9/2021, khung thời gian là H1.
Import các thư viện như sau:
Hàm để lấy dữ liệu từ binance api như sau:
III. Tính toán Hedging ratio (HR)
HR hiểu đơn giản là hệ số góc đường hồi quy của 2 chuỗi giá
Công thức: At = I + H * Bt + et (H là hedging ratio của 2 chuỗi giá A và B, I là hệ số chặn, et là sai số)
1. Tính toán HR tĩnh:
1.1 Tính HR theo CADF
Ta sẽ tính toán trong 2 trường hợp, tại đó mỗi symbol sẽ được làm biến độc lập hoặc phụ thuộc một lần:
- Của chuỗi et tạo ra từ phương pháp Johansen Test: 120 (giờ)
class MyKalmanFilter:
def __init__(self, delta=1e-4, R=1e-3):
# measurement noise variance
self.R = R
# co-variance of process noise(2 dimensions)
self.Q = delta / (1-delta) * np.eye(2) #Tao ma tran 2*2 voi 1 o duong cheo, sau do nhan ma tran nay voi delta/(1-delta)
# state (slope, intercept) will be (2 x n), we will initialize with just one column at first
self.x = np.zeros((2, 1)) #Tao ma tran rong 2*1 (se thay doi theo thoi gian)
# state covariance
self.P = np.zeros((2,2)) #Tao ma tran rong 2*2 (se thay doi theo thoi gian)
def step_forward(self, y1, y2): #y1, y2 lan luot la gia tri tung hang cua cot EWC va EWA
# Before entering the equations, let's define H as (1, 2) matrix
H = np.array([y2, 1])[None] #Tao mot array kieu [[y2, 1]]
# and define z
z = y1
## TIME UPDATE ##
# first thing is to predict new state as the previous one (2x1)
x_hat = self.x[:, -1][..., None]
# then, the uncertainty or covariance prediction
P_hat = self.P + self.Q
## MEASUREMENT UPDATE ##
# calc the Kalman gain
K = P_hat.dot(H.T)/(H.dot(P_hat.dot(H.T))+self.R)
# state update part 1 (measurement estimation)
z_hat = H.dot(x_hat)
# state update part 2
x = x_hat + K.dot(z-z_hat)
# uncertainty update
self.P = (np.eye(2)-K.dot(H)).dot(P_hat)
# append the new state to the vector
self.x = np.concatenate([self.x, x], axis=1)
return x, self.P, K, z_hat
mkf = MyKalmanFilter(delta=1e-4, R=1e-3)
series = []
for idx, row in c.iterrows():
x, P, K, z_hat = mkf.step_forward(row[symbol_list[1]], row[symbol_list[0]])
series.append(row[symbol_list[1]] - z_hat.squeeze())
# Plot the combined portfolio
plt.figure(figsize=(20,10))
plt.plot(series[10:])
# Plot the hedge ratio over time
plt.figure(figsize=(20,5))
plt.plot(mkf.x[0, 1:])
# Plot the intercept over time
plt.figure(figsize=(20,5))
plt.plot(mkf.x[1, 1:])
et:
Túm lại là kết quả giống nhau.
Các bạn có thể tải full notebook tại đây, sorry vì cái notebook nhìn như tờ nháp 😝
Cùng đón xem bài viết tiếp theo về thực thi chiến lược pair trading Crypto bằng Kalman Filter nha.







0 nhận xét: