op = df.iloc[:, (earnann.shape[1]):((earnann.shape[1]) + op.shape[1])] cl = df.iloc[:, ((earnann.shape[1]) + op.shape[1]):] op.columns = stocks.iloc[0, :] cl.columns = stocks.iloc[0, :] lookback = 90 retC2O = (op - cl.shift()) / cl.shift() stdC2O = retC2O.rolling(lookback).std() positions = np.zeros(cl.shape) longs = (retC2O >= 0.5 * stdC2O) & earnann shorts = (retC2O <= -0.5 * stdC2O) & earnann positions[longs] = 1 positions[shorts] = -1 ret = np.sum(positions * (cl - op) / op, axis=1) / 30 cumret = (np.cumprod(1 + ret) - 1) cumret.plot() print('APR=%f Sharpe=%f' % (np.prod(1 + ret)**(252 / len(ret)) - 1, np.sqrt(252) * np.mean(ret) / np.std(ret))) from calculateMaxDD import calculateMaxDD maxDD, maxDDD, i = calculateMaxDD(cumret.fillna(0)) print('Max DD=%f Max DDD in days=%i' % (maxDD, maxDDD)) #APR=0.068126 Sharpe=1.494743 #Max DD=-0.026052 Max DDD in days=109
# -*- coding: utf-8 -*- """ Created on Fri Sep 21 19:48:44 2018 @author: Ernest """ import numpy as np from calculateMaxDD import calculateMaxDD cumret = np.array([10, 9, 8, 7, 11, 9, 7, 5, 5, 12]) maxDD, maxDDD, i = calculateMaxDD(cumret) assert (maxDD == -0.5) assert (maxDDD == 4) assert (i == 7)
minusG = lambda f: -g(f, df) minusGsim = lambda f: -g(f, ret_sim) #optimal leverage based on simulated returns res = minimize(minusGsim, 0, method='Nelder-Mead') optimalF = res.x print('Optimal leverage=%f optimal growth rate=%f' % (optimalF, -res.fun)) #Optimal leverage=25.512625 optimal growth rate=0.005767 minR = np.min(ret_sim) print('minR=%f' % (minR)) #minR=-0.018201 # max drawdown with optimal leverage from calculateMaxDD import calculateMaxDD maxDD, maxDDD, i = calculateMaxDD((np.cumproduct(1 + optimalF * ret_sim) - 1)) print('Max DD=%f with optimal leverage=%f' % (maxDD, optimalF)) #Max DD=-0.996312 with optimal leverage=25.512625 #max drawdown with half of optimal leverage maxDD, maxDDD, i = calculateMaxDD( (np.cumproduct(1 + optimalF / 2 * ret_sim) - 1)) print('Max DD=%f with half optimal leverage=%f' % (maxDD, optimalF / 2)) #Max DD=-0.900276 with half optimal leverage=12.756313 # max drawdown with 1/7 of optimal leverage maxDD, maxDDD, i = calculateMaxDD( (np.cumproduct(1 + optimalF / 7 * ret_sim) - 1)) print('Max DD=%f with half optimal leverage=%f' % (maxDD, optimalF / 7)) #Max DD=-0.429629 with half optimal leverage=3.644661