-
Notifications
You must be signed in to change notification settings - Fork 213
/
cwmr.py
144 lines (118 loc) · 4.35 KB
/
cwmr.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
import numpy as np
import pandas as pd
import scipy.stats
from numpy import diag, log, sqrt, trace
from numpy.linalg import inv
from .. import tools
from ..algo import Algo
class CWMR(Algo):
"""Confidence weighted mean reversion.
Reference:
B. Li, S. C. H. Hoi, P.L. Zhao, and V. Gopalkrishnan.
Confidence weighted mean reversion strategy for online portfolio selection, 2013.
http://jmlr.org/proceedings/papers/v15/li11b/li11b.pdf
"""
PRICE_TYPE = "ratio"
REPLACE_MISSING = True
def __init__(self, eps=-0.5, confidence=0.95):
"""
:param eps: Mean reversion threshold (expected return on current day must be lower
than this threshold). Recommended value is -0.5.
:param confidence: Confidence parameter for profitable mean reversion portfolio.
Recommended value is 0.95.
"""
super().__init__()
# input check
if not (0 <= confidence <= 1):
raise ValueError("confidence must be from interval [0,1]")
self.eps = eps
self.theta = scipy.stats.norm.ppf(confidence)
def init_weights(self, columns):
m = len(columns)
return np.ones(m) / m
def init_step(self, X):
m = X.shape[1]
self.sigma = np.matrix(np.eye(m) / m ** 2)
def step(self, x, last_b, history):
# initialize
m = len(x)
mu = np.matrix(last_b).T
sigma = self.sigma
theta = self.theta
eps = self.eps
x = np.matrix(x).T # matrices are easier to manipulate
# 4. Calculate the following variables
M = mu.T * x
V = x.T * sigma * x
x_upper = sum(diag(sigma) * x) / trace(sigma)
# 5. Update the portfolio distribution
mu, sigma = self.update(x, x_upper, mu, sigma, M, V, theta, eps)
# 6. Normalize mu and sigma
mu = tools.simplex_proj(mu)
sigma = sigma / (m ** 2 * trace(sigma))
"""
sigma(sigma < 1e-4*eye(m)) = 1e-4;
"""
self.sigma = sigma
return mu
def update(self, x, x_upper, mu, sigma, M, V, theta, eps):
# lambda from equation 7
foo = (
V - x_upper * x.T * np.sum(sigma, axis=1)
) / M ** 2 + V * theta ** 2 / 2.0
a = foo ** 2 - V ** 2 * theta ** 4 / 4
b = 2 * (eps - log(M)) * foo
c = (eps - log(M)) ** 2 - V * theta ** 2
a, b, c = a[0, 0], b[0, 0], c[0, 0]
lam = max(
0,
(-b + sqrt(b ** 2 - 4 * a * c)) / (2.0 * a),
(-b - sqrt(b ** 2 - 4 * a * c)) / (2.0 * a),
)
# bound it due to numerical problems
lam = min(lam, 1e7)
# update mu and sigma
U_sqroot = 0.5 * (
-lam * theta * V + sqrt(lam ** 2 * theta ** 2 * V ** 2 + 4 * V)
)
mu = mu - lam * sigma * (x - x_upper) / M
sigma = inv(inv(sigma) + theta * lam / U_sqroot * diag(x) ** 2)
"""
tmp_sigma = inv(inv(sigma) + theta*lam/U_sqroot*diag(xt)^2);
% Don't update sigma if results are badly scaled.
if all(~isnan(tmp_sigma(:)) & ~isinf(tmp_sigma(:)))
sigma = tmp_sigma;
end
"""
return mu, sigma
class CWMR_VAR(CWMR):
"""First variant of a CWMR outlined in original article. It is
only approximation to the posted problem."""
def update(self, x, x_upper, mu, sigma, M, V, theta, eps):
# lambda from equation 7
foo = (V - x_upper * x.T * np.sum(sigma, axis=1)) / M ** 2
a = 2 * theta * V * foo
b = foo + 2 * theta * V * (eps - log(M))
c = eps - log(M) - theta * V
a, b, c = a[0, 0], b[0, 0], c[0, 0]
lam = max(
0,
(-b + sqrt(b ** 2 - 4 * a * c)) / (2.0 * a),
(-b - sqrt(b ** 2 - 4 * a * c)) / (2.0 * a),
)
# bound it due to numerical problems
lam = min(lam, 1e7)
# update mu and sigma
mu = mu - lam * sigma * (x - x_upper) / M
sigma = inv(inv(sigma) + 2 * lam * theta * diag(x) ** 2)
"""
tmp_sigma = inv(inv(sigma) + theta*lam/U_sqroot*diag(xt)^2);
% Don't update sigma if results are badly scaled.
if all(~isnan(tmp_sigma(:)) & ~isinf(tmp_sigma(:)))
sigma = tmp_sigma;
end
"""
return mu, sigma
# use case
if __name__ == "__main__":
tools.quickrun(CWMR())