for t in range(n): if t >= min_period: b = self.get_b(data[:t, :], re_b) # double check (Normalize the constraint) b = b / np.sum(b) daily_portfolio[t, :] = b.reshape((1, m)) daily_ret[t] = np.dot( data[t, :], b) * (1 - tc / 2 * np.sum(np.absolute(b - re_b))) cum_ret = cum_ret * daily_ret[t] cumprod_ret[t] = cum_ret re_b = b * data[t, :][:, None] / daily_ret[t] self.exp_ret[0, self.L] *= np.dot(data[t, :], self.exp_w[self.K * self.L, :]) for k in np.arange(self.K): for l in np.arange(self.L): self.exp_ret[k, l] *= np.dot( data[t, :], self.exp_w[(k - 1) * self.L + l - 1, :]) logging.info('%d\t%f\t%f\n' % (t + 1, daily_ret[t], cumprod_ret[t])) logging.info('tc=%f, Final Return: %.2f\n' % (tc, cum_ret)) if __name__ == "__main__": tools.run(bk())
if t >= min_period: b = self.get_b(data[:t, :], re_b) # double check (Normalize the constraint) b = b / np.sum(b) daily_portfolio[t, :] = b.reshape((1, m)) daily_ret[t] = np.dot( data[t, :], b) * (1 - tc / 2 * np.sum(np.absolute(b - re_b))) cum_ret = cum_ret * daily_ret[t] cumprod_ret[t] = cum_ret re_b = b * data[t, :][:, None] / daily_ret[t] self.data_day[t, :] = data[t, :].dot(self.exp_w.T) for k in np.arange(1, self.window): self.exp_ret[k - 1] = np.dot(self.exp_ret[k - 1] * data[k, :], self.exp_w[k - 1, :].T) self.exp_ret2[k - 1] *= self.data_day[t, :].dot( self.exp_w2[k - 1, :]) self.exp_w2[k - 1, :] *= self.data_day[t, :] / np.dot( self.data_day[t, :], self.exp_w2[k - 1, :].T) logging.info('%d\t%f\t%f\n' % (t + 1, daily_ret[t], cumprod_ret[t])) logging.info('tc=%f, Final Return: %.2f\n' % (tc, cum_ret)) if __name__ == "__main__": tools.run(anticor2())
:param alpha: trade off parameter for moving average ''' super(olmar2, self).__init__() self.eps = eps self.alpha = alpha def get_b(self, data, last_b): T, N = data.shape data_phi = np.ones((1,N)) data_phi = self.alpha + (1-self.alpha)*data_phi/data[T-1,:] ell = max(0, self.eps - data_phi.dot(last_b)) x_bar = data_phi.mean() denominator = np.linalg.norm(data_phi - x_bar)**2 if denominator == 0: lam = 0 else: lam = ell / denominator data_phi = np.squeeze(data_phi) b = last_b.ravel() + lam * (data_phi - x_bar) b = tools.simplex_proj(b.ravel()) return b[:,None] if __name__ == "__main__": tools.run(olmar2())
cumprod_ret = np.ones((n, 1), np.float) daily_ret = np.ones((n, 1), np.float) #daily return b = np.ones((m, 1), np.float) / m # initialize b re_b = np.zeros((m, 1), np.float) # initialize rebalanced b daily_portfolio = np.zeros((n, m)) b = self.weights(data) for t in range(n): # double check (Normalize the constraint) b = b / np.sum(b) daily_portfolio[t, :] = b.reshape((1, m)) daily_ret[t] = np.dot( data[t, :], b) * (1 - tc / 2 * np.sum(np.absolute(b - re_b))) cum_ret *= daily_ret[t] cumprod_ret[t] = cum_ret re_b = b * data[t, :][:, None] / daily_ret[t] logging.info('%d\t%f\t%f\n' % (t + 1, daily_ret[t], cumprod_ret[t])) logging.info('tc=%f, Final Return: %.2f\n' % (tc, cum_ret)) self.pDiff = daily_ret self.last_b = b if __name__ == '__main__': tools.run(best())
def test_algo(): from mercurius.strategy.olmar import olmar from mercurius.strategy import tools tools.run(olmar(), min_period=2)
for i in range(S): bnew = np.copy(b) j = np.random.randint(low=1, high=N) a = np.random.randint(-1, 1) if a == 0: a = 1 bnew[j] = b[j] + (a * delta) if bnew[j] >= del0 and bnew[N - 1] >= del0: x = self.findQ(b, data, del0, delta) y = self.findQ(bnew, data, del0, delta) pr = np.minimum(y / x, 1) temp = np.random.uniform(0, 1) if temp < pr: b = bnew allM[:, m] = b.conj().T return np.sum(allM, axis=1) / M def findQ(self, b, data, del0, delta): N = data.shape[1] P = np.prod(data.dot(b)) Q = np.dot( P, np.minimum(1, np.exp((b[N - 1] - (2 * del0)) / ((N - 1) * delta)))) return Q if __name__ == '__main__': tools.run(up())
from mercurius.strategy.base import expert from mercurius.strategy import tools import numpy as np import logging class sp(expert): '''Switch Portfolio''' def __init__(self, gamma=0.25): super(sp, self).__init__() self.gamma = gamma def get_b(self, data, last_b): T, N = data.shape b = last_b * (1 - self.gamma - self.gamma / (N - 1)) + self.gamma / (N - 1) b = b / np.sum(b) return b if __name__ == "__main__": tools.run(sp())
self.b = b return self.b def update(self, b, data, eps, C): """ Update portfolio weights to satisfy constraint b * x <= eps and minimize distance to previous weights. """ T, N = data.shape x = data[-1, :] x_mean = np.mean(x) le = np.maximum(0., np.dot(b, x) - eps) # daily return denominator = np.square(np.linalg.norm(x - x_mean)) if self.variant == 0: tau = le / denominator elif self.variant == 1: tau = np.minimum(C, le / denominator) elif self.variant == 2: tau = le / (denominator + 0.5 / C) # limit lambda to avoid numerical problems tau = np.minimum(100000, tau) # update portfolio b = b - tau * (x - x_mean) # project it onto simplex return tools.simplex_proj(b.ravel()) if __name__ == "__main__": tools.run(pamr())
from mercurius.strategy.base import expert from mercurius.strategy import tools import numpy as np class m0(expert): def __init__(self, beta=0.5, C=None): super(m0, self).__init__() self.beta = beta self.C = C def get_b(self, data, last_b): m = data.shape[1] if self.C is None: self.C = np.zeros((m, 1)) b = (self.C + self.beta) / (m * self.beta + np.ones( (1, m)).dot(self.C)) max_ind = np.argmax(data[-1, :]) self.C[max_ind] += 1 return b if __name__ == "__main__": tools.run(m0())
b = np.ones((m,1), np.float) / m # initialize b re_b = np.zeros((m,1), np.float) # initialize rebalanced b daily_portfolio = np.zeros((n,m)) self.exp_ret = np.ones((self.K,self.L)) self.exp_w = np.ones((self.K*self.L,m)) / m for t in range(n): if t>= min_period: b = self.get_b(data[:t-1,:], re_b) # double check (Normalize the constraint) b = b / np.sum(b) daily_portfolio[t,:] = b.reshape((1,m)) daily_ret[t] = np.dot(data[t,:],b)*(1-tc/2*np.sum(np.absolute(b-re_b))) cum_ret = cum_ret * daily_ret[t] cumprod_ret[t] = cum_ret re_b = b * data[t,:][:,None] / daily_ret[t] self.exp_ret[:,0] *= np.dot(data[t,:],self.exp_w.T) logging.info('%d\t%f\t%f\n' % (t+1, daily_ret[t], cumprod_ret[t])) logging.info('tc=%f, Final Return: %.2f\n' % (tc, cum_ret)) self.pDiff = daily_ret if __name__ == "__main__": tools.run(cornu())
self.exp_ret = np.ones((self.K, self.L + 1)) self.exp_w = np.ones((self.K * (self.L + 1), m)) / m for t in range(n): if t >= min_period: b = self.get_b(data[:t, :], re_b) # double check (Normalize the constraint) b = b / np.sum(b) daily_portfolio[t, :] = b.reshape((1, m)) daily_ret[t] = np.dot( data[t, :], b) * (1 - tc / 2 * np.sum(np.absolute(b - re_b))) cum_ret = cum_ret * daily_ret[t] cumprod_ret[t] = cum_ret re_b = b * data[t, :][:, None] / daily_ret[t] for k in np.arange(self.K): for l in np.arange(self.L): self.exp_ret[k, l] *= np.dot( data[t, :], self.exp_w[(k - 1) * self.L + l - 1, :]) logging.info('%d\t%f\t%f\n' % (t + 1, daily_ret[t], cumprod_ret[t])) logging.info('tc=%f, Final Return: %.2f\n' % (tc, cum_ret)) if __name__ == "__main__": tools.run(bnn())
# calculate gradient grad = np.mat(data[-1, :] / np.dot(last_b, data[-1, :])).T # update A self.A += grad * grad.T # update b self.bt += (1 + 1. / self.beta) * grad # projection of p induced by norm A pp = self.projection_in_norm(self.delta * self.A.I * self.bt, self.A) self.b = pp * (1 - self.eta) + np.ones(N) / N * self.eta return self.b def projection_in_norm(self, x, M): """ Projection of x to simplex indiced by matrix M. Uses quadratic programming. """ m = M.shape[0] P = matrix(2 * M) q = matrix(-2 * M * x) G = matrix(-np.eye(m)) h = matrix(np.zeros((m, 1))) A = matrix(np.ones((1, m))) b = matrix(1.) sol = solvers.qp(P, q, G, h, A, b) return np.squeeze(sol['x']) if __name__ == "__main__": tools.run(ons())
cumprod_ret = np.ones((n, 1), np.float) daily_ret = np.ones((n, 1), np.float) #daily return b = np.ones((m, 1), np.float) / m # initialize b re_b = np.zeros((m, 1), np.float) # initialize rebalanced b daily_portfolio = np.zeros((n, m)) for t in range(n): if t >= min_period: b = self.get_b(data[:t, :], re_b) # double check (Normalize the constraint) b = b / np.sum(b) daily_portfolio[t, :] = b.reshape((1, m)) daily_ret[t] = np.dot( data[t, :], b) * (1 - tc / 2 * np.sum(np.absolute(b - re_b))) cum_ret *= daily_ret[t] cumprod_ret[t] = cum_ret re_b = b * np.reshape(data[t, :], (1, m)) / daily_ret[t] logging.info('%d\t%f\t%f\n' % (t + 1, daily_ret[t], cumprod_ret[t])) logging.info('tc=%f, Final Return: %.2f\n' % (tc, cum_ret)) self.pDiff = daily_ret if __name__ == '__main__': tools.run(cwmr_var())
class eg(expert): """ Exponentiated Gradient (EG) algorithm by Helmbold et al. Reference: Helmbold, David P., et al. "On‐Line Portfolio Selection Using Multiplicative Updates." Mathematical Finance 8.4 (1998): 325-347. http://www.cis.upenn.edu/~mkearns/finread/helmbold98line.pdf """ def __init__(self, eta=0.05, b=None): """ :params eta: Learning rate. Controls volatility of weights. """ super(eg, self).__init__() self.eta = eta self.b = b def get_b(self, data, last_b): T, N = data.shape if self.b is None: self.b = np.ones((N, 1)) / N last_b = self.b # the weight there is not rebalanced! self.b[:, 0] = last_b[:, 0] * np.exp(self.eta * data[T - 1, :].T / (data[T - 1, :].dot(last_b))) self.b = self.b / np.sum(self.b) return self.b if __name__ == "__main__": tools.run(eg())
cumprod_ret = np.ones((n, 1), np.float) daily_ret = np.ones((n, 1), np.float) #daily return b = np.ones((m, 1), np.float) / m # initialize b re_b = np.zeros((m, 1), np.float) # initialize rebalanced b daily_portfolio = np.zeros((n, m)) for t in range(n): if t >= min_period: b = self.get_b(data[:t, :], re_b) # double check (Normalize the constraint) b = b / np.sum(b) daily_portfolio[t, :] = b.reshape((1, m)) daily_ret[t] = np.dot( data[t, :], b) * (1 - tc / 2 * np.sum(np.absolute(b - re_b))) cum_ret *= daily_ret[t] cumprod_ret[t] = cum_ret re_b = b * np.reshape(data[t, :], (1, m)) / daily_ret[t] logging.info('%d\t%f\t%f\n' % (t + 1, daily_ret[t], cumprod_ret[t])) logging.info('tc=%f, Final Return: %.2f\n' % (tc, cum_ret)) self.pDiff = daily_ret if __name__ == '__main__': tools.run(cwmr())
self.exp_ret = np.ones((self.K, self.L)) self.exp_w = np.ones((self.K * self.L, m)) / m for t in range(n): if t >= min_period: b = self.get_b(data[:t, :], re_b) # double check (Normalize the constraint) b = b / np.sum(b) daily_portfolio[t, :] = b.reshape((1, m)) daily_ret[t] = np.dot( data[t, :], b) * (1 - tc / 2 * np.sum(np.absolute(b - re_b))) cum_ret = cum_ret * daily_ret[t] cumprod_ret[t] = cum_ret re_b = b * data[t, :][:, None] / daily_ret[t] for k in np.arange(self.K): for l in np.arange(self.L): self.exp_ret[k, l] *= data[t, :].dot( self.exp_w[(k - 1) * self.L + l, :].T) logging.info('%d\t%f\t%f\n' % (t + 1, daily_ret[t], cumprod_ret[t])) logging.info('tc=%f, Final Return: %.2f\n' % (tc, cum_ret)) if __name__ == "__main__": tools.run(cornk())
from mercurius.strategy.base import expert from mercurius.strategy import tools import numpy as np import logging class ubah(expert): '''Uniform Buy and Hold''' def __init__(self): super(ubah, self).__init__() def get_b(self, data, last_b): return last_b if __name__ == '__main__': tools.run(ubah(), plot=True)
data_close = self.get_close(data) cum_ret = 1 #cumulative return aka total return cumprod_ret = np.ones((n, 1), np.float) daily_ret = np.ones((n, 1), np.float) #daily return b = np.ones((m, 1), np.float) / m # initialize b re_b = np.zeros((m, 1), np.float) # initialize rebalanced b daily_portfolio = np.zeros((n, m)) for t in range(n): b = self.update(data_close, data, t + 1, self.b, self.eps, self.W) daily_portfolio[t, :] = b.reshape((1, m)) daily_ret[t] = np.dot( data[t, :], b) * (1 - tc / 2 * np.sum(np.absolute(b - re_b))) cum_ret *= daily_ret[t] cumprod_ret[t] = cum_ret re_b = b * data[t, :][:, None] / daily_ret[t] logging.info('%d\t%f\t%f\n' % (t + 1, daily_ret[t], cumprod_ret[t])) logging.info('tc=%f, Final Return: %.2f\n' % (tc, cum_ret)) self.pDiff = daily_ret if __name__ == "__main__": tools.run(rmr())
for t in range(n): if t >= min_period: b = self.get_b(data[:t, :], re_b) # double check (Normalize the constraint) b = b / np.sum(b) daily_portfolio[t, :] = b.reshape((1, m)) daily_ret[t] = np.dot( data[t, :], b) * (1 - tc / 2 * np.sum(np.absolute(b - re_b))) cum_ret = cum_ret * daily_ret[t] cumprod_ret[t] = cum_ret re_b = b * data[t, :][:, None] / daily_ret[t] for k in np.arange(1, self.window): self.exp_ret[k - 1, 0] = np.dot(self.exp_ret[k - 1, 0] * data[k, :], self.exp_w[k - 1, :].T) self.exp_ret[:, 0] /= np.sum(self.exp_ret[:, 0]) logging.info('%d\t%f\t%f\n' % (t + 1, daily_ret[t], cumprod_ret[t])) logging.info('tc=%f, Final Return: %.2f\n' % (tc, cum_ret)) self.pDiff = daily_ret if __name__ == "__main__": tools.run(anticor())
from mercurius.strategy.base import expert from mercurius.strategy import tools import numpy as np import logging class ucrp(expert): """uniform constant rebalanced portfolio""" def __init__(self): super(ucrp, self).__init__() def get_b(self, data, last_b): n, m = data.shape return np.ones((m, 1)) / m if __name__ == '__main__': #logging.basicConfig(level=logging.INFO) #data = tools.load_mat('djia') #test = ucrp() #test.trade(data) tools.run(ucrp())
T, N = data.shape if self.b is None: self.b = np.ones(N) / N if T < self.window + 1: data_phi = data[T - 1, :] else: data_phi = np.zeros((1, N)) tmp_x = np.ones((1, N)) for i in range(self.window): data_phi += 1. / tmp_x tmp_x *= data[T - i - 1, :] data_phi *= np.float32(1. / self.window) ell = np.maximum(0, self.eps - data_phi.dot(last_b)) #print data_phi x_bar = np.mean(data, dtype=np.float32) dd = data_phi - x_bar denominator = np.linalg.norm(dd)**2 if denominator != 0: lam = ell / denominator else: lam = 0 self.b = self.b.ravel() + lam * dd self.b = tools.simplex_proj2(self.b.ravel()) self.b = self.b[:, None] return self.b if __name__ == "__main__": tools.run(olmar(), min_period=2)
data[t, :], b) * (1 - tc / 2 * np.sum(np.absolute(b - re_b))) cum_ret *= daily_ret[t] cumprod_ret[t] = cum_ret re_b = b * data[t, :][:, None] / daily_ret[t] logging.info('%d\t%f\t%f\n' % (t + 1, daily_ret[t], cumprod_ret[t])) logging.info('tc=%f, Final Return: %.2f\n' % (tc, cum_ret)) self.pDiff = daily_ret self.last_b = b def opt_weights(X, max_leverage=1): x_0 = max_leverage * np.ones(X.shape[1]) / float(X.shape[1]) objective = lambda b: -np.prod(X.dot(b)) cons = ({'type': 'eq', 'fun': lambda b: max_leverage - np.sum(b)}, ) bnds = [(0., max_leverage)] * len(x_0) res = minimize(objective, x_0, bounds=bnds, constraints=cons, method='slsqp', options={'ftol': 1e-07}) return res.x if __name__ == '__main__': tools.run(bcrp())