def optimize_for_sharpe_ratio(allocation, start_value, df, symbols): symbols = symbols[1:] dr = utils.daily_returns(df) df = df[symbols] # print df corr = np.asarray(utils.get_correlation(dr)) corr = np.asarray([1,-.12,.00209,-.004,-.007,.005]) # print symbols cons = ({'type': 'eq', 'fun': lambda x: 1 - sum(x)}) bnds = tuple((0, 1) for item in allocation) result = op.minimize(__get_sharpe_ratio, allocation, args=(df, symbols, start_value,corr), method='SLSQP', bounds=bnds, constraints=cons) print "Correlation to SPY: ", corr[1:] return np.round(result.x, 2)
def __get_sharpe_ratio(allocation, df, symbol, start_value,corr): dr = utils.daily_returns(df) # corr = np.asarray(utils.get_correlation(dr)) sd = dr.std() dr = dr.mean() var = __variance(len(symbol),allocation,sd,corr) df_normed = df / df.ix[0, :] df_alloced = df_normed * allocation pos_vals = df_alloced * start_value portfolio_value = pos_vals.sum(axis=1) return (np.sum(dr * allocation)/np.sqrt(var)) * -1
def __get_sharpe_ratio(allocation, df, symbol, start_value): df_normed = df / df.ix[0, :] df_alloced = df_normed * allocation pos_vals = df_alloced * start_value # portfolio_value = pos_vals.sum(axis=1) # port_daily_ret = utils.daily_returns(pos_vals) portfolio_daily_return_mean = port_daily_ret.mean() portfolio_standard_deviation = port_daily_ret.std() # plt.scatter(portfolio_daily_return_mean,portfolio_standard_deviation) # plt.show() # print portfolio_daily_return_mean,portfolio_standard_deviation sharpe = (math.sqrt(252) * (portfolio_daily_return_mean / portfolio_standard_deviation)) * -1 print "Allocations: ", np.round(allocation, 2) # print "Portfolio Value: ", portfolio_value.tail(5) print "Sharpe Ratio: ", sharpe * -1 print "symbols: ", symbol return sharpe
import pandas as pd import scipy import utils symbols = ['IBM','AAPL','GLD','XOM'] L = len(symbols) addressable_dates = pd.date_range('2010-02-01', '2010-12-31') df = utils.get_data(symbols, addressable_dates) df = df.dropna() daily_ret = utils.daily_returns(df) daily_ret_mean = scipy.array(daily_ret.mean()) std = utils.std_daily_return(daily_ret) stds = scipy.array(std) print stds print symbols print daily_ret_mean corr = scipy.array(daily_ret.corr()) # cor = scipy.corrcoef(x) # print cor
def main_run(): # h = [.01, .01, .01,.01, .01,.01, .01,.01] # # h = pd.Series([0.0025,0.0025,0.0025,0.0025,0.0025,0.0025,0.0025,0.0025],dtype=float) # # # x = [3., 2., 1.5,2., 1.5,3., 4.5,4.9] # # y = [4.2,1.9,1.9,2.1,2.0 ,2.5,3.9,4.5] # # x = [1.5, 2., 1.5,2., 1.5,3., 4.5,4.9] # y = [4.2,1.9,1.9,2.1,2.0 ,2.5,3.9,4.5] # z = [0.012,0.032,0.035,0.902,0.052,0.302,-0.909,0.902] # # df.corr() # b = [1., -1., -1.,1., 1.,-1., 1,-1] # p = [0.12,0.55,0.45,0.3,0.53,0.57,0.19,0.58] start_value = 1000000 # symbols = ['AC','ALI','BDO','BPI','DMC','GLO', # 'GTCAP','HCP','JFC','MBT','MPI','MEG', # 'RLC','SECB','SM','SMPH','TEL','URC'] # symbols = ['AAPL','IBM','XOM','GLD'] # symbols = ['goog','aapl','msft','amzn'] symbols = ['AAPL', 'MSFT','ORCL','QCOM','BBY','MU','GILD','YUM','NFLX','VZ','APA','RRC','MDLZ','CSCO','V','MET','SBUX','GGP','UA','GM'] h = np.ones(len(symbols)) addressable_dates = pd.date_range('2012-01-01','2015-12-31') df = utils.get_data_online(symbols, addressable_dates) df = pd.DataFrame(df,index=df.index,dtype=np.float64) df = df.dropna() x = np.asarray(utils.daily_returns(df[symbols[1:]]).std()) # print x y = np.asarray(utils.daily_returns(df[symbols[1:]]).mean()) # print y # b = [1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.] z = np.asarray(utils.get_correlation(df)[1:]) # print z # p = [.5,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5,.5] b = np.ones(len(symbols) - 1) # print b p = Accuracy.get_accuracy(symbols,addressable_dates) # print p sharpe_ratios = utils.get_sharpe_ratio(utils.daily_returns(df[symbols[1:]])) # print sharpe_ratios data = (x,y,z,b,p) x_sorted = np.sort(x) y_sorted = np.sort(y) # print "h",np.transpose( h) * y # print "cost", error(h) # cons = ({'type':'eq', 'fun': lambda x: 1 - sum(x)}) cons = ({'type': 'eq', 'fun': lambda x: 1 - sum(x)}) # bounds = tuple((0,1) for it in h) bnds = tuple((0,1) for it in h) bounds = bnds # bounds = (0,1) min_result = spo.minimize(error,h,args=(data,), method='SLSQP',bounds=bounds, constraints=cons, options={'disp':True}) print "Parameters = {}, Y = {}".format(np.round(min_result.x,2), np.abs( min_result.fun)) # for tracing # print "xdata",xdata model_bounds = max(x.max(),y.max()) xdata = np.linspace(0,5,8) y_main = func(xdata,model_bounds,1,-model_bounds) print "bias", b * np.round(min_result.x,3) print "risk: ", x print "rewards: ", y print "correlation: ", z print "accuracy: ", p print "y main",y_main plt.plot(xdata,y_main) y = func(xdata,2.5,1.3,0.5) ydata = y + 0.2 * np.random.normal(size=len(xdata)) coeffs, pcov = curve_fit(func,xdata,ydata) yaj = func(xdata, coeffs[0], coeffs[1], coeffs[2]) print pcov # plt.scatter(xdata,ydata) # plt.plot(xdata,yaj) # c,p = curve_fit(sigmoid,x_sorted,y_sorted) plt.scatter(x_sorted,y_sorted) plt.show() return None