def plot_decomposition(timeSeries): trend, seasonal, residual = tsa.seasonal_decompose(timeSeries) gl.set_subplots(4, 1) gl.plot([], timeSeries, labels=["", "time", "Original"], legend=['Original'], loc="best") gl.plot([], trend, labels=["", "time", "trend"], legend=['trend'], loc="best") gl.plot([], seasonal, labels=["", "time", "seasonal"], legend=['seasonal'], loc="best") gl.plot([], residual, labels=["", "time", "residual"], legend=['residual'], loc="best")
def IFE_b(self, year_start=1996, year_finish=2016, window=10): ## Question b of the asqued thing all_returns = [] all_covMatrices = [] all_dates = [] # To store the dates of the estimation for year_test in range(year_start, year_finish - window + 1): # +1 !! # Set the dates self.pf.set_interval(dt.datetime(year_test, 1, 1), dt.datetime(year_test + window, 1, 1)) ret = self.yearly_Return(self.get_MeanReturns()) covMat = self.yearly_covMatrix(self.get_covMatrix()) all_covMatrices.append(covMat) all_returns.append(ret) # Get the dates from any of the symbols of the portfolio dates = self.get_dates() all_dates.append(dates[-1]) ## Plotting the returns all_returns = np.array(all_returns) # gl.plot(all_dates, all_returns[:,0], # labels = ["Returns", "Time", "Return"], # legend = [self.pf.symbols.keys()[0]]) # # gl.plot(all_dates, all_returns[:,1], # legend = [self.pf.symbols.keys()[1]], nf = 0, na = 0) ## 1) Plot the returns of all of them together for the eleven windows gl.plot(all_dates, all_returns, labels=[ "Average Return in 10 years", "Time (years)", "Anual return of Assets" ], legend=self.symbol_names) gl.savefig(folder_images + 'returnsAveAll.png', dpi=150, sizeInches=[2 * 8, 1.5 * 6]) ## 2) Plot the covariance matrix for 9 years gl.set_subplots(2, 3) for i in range(6): gl.bar_3D(self.symbol_names, self.symbol_names, all_covMatrices[i], labels=[str(year_start + window + i), "", ""], fontsize=30, fontsizeA=19) gl.savefig(folder_images + 'covsAveAll.png', dpi=80, sizeInches=[4 * 8, 3 * 6])
def plot_acf_pacf(timeSeries, nlags=40, alpha=0.05, method_acf=True, method_pacf='ywunbiased', legend=["ACF", "PACF"], labels=["timeSeries"]): valuesACF, confIntACF = tsa.acf(timeSeries, nlags=30, alpha=0.05, unbiased=True, qstat=False) # qstat: For LJung-Box values and pvalues: For Pvalues of this ## For some reason the first value of the PACF is 1, when it should not be defined valuesPACF, confIntPACF = tsa.pacf(timeSeries, nlags=30, alpha=0.05, method='ywunbiased') gl.set_subplots(2, 1) gl.stem([], valuesACF, labels=[labels[0], "lag", "ACF"], legend=[legend[0]]) # gl.plot([],confIntACF, nf = 0, color = "blue", # legend = ["ConfInt %.2f" % (1 - alpha)], # lw = 1) plt.axhline(y=-1.96 / np.sqrt(len(timeSeries)), linestyle='--', color='gray', lw=3) plt.axhline(y=1.96 / np.sqrt(len(timeSeries)), linestyle='--', color='gray', lw=3) gl.stem([], valuesPACF, labels=[labels[0], "lag", "PACF"], legend=[legend[1]]) # gl.plot([],confIntPACF, nf = 0, color = "blue", # legend = ["ConfInt %.2f" % (1 - alpha)]) plt.axhline(y=-1.96 / np.sqrt(len(timeSeries)), linestyle='--', color='gray', lw=3) plt.axhline(y=1.96 / np.sqrt(len(timeSeries)), linestyle='--', color='gray', lw=3)
def IFE_a(self, year_start=1996, year_finish=2016, window=10): ## Basic, just look at the bloody graphs self.pf.set_interval(dt.datetime(year_start, 1, 1), dt.datetime(year_finish, 1, 1)) dates = self.get_dates() prices = self.pf.get_timeSeries(self.period) returns = self.get_Returns() # print returns.shape gl.plot( dates, prices, labels=["Monthly price of Symbols", "Time (years)", "Price (dolar)"], legend=self.pf.symbols.keys(), loc=2) gl.savefig(folder_images + 'pricesAll.png', dpi=150, sizeInches=[2 * 8, 1.5 * 6]) gl.plot( dates, returns, labels=["Monthly return of the Symbols", "Time (years)", "Return (%)"], legend=self.pf.symbols.keys()) gl.savefig(folder_images + 'returnsAll.png', dpi=150, sizeInches=[2 * 8, 1.5 * 6]) ## Distribution obtaining gl.set_subplots(2, 2) for i in range(4): gl.histogram(returns[:, i], labels=[self.symbol_names[i]]) gl.savefig(folder_images + 'returnDistribution.png', dpi=150, sizeInches=[2 * 8, 1.5 * 6]) ############## Posible Transformations ################## ws = [3, 4, 6, 8] gl.set_subplots(2, 2) for w in ws: means, ranges = bMl.get_meanRange(prices[:, 1], w) gl.scatter(means, ranges, lw=4, labels=["", "mean", "range"], legend=["w = %i" % (w)]) gl.savefig(folder_images + 'rangeMean.png', dpi=150, sizeInches=[2 * 8, 1.5 * 6])
def IFE_b(self,year_start = 1996, year_finish = 2016, window = 10): ## Question b of the asqued thing all_returns = [] all_covMatrices = [] all_dates = [] # To store the dates of the estimation for year_test in range(year_start,year_finish - window + 1): # +1 !! # Set the dates self.pf.set_interval(dt.datetime(year_test,1,1),dt.datetime(year_test + window,1,1)) ret = self.yearly_Return(self.get_MeanReturns()) covMat = self.yearly_covMatrix(self.get_covMatrix()) all_covMatrices.append(covMat) all_returns.append(ret) # Get the dates from any of the symbols of the portfolio dates = self.get_dates() all_dates.append(dates[-1]) ## Plotting the returns all_returns = np.array(all_returns) # gl.plot(all_dates, all_returns[:,0], # labels = ["Returns", "Time", "Return"], # legend = [self.pf.symbols.keys()[0]]) # # gl.plot(all_dates, all_returns[:,1], # legend = [self.pf.symbols.keys()[1]], nf = 0, na = 0) ## 1) Plot the returns of all of them together for the eleven windows gl.plot(all_dates, all_returns, labels = ["Average Return in 10 years", "Time (years)", "Anual return of Assets"], legend = self.symbol_names) gl.savefig(folder_images +'returnsAveAll.png', dpi = 150, sizeInches = [2*8, 1.5*6]) ## 2) Plot the covariance matrix for 9 years gl.set_subplots(2,3) for i in range(6): gl.bar_3D(self.symbol_names, self.symbol_names, all_covMatrices[i], labels = [str(year_start +window+i),"",""], fontsize = 30, fontsizeA = 19) gl.savefig(folder_images +'covsAveAll.png', dpi = 80, sizeInches = [4*8, 3*6])
def IFE_a(self, year_start = 1996, year_finish = 2016, window = 10): ## Basic, just look at the bloody graphs self.pf.set_interval(dt.datetime(year_start,1,1),dt.datetime(year_finish,1,1)) dates = self.get_dates() prices = self.pf.get_timeSeries(self.period) returns = self.get_Returns() # print returns.shape gl.plot(dates, prices, labels = ["Monthly price of Symbols", "Time (years)", "Price (dolar)"], legend = self.pf.symbols.keys(), loc = 2) gl.savefig(folder_images +'pricesAll.png', dpi = 150, sizeInches = [2*8, 1.5*6]) gl.plot(dates, returns, labels = ["Monthly return of the Symbols", "Time (years)", "Return (%)"], legend = self.pf.symbols.keys()) gl.savefig(folder_images +'returnsAll.png', dpi = 150, sizeInches = [2*8, 1.5*6]) ## Distribution obtaining gl.set_subplots(2,2) for i in range(4): gl.histogram(returns[:,i], labels = [self.symbol_names[i]]) gl.savefig(folder_images +'returnDistribution.png', dpi = 150, sizeInches = [2*8, 1.5*6]) ############## Posible Transformations ################## ws = [3, 4, 6, 8] gl.set_subplots(2,2) for w in ws: means, ranges = bMl.get_meanRange(prices[:,1], w) gl.scatter(means, ranges, lw = 4, labels = ["", "mean","range"], legend = ["w = %i" %(w)]) gl.savefig(folder_images +'rangeMean.png', dpi = 150, sizeInches = [2*8, 1.5*6])
def plot_acf_pacf(timeSeries, nlags = 40, alpha = 0.05, method_acf = True, method_pacf = 'ywunbiased', legend = ["ACF", "PACF"], labels = ["timeSeries"]): valuesACF, confIntACF = tsa.acf(timeSeries, nlags = 30, alpha = 0.05, unbiased = True, qstat = False) # qstat: For LJung-Box values and pvalues: For Pvalues of this ## For some reason the first value of the PACF is 1, when it should not be defined valuesPACF, confIntPACF = tsa.pacf(timeSeries, nlags = 30, alpha = 0.05, method = 'ywunbiased') gl.set_subplots(2,1) gl.stem([],valuesACF, labels = [labels[0], "lag", "ACF"], legend = [legend[0]]) # gl.plot([],confIntACF, nf = 0, color = "blue", # legend = ["ConfInt %.2f" % (1 - alpha)], # lw = 1) plt.axhline(y=-1.96/np.sqrt(len(timeSeries)), linestyle='--',color='gray', lw = 3) plt.axhline(y=1.96/np.sqrt(len(timeSeries)), linestyle='--',color='gray', lw = 3) gl.stem([],valuesPACF, labels = [labels[0], "lag", "PACF"], legend = [legend[1]]) # gl.plot([],confIntPACF, nf = 0, color = "blue", # legend = ["ConfInt %.2f" % (1 - alpha)]) plt.axhline(y=-1.96/np.sqrt(len(timeSeries)), linestyle='--',color='gray', lw = 3) plt.axhline(y=1.96/np.sqrt(len(timeSeries)), linestyle='--',color='gray', lw = 3)
def plot_decomposition(timeSeries): trend, seasonal, residual = tsa.seasonal_decompose(timeSeries) gl.set_subplots(4,1) gl.plot([], timeSeries, labels = ["", "time", "Original"], legend = ['Original'], loc = "best") gl.plot([], trend, labels = ["", "time", "trend"], legend = ['trend'], loc = "best") gl.plot([], seasonal, labels = ["", "time", "seasonal"], legend = ['seasonal'], loc = "best") gl.plot([], residual, labels = ["", "time", "residual"], legend = ['residual'], loc = "best")
def plot_multiple_iterations(Xs, mus, covs, Ks, myDManager, logl, theta_list, model_theta_list, folder_images): ######## Plot the original data ##### gl.init_figure() gl.set_subplots(2, 3) Ngraph = 6 colors = ["r", "b", "g"] K_G, K_W, K_vMF = Ks for i in range(Ngraph): indx = int(i * ((len(theta_list) - 1) / float(Ngraph - 1))) nf = 1 for xi in range(len(Xs)): ## First cluster labels = [ 'EM Evolution. Kg:' + str(K_G) + ', Kw:' + str(K_W) + ', K_vMF:' + str(K_vMF), "X1", "X2" ] ax1 = gl.scatter(Xs[xi][0, :], Xs[xi][1, :], labels=["", "", ""], color=colors[xi], alpha=0.2, nf=nf) nf = 0 mean, w, h, theta = bMA.get_gaussian_ellipse_params(mu=mus[xi], Sigma=covs[xi], Chi2val=2.4477) r_ellipse = bMA.get_ellipse_points(mean, w, h, theta) gl.plot(r_ellipse[:, 0], r_ellipse[:, 1], ax=ax1, ls="--", lw=2, AxesStyle="Normal2", color=colors[xi], alpha=0.7) # Only doable if the clusters dont die for k_c in myDManager.clusterk_to_Dname.keys(): k = myDManager.clusterk_to_thetak[k_c] distribution_name = myDManager.clusterk_to_Dname[k_c] # G W if (distribution_name == "Gaussian"): ## Plot the ecolution of the mu #### Plot the Covariance of the clusters ! mean, w, h, theta = bMA.get_gaussian_ellipse_params( mu=theta_list[indx][k][0], Sigma=theta_list[indx][k][1], Chi2val=2.4477) r_ellipse = bMA.get_ellipse_points(mean, w, h, theta) gl.plot(r_ellipse[:, 0], r_ellipse[:, 1], ax=ax1, ls="-.", lw=3, AxesStyle="Normal2", legend=[ "Kg(%i). pi:%0.2f" % (k, float(model_theta_list[indx][0][0, k])) ]) elif (distribution_name == "Watson"): #### Plot the pdf of the distributino ! ## Distribution parameters for Watson kappa = float(theta_list[indx][k][1]) mu = theta_list[indx][k][0] Nsa = 1000 # Draw 2D samples as transformation of the angle Xalpha = np.linspace(0, 2 * np.pi, Nsa) Xgrid = np.array([np.cos(Xalpha), np.sin(Xalpha)]) probs = [] # Vector with probabilities for i in range(Nsa): probs.append( np.exp(Wad.Watson_pdf_log(Xgrid[:, i], [mu, kappa]))) probs = np.array(probs) # Plot it in polar coordinates X1_w = (1 + probs) * np.cos(Xalpha) X2_w = (1 + probs) * np.sin(Xalpha) gl.plot(X1_w, X2_w, alpha=1, lw=3, ls="-.", legend=[ "Kw(%i). pi:%0.2f" % (k, float(model_theta_list[indx][0][0, k])) ]) elif (distribution_name == "vonMisesFisher"): #### Plot the pdf of the distributino ! ## Distribution parameters for Watson kappa = float(theta_list[indx][k][1]) mu = theta_list[indx][k][0] Nsa = 1000 # Draw 2D samples as transformation of the angle Xalpha = np.linspace(0, 2 * np.pi, Nsa) Xgrid = np.array([np.cos(Xalpha), np.sin(Xalpha)]) probs = [] # Vector with probabilities for i in range(Nsa): probs.append( np.exp( vMFd.vonMisesFisher_pdf_log( Xgrid[:, i], [mu, kappa]))) probs = np.array(probs) probs = probs.reshape((probs.size, 1)).T # Plot it in polar coordinates X1_w = (1 + probs) * np.cos(Xalpha) X2_w = (1 + probs) * np.sin(Xalpha) # print X1_w.shape, X2_w.shape gl.plot(X1_w, X2_w, alpha=1, lw=3, ls="-.", legend=[ "Kvmf(%i). pi:%0.2f" % (k, float(model_theta_list[indx][0][0, k])) ]) ax1.axis('equal') gl.subplots_adjust(left=.09, bottom=.10, right=.90, top=.95, wspace=.2, hspace=0.01) gl.savefig(folder_images + 'Final_State2. K_G:' + str(K_G) + ', K_W:' + str(K_W) + '.png', dpi=100, sizeInches=[18, 8])
def IFE_e(self, ObjectiveR=0.003, Rf=0.0, year_start=1996, year_finish=2016, window=10): # Just, choose a desired return, # Using training Samples calculate using the market line # the optimal porfolio for that. # Then, using also the last year ( test), recalculate the portfolio needed # for that return, and the difference between is the turnover self.set_Rf(Rf) nf_flag = 1 desired_Portfolios = [] all_dates = [] for year_test in range(year_start, year_finish - window + 1): # +1 !! # Set the dates self.pf.set_interval(dt.datetime(year_test, 1, 1), dt.datetime(year_test + window, 1, 1)) # Obtain the market line !! w = self.TangentPortfolio(Rf=Rf) # Obtain allocation # Obtain the expected return and std when using all our money ! self.set_allocation(w) expRet, stdRet = self.get_metrics(investRf="no") param = bMl.obtain_equation_line(Rf, expRet, stdRet) bias, slope = param # Once we have the equation of the line, we obtain how much money # we need to use to reach the desired Expecred Return. # Rt = (1 - X)Rf + XRp with X = sum(w) # For a desired Rt we solve the X X = (ObjectiveR - Rf) / (expRet - Rf) # print X # So the desired porfolio is: wdesired = w * X desired_Portfolios.append(wdesired) gl.plot([0, 1.3 * abs(X * stdRet)], [bias, bias + 1.3 * abs(slope * stdRet * X)], labels=["Desired Portfolios", "Risk (std)", "Return (%)"], legend=["%s, X: %0.3f" % ((year_test + window), X[0])], nf=nf_flag, loc=2) nf_flag = 0 gl.scatter([abs(X * stdRet)], [ObjectiveR], nf=0) dates = self.get_dates() all_dates.append(dates[-1]) # print wdesired gl.savefig(folder_images + 'desiredPortfolios.png', dpi=150, sizeInches=[2 * 8, 2 * 6]) # Now we calculate the turnovers Turnovers = [] prev_abs_alloc = [] # Previous, absolute allocation percentaje_changed = [] Nport = len(desired_Portfolios) for i in range(Nport - 1): to = bMl.get_TurnOver(desired_Portfolios[i], desired_Portfolios[i + 1]) Turnovers.append(to) prev_abs_alloc.append(np.sum(np.abs(desired_Portfolios[i]))) percentaje_changed.append(Turnovers[-1] / prev_abs_alloc[-1]) print Turnovers gl.set_subplots(1, 3) gl.bar(all_dates[1:], Turnovers, color="g", labels=["Portfolio turnovers", "Year", "Value"]) gl.add_text([all_dates[1:][3], max(Turnovers) * 0.80], "Mean: %0.2f" % np.mean(Turnovers), 30) gl.bar(all_dates[0:-1], prev_abs_alloc, color="r", labels=["Absolute allocations", "Year", "Value"]) gl.bar(all_dates[1:], percentaje_changed, color="b", labels=["Percentage turnover", "Year", "Value"]) gl.add_text( [all_dates[1:][3], max(percentaje_changed) * 0.80], "Mean: %0.2f" % np.mean(percentaje_changed), 30) gl.savefig(folder_images + 'turnovers.png', dpi=150, sizeInches=[2 * 8, 1 * 6])
def yieldPriceStudy(self, initial_price = 80): # The initial price is for the aproximation of the # funciton with a cuadratic equation in one point. #### Obtain the yield-price curve from the structure Np = 100 ytm_list = np.linspace(0.001, 0.40, Np) prices = [] mdurations = [] convexities = [] for ytm in ytm_list: price = self.get_price(ytm = ytm) mduration = self.get_mduration(price = price) convexity = self.get_convexity(price = price) prices.append(self.get_price(ytm = ytm)) mdurations.append(mduration) convexities.append(convexity) gl.set_subplots(2,2) gl.plot(ytm_list,prices, labels = ["Yield curve", "Yield to maturity" ,"Price of Bond"], legend = ["Yield curve"], loc = 3) gl.plot(ytm_list,prices, labels = ["Duration and Yield", "Yield to maturity" ,"Price of Bond"], legend = ["Yield curve"], loc = 3) gl.plot(ytm_list,mdurations, na = 1, nf = 0, legend = ["Duration"], loc = 1) gl.plot(ytm_list,prices, labels = ["Convexity and Yield","Yield to maturity" ,"Price of Bond"], legend = ["Yield curve"], loc = 3) gl.plot(ytm_list,convexities, na = 1, nf = 0, legend = ["Convexity"], loc = 1) ### Estimation of the yield courve around a point using the ## Duration and convexity. price = initial_price ytm = self.get_ytm(price) dytmList = np.linspace(-0.10, 0.10, 100) ## Obtain estimations estimations = [] for dytm in dytmList: eprice = self.estimate_price_DC(price = price, dytm = dytm, dy = 0.01) estimations.append(eprice) ## Obtain real values rael_values = [] for dytm in dytmList: rprice = self.get_price(ytm = ytm + dytm) rael_values.append(rprice) # Calculate the error ! rael_values = ul.fnp(rael_values) estimations = ul.fnp(estimations) error = np.abs(np.power(rael_values - estimations, 1)) gl.plot(ytm_list,prices, labels = ["Convexity and Yield","Yield to maturity" ,"Price of Bond"], legend = ["Yield curve"], loc = 3, lw = 4, color = "r") gl.scatter([ytm],[price], nf = 0, legend = ["Initial price"], loc = 3, lw = 4, color = "g") gl.plot(dytmList + ytm,estimations, nf = 0, legend = ["Estimation"], loc = 3, lw = 2, color = "b") gl.plot(dytmList + ytm,error, nf = 0, na = 1, legend = ["Error"], loc = 1, lw = 2, color = "b") ## The limit is the Spot Rate !! When we can do it continuously ## In this case the return is e^(RT)
symbolID = "EURUSD" Lslow, Lfast = 30, 5 myEstrategia.set_slowMA(symbolID, period1, L=Lslow, MAtype="EMA") myEstrategia.set_fastMA(symbolID, period1, L=Lfast, MAtype="EMA") crosses, dates = myEstrategia.get_TradeSignals() ########## Signals simulation #################### EMAslow = Cartera.EMA(symbolIDs=[symbolID], period=period1, n=Lslow)[0] EMAfast = Cartera.EMA(symbolIDs=[symbolID], period=period1, n=Lfast)[0] price = Cartera.get_timeData(symbolID, period1).get_timeSeries() dataHLOC = Cartera.get_timeData(symbolID, period1).get_timeSeries( ["High", "Low", "Open", "Close"]) dates = Cartera.get_timeData(symbolID, period1).get_dates() ########## Plotting ! #################### gl.set_subplots(2, 1) ax1 = gl.plot(dates, price, legend=["Price"], labels=["Crossing MA Strategy", "", "Price"], nf=1) gl.plot(dates, EMAslow, legend=["Slow"], lw=3) gl.plot(dates, EMAfast, legend=["fast"]) ax2 = gl.plot(dates, ul.scale(EMAfast - EMAslow), legend=["Difference"], nf=1, sharex=ax1, labels=["", "", "Events"], fill=1,
X = np.array(range(0, 100)) Y = np.sin(1.5 * (2 * np.pi / X.size) * X) X2 = np.array(range(0, 50)) Y2 = (-15 + np.array(range(0, 50))) / 25.0 gl.close("all") type_graph = 2 folder_images = "../pics/gl/" dpi = 100 sizeInches = [2 * 8, 2 * 3] # Subplot Type 1 if (type_graph == 1): gl.set_subplots(nr=1, nc=2) gl.plot(X, Y, nf=1, color="k", lw=5, alpha=0.7, labels=["Sine chart", "Time (s)", "Voltage(V)"], legend=["Rolling measurement"]) gl.stem(X2, Y2, nf=1, color="k", lw=2, alpha=0.7,
cov = bMA.get_covMatrix(data) ############################################################ ################# PLOT DATA ############################### ############################################################ import numpy as np import scipy.stats as stats from matplotlib import pyplot as plt cdf = stats.norm.cdf data = ret1 if (qq_plot): # Get the histogram and gaussian estimations ! ## Scatter plot of the points gl.set_subplots(1, 2) x_grid_emp, y_val_emp = bMA.empirical_1D_cdf(ret1) x_grid = np.linspace(x_grid_emp[0], x_grid_emp[-1], 100) x_grid, y_val = bMA.gaussian1D_points_cdf(X=ret1, x_grid=x_grid) ax1 = gl.plot(X=x_grid, Y=y_val, AxesStyle="Normal", nf=1, color="k", alpha=0.5) gl.scatter(x_grid_emp, y_val_emp,
## Thus investing in everything proportionally to their capital. ## Then we have alpha = 0 and beta = 1 # CAPMillo.test_symbol_ab(symbols[2]) CAPMillo.test_Jensens_Alpha() # Do it again with an optimal portolio w = CAPMillo.TangentPortfolio(Rf = 0.0) CAPMillo.set_allocation(w) CAPMillo.test_Jensens_Alpha() print "Market Timing " print CAPMillo.get_portfolio_ab() if (efficient_frontiers == 1): gl.set_subplots(2,2) Nalloc = 10000 #1 alloc = CAPMillo.get_random_allocations(Nalloc, short = "yes", mode = "gaussian") CAPMillo.scatter_allocations(alloc, alpha = 0.8, legend = ["Normal alloc"]) optimal, portfolios = CAPMillo.efficient_frontier(kind = "Tangent", max_exp = 100.0) CAPMillo.plot_allocations(portfolios, legend = ["Normal Eff"], nf = 0) CAPMillo.scatter_allocations(np.eye(CAPMillo.Nsym), legend = ["Assets"], nf = 0, alpha = 1.0, lw = 5) #2 alloc = CAPMillo.get_random_allocations(Nalloc, short = "Lintner", mode = "gaussian") CAPMillo.scatter_allocations(alloc, alpha = 0.8,nf = 1, legend = ["Lintner alloc"]) optimal, portfolios = CAPMillo.efficient_frontier(kind = "Lintner") CAPMillo.plot_allocations(portfolios, legend = ["Lintner Eff"], nf = 0) CAPMillo.scatter_allocations(np.eye(CAPMillo.Nsym),
X = np.array(range(0,100)) Y = np.sin(1.5*(2*np.pi/X.size)* X) X2 = np.array(range(0,50)) Y2 = (-15 + np.array(range(0,50)))/25.0 gl.close("all") type_graph = 2 folder_images = "../pics/gl/" dpi = 100 sizeInches = [2*8, 2*3] # Subplot Type 1 if (type_graph == 1): gl.set_subplots(nr = 1, nc = 2) gl.plot(X,Y, nf = 1, color = "k", lw = 5, alpha = 0.7, labels = ["Sine chart","Time (s)", "Voltage(V)"], legend = ["Rolling measurement"]) gl.stem(X2,Y2, nf = 1, color = "k", lw = 2, alpha = 0.7, labels = ["Discrete window","Sample (k)", "Amplitud"], legend = ["Window values"]) gl.savefig(folder_images +'subplot1.png', dpi = dpi, sizeInches = sizeInches) # Subplot Type 2 if (type_graph == 2): ax1 = gl.subplot2grid((1,4), (0,0), rowspan=1, colspan=3)
edate = dt.datetime.strptime(edate_str, "%d-%m-%Y") mySymbol.set_interval(sdate,edate) # Set the interval period to be analysed #### Filling of data !!! #mySymbol.fill_data() # Set the timeSeries to operate with. mySymbol.set_seriesNames(["Close"]) ############################################################ ###### NOW WE OPERATE DIRECTLY ON THE TIMEDATAs ############ ############################################################ periods = mySymbol.get_periods() gl.set_subplots(4,1, sharex = True) # TODO: Be able to automatize the shareX thing for period in periods: myTimeData = mySymbol.get_timeDataObject(period) price = myTimeData.get_timeSeries(["Close"]) volume = myTimeData.get_timeSeries(["Volume"]) dates = myTimeData.get_dates() gl.plot(dates, price, labels = ["", "", mySymbol.symbol], legend = [str(period)]) gl.stem(dates, volume, legend = [str(period)], na = 1, nf = 0) gl.subplots_adjust(left=.09, bottom=.10, right=.90, top=.95, wspace=.20, hspace=0)
def yieldPriceStudy(self, initial_price=80): # The initial price is for the aproximation of the # funciton with a cuadratic equation in one point. #### Obtain the yield-price curve from the structure Np = 100 ytm_list = np.linspace(0.001, 0.40, Np) prices = [] mdurations = [] convexities = [] for ytm in ytm_list: price = self.get_price(ytm=ytm) mduration = self.get_mduration(price=price) convexity = self.get_convexity(price=price) prices.append(self.get_price(ytm=ytm)) mdurations.append(mduration) convexities.append(convexity) gl.set_subplots(2, 2) gl.plot(ytm_list, prices, labels=["Yield curve", "Yield to maturity", "Price of Bond"], legend=["Yield curve"], loc=3) gl.plot( ytm_list, prices, labels=["Duration and Yield", "Yield to maturity", "Price of Bond"], legend=["Yield curve"], loc=3) gl.plot(ytm_list, mdurations, na=1, nf=0, legend=["Duration"], loc=1) gl.plot( ytm_list, prices, labels=["Convexity and Yield", "Yield to maturity", "Price of Bond"], legend=["Yield curve"], loc=3) gl.plot(ytm_list, convexities, na=1, nf=0, legend=["Convexity"], loc=1) ### Estimation of the yield courve around a point using the ## Duration and convexity. price = initial_price ytm = self.get_ytm(price) dytmList = np.linspace(-0.10, 0.10, 100) ## Obtain estimations estimations = [] for dytm in dytmList: eprice = self.estimate_price_DC(price=price, dytm=dytm, dy=0.01) estimations.append(eprice) ## Obtain real values rael_values = [] for dytm in dytmList: rprice = self.get_price(ytm=ytm + dytm) rael_values.append(rprice) # Calculate the error ! rael_values = ul.fnp(rael_values) estimations = ul.fnp(estimations) error = np.abs(np.power(rael_values - estimations, 1)) gl.plot( ytm_list, prices, labels=["Convexity and Yield", "Yield to maturity", "Price of Bond"], legend=["Yield curve"], loc=3, lw=4, color="r") gl.scatter([ytm], [price], nf=0, legend=["Initial price"], loc=3, lw=4, color="g") gl.plot(dytmList + ytm, estimations, nf=0, legend=["Estimation"], loc=3, lw=2, color="b") gl.plot(dytmList + ytm, error, nf=0, na=1, legend=["Error"], loc=1, lw=2, color="b")
# Set the timeSeries to operate with. mySymbol.set_seriesNames(["Close"]) ############################################################ ###### NOW WE OPERATE DIRECTLY ON THE TIMEDATAs ############ ############################################################ periods = mySymbol.get_periods() periods = sorted(periods,reverse = True) opentime, closetime = mySymbol.get_timeData(periods[1]).guess_openMarketTime() dataTransform = ["intraday", opentime, closetime] folder_images = "../pics/gl/" gl.set_subplots(4,1) # TODO: Align the transformation of the daily prices to axeshare = None for i in range(len(periods)): period = periods[i] myTimeData = mySymbol.get_timeData(period) AxesStyle = " - No xaxis" if (i == len(periods) -1): AxesStyle = "" if (i == 0): title = "Bar Chart. " + str(symbolID) + r" . Price ($\$$)" else: title = "" ylabel = ul5.period_dic[myTimeData.period]
price = timeData.get_timeSeries(["RangeHL","RangeCO"]); price = timeData.get_timeSeries(["magicDelta"]); returns = timeData.get_timeSeriesReturn(["Close","Average"]) cumReturns = timeData.get_timeSeriesCumReturn() SortinoRatio = timeData.get_SortinoR() get_SharpR = timeData.get_SharpR() ################# BASIC PLOTTING MIXTURES ############################ if (basic_plotting): """ We aim to plot the price, volume, return and cummulative return for the selected security in the selected time frame. """ gl.set_subplots(4,1) ############# 1: Basic Time Series and Volume seriesNames = ["Average", "High"] dataHLOC = timeData.get_timeSeries(["High","Low","Open","Close"]) prices = timeData.get_timeSeries(seriesNames); dates = timeData.get_dates() volume = timeData.get_timeSeries(["Volume"]); Returns = timeData.get_timeSeriesReturn(seriesNames = ["Close"]); CumReturns = timeData.get_timeSeriesCumReturn(seriesNames = ["Close"]); nSMA = 10 SMA = timeData.SMA(n = nSMA) ax1 = gl.plot(dates, SMA, labels = [timeData.symbolID + str(timeData.period), "Time", "Price"], legend = ["SMA(%i)" % nSMA], nf = 1, dataTransform = dataTransform, AxesStyle = "Normal - No xaxis", color = "cobalt blue") gl.barchart(dates, dataHLOC, lw = 2, dataTransform = dataTransform, color = "k",
###### WE CAN OPERATE DIRECTLY ON SYMBOLS ################# mySymbol = Cartera.symbols["GE"] basic_joint_info = 1 # Obtaining info for the same period indicators_lib = 1 # Obtaining the indicators of the timeSeries ###### FUNCTIONS TO OPERATE ON THE SAME PERIOD ############# basic_joint_info = 1 if (basic_joint_info == 1): prices = Cartera.get_timeSeries(period1) returns = Cartera.get_Returns(period1) cumReturns = Cartera.get_CumReturns(period1) dates = Cartera.get_dates(period1, Cartera.symbol_names[0]) gl.set_subplots(2, 2) gl.plot(dates, prices[:, 0], labels=["Prices Portfolio Assets", "", "Price"], legend=[Cartera.symbol_names[0]]) gl.plot(dates, prices[:, 1], legend=[Cartera.symbol_names[1]], nf=0, na=1) gl.plot(dates, returns, labels=["Returns Portfolio Assets", "", "Return"], legend=Cartera.symbol_names) gl.plot(dates, cumReturns, labels=["cumReturns Portfolio Assets", "", "Return"],
################# PLOT DATA ############################### ############################################################ import numpy as np import scipy.stats as stats from matplotlib import pyplot as plt cdf = stats.norm.cdf data = ret1; if(qq_plot): # Get the histogram and gaussian estimations ! ## Scatter plot of the points gl.set_subplots(1,2) x_grid_emp, y_val_emp = bMA.empirical_1D_cdf(ret1) x_grid = np.linspace(x_grid_emp[0],x_grid_emp[-1],100) x_grid, y_val = bMA.gaussian1D_points_cdf(X = ret1, x_grid = x_grid) ax1 = gl.plot(X = x_grid, Y = y_val, AxesStyle = "Normal", nf = 1, color = "k", alpha = 0.5) gl.scatter(x_grid_emp, y_val_emp, color = "k", labels = ["","",""], legend = ["empirical cdf"]) ## Now here we just plot it one againts each other like in a regression ## problem !
def IFE_h (self, Rf = 0, mktcap = [], year_start = 1996, year_finish = 2016, window = 10): ## Black litterman question !! # The optimal portolio, lets say is the one given by Markovitz # mktcap is a dicktionary with the market capitalizaion of the equities self.pf.set_interval(dt.datetime(year_start,1,1),dt.datetime(year_finish,1,1)) ## Get the actual stuff !! ExpRet = self.get_MeanReturns() Sigma = self.get_covMatrix() woptimal = self.TangentPortfolio() self.set_allocation(woptimal) R,S = self.get_metrics() delta = (R - self.Rf)/np.power(S,2) # Optimal risk adversion ## Get the weights by the market capitalization if (len(mktcap) > 0): weq = [] for sym in self.symbol_names: weq.append(mktcap[sym]) weq = ul.fnp(weq) /np.sum(weq) weq = weq.T.tolist()[0] # print weq else: weq = woptimal # Initial prior ############### PUT FECKING BL prior instead ########## # Calculate initial portfolio from the market capitalization # Risk aversion of the market. We say it is the one of the portfolio # The optimal portfolio is the market. # weq = np.ones((1,self.Nsym))/self.Nsym # weq = weq.tolist()[0] # Coefficient of uncertainty in the prior estimate of the mean tau = 10 ### Prior of our Views !!! P1 = np.zeros((2,self.Nsym)) P1[0,0] = -1; P1[0,1] = 1 P1[1,1] = -1; P1[1,2] = 1 P1 = ul.fnp(P1) # If we invert P1 and Q1 at the same time we get the same Q1 = [0.0002, 0.0001] Q1 = ul.fnp(Q1) Omega1 = np.dot(np.dot(P1,Sigma),P1.T) * np.eye(Q1.shape[0]) postPi,weqpost = self.BlackLitterman(weq, Sigma, delta, # Prior portfolio variables tau, # Uncertainty coefficient of the porfolio priors P1, Q1, Omega1) # Prior views variables # Reference returns of the portfolio of the market # They can just be calculated using the portfolio # A priory the expected return Posteriori does not have to be bigger # Just more accuarate to reality if our views are right :) refPi = delta * np.dot(Sigma, weq) Ereturn = np.dot(refPi,weq) EreturnPost = np.dot(postPi,weqpost) ## Plot the returns !!! # We will plot the real w returns, the Pi Returns, and the Post- Returns gl.set_subplots(2,3) gl.bar(self.pf.symbols.keys(),ExpRet, labels = ["Optimal initial returns"]) gl.bar(self.pf.symbols.keys(),refPi, labels = ["Prior Returns"]) gl.bar(self.pf.symbols.keys(),postPi, labels = ["Posterior Returns"]) # gl.savefig(folder_images +'returnsBL.png', # dpi = 150, sizeInches = [2*8, 2*6]) ## Plot the weights !!! # We will plot the real w returns, the Pi Returns, and the Post- Returns # gl.set_subplots(1,3) gl.bar(self.pf.symbols.keys(),woptimal, labels = ["Optimal intial weights"]) gl.bar(self.pf.symbols.keys(),weq, labels = ["Prior Weights"]) gl.bar(self.pf.symbols.keys(),weqpost, labels = ["Posterior Weights"]) # gl.savefig(folder_images +'weightsBL.png', # dpi = 150, sizeInches = [2*8, 2*6]) gl.savefig(folder_images +'weightsreturnsBL.png', dpi = 150, sizeInches = [2*8, 2*6]) pass
# Set the timeSeries to operate with. mySymbol.set_seriesNames(["Close"]) ############################################################ ###### NOW WE OPERATE DIRECTLY ON THE TIMEDATAs ############ ############################################################ periods = mySymbol.get_periods() periods = sorted(periods,reverse = True) opentime, closetime = mySymbol.get_timeData(periods[1]).guess_openMarketTime() dataTransform = ["intraday", opentime, closetime] folder_images = "../pics/gl/" gl.set_subplots(4,1) # TODO: Align the transformation of the daily prices to axeshare = None for i in range(len(periods)): period = periods[i] myTimeData = mySymbol.get_timeData(period) AxesStyle = " - No xaxis" if (i == len(periods) -1): AxesStyle = "" if (i == 0): title = "Bar Chart. " + str(symbols[0]) + r" . Price ($\$$)" else: title = "" ylabel = ul.period_dic[myTimeData.period]
# SMASMA = indl.get_SMA(diffw1, nHMA, cval = 1) WMAw = indl.get_WMA(delta, nHMA, cval = 1) dWMAw = bMA.convolve(WMAw, diff_final) # WMAWMA = bMA.diff(WMAWMA, cval = np.nan) # WMAWMA = indl.get_WMA(diffw1, nHMA, cval = 1) EMAw = indl.get_EMA(delta, nHMA, cval = 1) dEMAw = bMA.convolve(EMAw, diff_final) # EMAEMA = bMA.diff(EMAEMA, cval = np.nan) # EMAEMA = indl.get_EMA(diffw1, nHMA, cval = 1) ## Plotting just the 3 windows gl.set_subplots(1,3) marker = [".",20,"r"] lw = 4 # Plotting the 3 of them at the same time. ax1 = gl.stem([], diffw1, nf = 1, lw = lw, labels = ["MOMw(%i)"%ndiff1,"lag","Value"], xlimPad = [0.1,0.3], ylimPad = [0.1,0.1], marker = marker, AxesStyle = "Normal2") gl.stem([], diffw2, nf = 1, sharex = ax1, sharey = ax1,lw = lw, labels = ["MOMw(%i)"%ndiff2,"lag",""], xlimPad = [0.1,0.3], ylimPad = [0.1,0.1], marker = marker, AxesStyle = "Normal2 - No yaxis") gl.stem([], diffw3, nf = 1,sharex = ax1, sharey = ax1,lw = lw,
def plot_multiple_iterations(Xs,mus,covs, Ks ,myDManager, logl,theta_list,model_theta_list, folder_images): ######## Plot the original data ##### gl.init_figure(); gl.set_subplots(2,3); Ngraph = 6 colors = ["r","b","g"] K_G,K_W,K_vMF = Ks for i in range(Ngraph): indx = int(i*((len(theta_list)-1)/float(Ngraph-1))) nf = 1 for xi in range(len( Xs)): ## First cluster labels = ['EM Evolution. Kg:'+str(K_G)+ ', Kw:' + str(K_W) + ', K_vMF:' + str(K_vMF), "X1","X2"] ax1 = gl.scatter(Xs[xi][0,:],Xs[xi][1,:],labels = ["","",""] , color = colors[xi] ,alpha = 0.2, nf = nf) nf =0 mean,w,h,theta = bMA.get_gaussian_ellipse_params( mu = mus[xi], Sigma = covs[xi], Chi2val = 2.4477) r_ellipse = bMA.get_ellipse_points(mean,w,h,theta) gl.plot(r_ellipse[:,0], r_ellipse[:,1], ax = ax1, ls = "--", lw = 2 ,AxesStyle = "Normal2", color = colors[xi], alpha = 0.7) # Only doable if the clusters dont die for k_c in myDManager.clusterk_to_Dname.keys(): k = myDManager.clusterk_to_thetak[k_c] distribution_name = myDManager.clusterk_to_Dname[k_c] # G W if (distribution_name == "Gaussian"): ## Plot the ecolution of the mu #### Plot the Covariance of the clusters ! mean,w,h,theta = bMA.get_gaussian_ellipse_params( mu = theta_list[indx][k][0], Sigma = theta_list[indx][k][1], Chi2val = 2.4477) r_ellipse = bMA.get_ellipse_points(mean,w,h,theta) gl.plot(r_ellipse[:,0], r_ellipse[:,1], ax = ax1, ls = "-.", lw = 3, AxesStyle = "Normal2", legend = ["Kg(%i). pi:%0.2f"%(k, float(model_theta_list[indx][0][0,k]))]) elif(distribution_name == "Watson"): #### Plot the pdf of the distributino ! ## Distribution parameters for Watson kappa = float(theta_list[indx][k][1]) mu = theta_list[indx][k][0] Nsa = 1000 # Draw 2D samples as transformation of the angle Xalpha = np.linspace(0, 2*np.pi, Nsa) Xgrid= np.array([np.cos(Xalpha), np.sin(Xalpha)]) probs = [] # Vector with probabilities for i in range(Nsa): probs.append(np.exp(Wad.Watson_pdf_log(Xgrid[:,i],[mu,kappa]) )) probs = np.array(probs) # Plot it in polar coordinates X1_w = (1 + probs) * np.cos(Xalpha) X2_w = (1 + probs) * np.sin(Xalpha) gl.plot(X1_w,X2_w, alpha = 1, lw = 3, ls = "-.",legend = ["Kw(%i). pi:%0.2f"%(k, float(model_theta_list[indx][0][0,k]))]) elif(distribution_name == "vonMisesFisher"): #### Plot the pdf of the distributino ! ## Distribution parameters for Watson kappa = float(theta_list[indx][k][1]); mu = theta_list[indx][k][0] Nsa = 1000 # Draw 2D samples as transformation of the angle Xalpha = np.linspace(0, 2*np.pi, Nsa) Xgrid= np.array([np.cos(Xalpha), np.sin(Xalpha)]) probs = [] # Vector with probabilities for i in range(Nsa): probs.append(np.exp(vMFd.vonMisesFisher_pdf_log(Xgrid[:,i],[mu,kappa]) )) probs = np.array(probs) probs = probs.reshape((probs.size,1)).T # Plot it in polar coordinates X1_w = (1 + probs) * np.cos(Xalpha) X2_w = (1 + probs) * np.sin(Xalpha) # print X1_w.shape, X2_w.shape gl.plot(X1_w,X2_w, alpha = 1, lw = 3, ls = "-.", legend = ["Kvmf(%i). pi:%0.2f"%(k, float(model_theta_list[indx][0][0,k]))]) ax1.axis('equal') gl.subplots_adjust(left=.09, bottom=.10, right=.90, top=.95, wspace=.2, hspace=0.01) gl.savefig(folder_images +'Final_State2. K_G:'+str(K_G)+ ', K_W:' + str(K_W) + '.png', dpi = 100, sizeInches = [18, 8])
period=period1, maxPullback=maxPullback) exitcrosses, all_stops, pCheckCross, datesExit = mySalida.get_TradeSignals() # Second Signal mySalida2 = CTS.CTrailingStop("salircaca", period1, Cartera) secondEntrySingal = EntrySignals[1] mySalida2.set_trailingStop(SymbolName=symbol, BUYSELL=secondEntrySingal.BUYSELL, datetime=secondEntrySingal.datetime, period=period1, maxPullback=maxPullback) exitcrosses2, all_stops2, pCheckCross2, datesExit2 = mySalida2.get_TradeSignals( ) ########## Plotting ! #################### gl.set_subplots(3, 1) ## Price Axes ax1 = gl.plot(dates, price, legend=["Price"], labels=["Crossing MA Strategy", "", "Price"], alpha=0, nf=1) gl.barchart(dates, dataHLOC) gl.plot(dates, EMAslow, legend=["Slow"], lw=1, color="b") gl.plot(dates, EMAfast, legend=["fast"], lw=1, color="r", xaxis_mode="hidden") ## Entry Axes ax2 = gl.plot(dates,
def IFE_g(self, Rf=0, year_start=1996, year_finish=2016, window=10): ## CAPM model question, calculate abs and doubt everything you know self.set_Rf(Rf) self.pf.set_interval(dt.datetime(year_start, 1, 1), dt.datetime(year_finish, 1, 1)) # Plot the correlation between some index and the stock gl.set_subplots(2, 3) self.pf.set_interval(dt.datetime(year_start, 1, 1), dt.datetime(year_start + window, 1, 1)) for i in range(6): self.plot_corrab(self.symbol_names[i]) gl.savefig(folder_images + 'SymbolAB.png', dpi=80, sizeInches=[2 * 8, 2 * 6]) # Plot the jensen alpha of some of the stocks gl.set_subplots(2, 3) self.pf.set_interval(dt.datetime(year_start, 1, 1), dt.datetime(year_start + window, 1, 1)) for i in range(6): JensenAlpha = self.get_symbol_JensenAlpha(self.symbol_names[i]) gl.histogram(JensenAlpha, labels=[self.symbol_names[i]]) gl.savefig(folder_images + 'JensenAlphasAll.png', dpi=80, sizeInches=[4 * 8, 3 * 6]) ## We set a stupid initial portfolio (Everything equal) param = self.get_symbol_ab(self.symbol_names[1]) print "Params of %s" % self.symbol_names[1] print param ########## TEST ONE SYMBOL ###### # self.test_symbol_ab(self.symbol_names[1]) # Print stupid portfolio # Param params = self.get_all_symbols_ab() print "All params" print params # Params of stupid porfolio print "Params of stupid portfolio" self.set_allocation([]) param = self.get_portfolio_ab(mode="normal") # Obtained as definition print param param = self.get_portfolio_ab( mode="gaussian") # Obtained first getting the cov matrix print param ########## TEST Portfolio ###### # Test the jensenAlpha of the portfolio JensenAlpha = self.get_portfolio_JensenAlpha() ## IDEA !! Maybe use the portfolio in the frontier that maximizes ## the alpha and minimizes the beta !!! Maybe minimizing beta is not as important ## In the CAMP we already have the total Exp and risk. ## Alpha and beta say: Does out portolio perform better than the market ? ## If we just follow the market, investing everything on the index, ## Thus investing in everything proportionally to their capital. ## Then we have alpha = 0 and beta = 1 # CAPMillo.test_symbol_ab(symbols[2]) # Plot random porfolios correlation with the index alloc = self.get_random_allocations(100, short="yes", mode="gaussian") gl.set_subplots(2, 3) for i in range(6): self.set_allocation(alloc[i]) self.plot_portfoliocorrab(nf=1) gl.savefig(folder_images + 'randomPortCorr.png', dpi=150, sizeInches=[2 * 8, 2 * 6]) # Plot Jesen Alpha for random portfolios flag_nf = 1 for i in range(5): self.set_allocation(alloc[i]) self.test_Jensens_Alpha(nf=flag_nf) flag_nf = 0 gl.savefig(folder_images + 'randomPortJA.png', dpi=150, sizeInches=[2 * 8, 2 * 6]) ############################################## ########### ANALIZE 3 optimal portfolios ##### ############################################## Rfs = [0, 0.002, 0.0031] print "???????????????:?:::::::::::::::::::::::::::::::::::::::" flag_nf = 1 for Rf in Rfs: # Do it again with an optimal portolio w = self.TangentPortfolio(Rf=Rf) self.set_allocation(w) self.test_Jensens_Alpha(nf=flag_nf) flag_nf = 0 flag_nf = 1 gl.savefig(folder_images + 'optimalPortJA.png', dpi=150, sizeInches=[2 * 8, 2 * 6]) gl.set_subplots(1, 3) for Rf in Rfs: # Do it again with an optimal portolio w = self.TangentPortfolio(Rf=Rf) self.set_allocation(w) self.plot_portfoliocorrab(nf=1) flag_nf = 0 gl.savefig(folder_images + 'optimalPortCorr.png', dpi=150, sizeInches=[2 * 8, 1 * 6])
if (comparing_lags): # Some basic indicators. price = timeData.get_timeSeries(["Close"]) dates = timeData.get_dates() nSMAs = [7, 20, 50] nEMAs = [7, 20, 50] # For lag and noise SMAs = [] for nMA_i in nSMAs: SMAs.append(timeData.SMA(seriesNames=["Close"], n=nMA_i)) EMAs = [] for nMA_i in nEMAs: EMAs.append(timeData.EMA(seriesNames=["Close"], n=nMA_i)) ############## PLOTTING ################ gl.set_subplots(2, 1) # Axes with the SMAs legend = ["Price"] legend.extend(["SMA(" + str(x) + ")" for x in nSMAs]) SMAs.insert(0, price) title = "Influence of L in the lag. " + str( symbols[0]) + "(" + ul5.period_dic[timeData.period] + ")" ax1 = gl.plot(dates, SMAs, nf=1, labels=[title, "", r"Price ($\$$)"], legend=legend, AxesStyle="Normal - No xaxis") # Axes with the EMAs legend = ["Price"]
def IFE_h(self, Rf=0, mktcap=[], year_start=1996, year_finish=2016, window=10): ## Black litterman question !! # The optimal portolio, lets say is the one given by Markovitz # mktcap is a dicktionary with the market capitalizaion of the equities self.pf.set_interval(dt.datetime(year_start, 1, 1), dt.datetime(year_finish, 1, 1)) ## Get the actual stuff !! ExpRet = self.get_MeanReturns() Sigma = self.get_covMatrix() woptimal = self.TangentPortfolio() self.set_allocation(woptimal) R, S = self.get_metrics() delta = (R - self.Rf) / np.power(S, 2) # Optimal risk adversion ## Get the weights by the market capitalization if (len(mktcap) > 0): weq = [] for sym in self.symbol_names: weq.append(mktcap[sym]) weq = ul.fnp(weq) / np.sum(weq) weq = weq.T.tolist()[0] # print weq else: weq = woptimal # Initial prior ############### PUT FECKING BL prior instead ########## # Calculate initial portfolio from the market capitalization # Risk aversion of the market. We say it is the one of the portfolio # The optimal portfolio is the market. # weq = np.ones((1,self.Nsym))/self.Nsym # weq = weq.tolist()[0] # Coefficient of uncertainty in the prior estimate of the mean tau = 10 ### Prior of our Views !!! P1 = np.zeros((2, self.Nsym)) P1[0, 0] = -1 P1[0, 1] = 1 P1[1, 1] = -1 P1[1, 2] = 1 P1 = ul.fnp(P1) # If we invert P1 and Q1 at the same time we get the same Q1 = [0.0002, 0.0001] Q1 = ul.fnp(Q1) Omega1 = np.dot(np.dot(P1, Sigma), P1.T) * np.eye(Q1.shape[0]) postPi, weqpost = self.BlackLitterman( weq, Sigma, delta, # Prior portfolio variables tau, # Uncertainty coefficient of the porfolio priors P1, Q1, Omega1) # Prior views variables # Reference returns of the portfolio of the market # They can just be calculated using the portfolio # A priory the expected return Posteriori does not have to be bigger # Just more accuarate to reality if our views are right :) refPi = delta * np.dot(Sigma, weq) Ereturn = np.dot(refPi, weq) EreturnPost = np.dot(postPi, weqpost) ## Plot the returns !!! # We will plot the real w returns, the Pi Returns, and the Post- Returns gl.set_subplots(2, 3) gl.bar(self.pf.symbols.keys(), ExpRet, labels=["Optimal initial returns"]) gl.bar(self.pf.symbols.keys(), refPi, labels=["Prior Returns"]) gl.bar(self.pf.symbols.keys(), postPi, labels=["Posterior Returns"]) # gl.savefig(folder_images +'returnsBL.png', # dpi = 150, sizeInches = [2*8, 2*6]) ## Plot the weights !!! # We will plot the real w returns, the Pi Returns, and the Post- Returns # gl.set_subplots(1,3) gl.bar(self.pf.symbols.keys(), woptimal, labels=["Optimal intial weights"]) gl.bar(self.pf.symbols.keys(), weq, labels=["Prior Weights"]) gl.bar(self.pf.symbols.keys(), weqpost, labels=["Posterior Weights"]) # gl.savefig(folder_images +'weightsBL.png', # dpi = 150, sizeInches = [2*8, 2*6]) gl.savefig(folder_images + 'weightsreturnsBL.png', dpi=150, sizeInches=[2 * 8, 2 * 6]) pass
############### Getting a noisy signal and label it ######################### ########################################################################### # Generate noisy signal: f_prime = np.random.randn(N,1) error = L.dot(f_prime) X_noisy = X + error # Label the original and new signal Y = (np.sign(np.diff(X,n=1,axis = 0)) +1)/2.0 Y_noisy = (np.sign(np.diff(X_noisy,n=1,axis = 0)) +1)/2.0 ## Subselect both the signals X and the labels Y since we cannot know the prediction of the last sample. if (plot_labelling_signal and plot_flag): gl.set_subplots(2,1) # Plot the original signal and its labelling ! ax1 = gl.scatter(tgrid,X, lw = 1, alpha = 0.9, color = "k", nf = 1, labels = ["Original signal","",r"$\mu(t)$"]) gl.plot(tgrid,X, lw = 2, color = "k", ls = "--") gl.set_fontSizes( title = 20, xlabel = 15, ylabel = 20, legend = 12, xticks = 12, yticks = 12) gl.stem(tgrid[:-1,0], Y, sharex = ax1, nf = 1, labels = ["", "t","Y(t)"], bottom = 0.5) # Plot noisy part # gl.scatter(tgrid,X_noisy, lw = 1, alpha = 0.9, color = "k", nf = 1, # labels = ["Noisy signal","","X(t)"]) # gl.plot(tgrid,X_noisy, lw = 2, color = "k", ls = "--") # gl.stem(tgrid[:-1,0], Y_noisy, sharex = ax1, nf = 1, labels = ["", "t","Y_noise(t)"])
if (myEM.clusters_relation == "independent"): Nsam, K = r.shape elif(myEM.clusters_relation == "MarkovChain1"): Nsam, K = r[0].shape legend = [" K = %i"%i for i in range(K)] ax1 = None legend = [] labels_title = "Cluster's responsibility" if (1): """ We plot them on top of each other """ gl.set_subplots(days_plot,1); dataTransform = None nf = 1 for i in range(len(Xdata_dates)): Xdata_dates[i] = Xdata_dates[i].time else: """ We plot them on as a sequence """ gl.init_figure() nf = 0 AxesStyle = "Normal - No xaxis - Ny:3" for i in range(days_plot): chain = Xdata[i] r = myEM.get_responsibilities([chain],myDManager, theta_list[-1],model_theta_list[-1])
if (myEM.clusters_relation == "independent"): Nsam, K = r.shape elif (myEM.clusters_relation == "MarkovChain1"): Nsam, K = r[0].shape legend = [" K = %i" % i for i in range(K)] ax1 = None legend = [] labels_title = "Cluster's responsibility" if (1): """ We plot them on top of each other """ gl.set_subplots(days_plot, 1) dataTransform = None nf = 1 for i in range(len(Xdata_dates)): Xdata_dates[i] = Xdata_dates[i].time else: """ We plot them on as a sequence """ gl.init_figure() nf = 0 AxesStyle = "Normal - No xaxis - Ny:3" for i in range(days_plot): chain = Xdata[i] r = myEM.get_responsibilities([chain], myDManager, theta_list[-1],
edate = dt.datetime.strptime(edate_str, "%d-%m-%Y") mySymbol.set_interval(sdate, edate) # Set the interval period to be analysed #### Filling of data !!! #mySymbol.fill_data() # Set the timeSeries to operate with. mySymbol.set_seriesNames(["Close"]) ############################################################ ###### NOW WE OPERATE DIRECTLY ON THE TIMEDATAs ############ ############################################################ periods = mySymbol.get_periods() gl.set_subplots(4, 1, sharex=True) # TODO: Be able to automatize the shareX thing for period in periods: myTimeData = mySymbol.get_timeDataObject(period) price = myTimeData.get_timeSeries(["Close"]) volume = myTimeData.get_timeSeries(["Volume"]) dates = myTimeData.get_dates() gl.plot(dates, price, labels=["", "", mySymbol.symbol], legend=[str(period)]) gl.stem(dates, volume, legend=[str(period)], na=1, nf=0) gl.subplots_adjust(left=.09,
def IFE_f(self, ObjectiveR=0.003, Rf=0.0, year_start=1996, year_finish=2016, window=10): ### The official one can be done executing the exercise c with another Rf ## Just another graph to show that now we should not use all the data. # Just, choose a desired return, # Using training Samples calculate using the market line # the optimal porfolio for that. # Then calculate for the next year, the real return # for that portfolio. # Do this for several years as well. self.set_Rf(Rf) nf_flag = 1 All_stds = [] PortfolioReturns = [] IndexReturns = [] all_dates = [] for year_test in range(year_start, year_finish - window + 1 - 1): # +1 !! # Set the dates self.pf.set_interval(dt.datetime(year_test, 1, 1), dt.datetime(year_test + window, 1, 1)) # Obtain the market line !! w = self.TangentPortfolio(Rf=Rf) # Obtain allocation self.set_allocation(w) # Obtain the expected return and std when using all our money ! expRet, stdRet = self.get_metrics(investRf="no") param = bMl.obtain_equation_line(Rf, expRet, stdRet) bias, slope = param X = (ObjectiveR - Rf) / (expRet - Rf) wdesired = w * X ## Check that the output of this portfolio is the desired one. self.set_allocation(wdesired) # Set the allocation expRet, stdRet = self.get_metrics( ) # Get the expected return for that year # print ret ## Now that we have the desired w*X, we will calculate the resturn of ## the portfolio in the following year. # To do so, we set the dates, only to the next year, set the portfolio allocation # And calculate the yearly expected return !! # Set the dates to only the next year !! # Also, one month before in order to get the returns of the first month. self.pf.set_interval(dt.datetime(year_test + window, 1, 1), dt.datetime(year_test + window + 1, 1, 1)) self.set_allocation(wdesired) # Set the allocation expRet, stdRet = self.get_metrics( ) # Get the expected return for that year PortfolioRet = self.yearly_Return(expRet) # Get yearly returns PortfolioReturns.append(PortfolioRet) All_stds.append(self.yearly_covMatrix(stdRet)) indexRet = self.get_indexMeanReturn() indexRet = self.yearly_Return(indexRet) IndexReturns.append(indexRet) # dates = self.get_dates() all_dates.append(year_test + window + 1) ## Graph with the evolutio of the portfolio price after the assignment gl.plot(range(1, 13), np.cumsum(self.get_PortfolioReturn()), nf=nf_flag, labels=[ "Evolution of returns by month", "Months passed", "Cumulative Return" ], legend=[str(year_test + window + 1)]) nf_flag = 0 # print ret gl.savefig(folder_images + 'returnsEvolMonth.png', dpi=150, sizeInches=[2 * 8, 2 * 6]) ## Graph with the desired, the obtained returns and the returns of the index gl.bar(all_dates[:], IndexReturns, labels=["Obtained returns", "Time (years)", "Return (%)"], legend=["Index Return"], alpha=0.8, nf=1) gl.bar(all_dates[:], PortfolioReturns, labels=["Returns of year", "Year", "Value"], legend=["Porfolio Return"], alpha=0.8, nf=0) gl.scatter(all_dates[:], self.yearly_Return(ObjectiveR) * np.ones( (len(all_dates[:]), 1)), legend=["Objective Return"], nf=0) gl.scatter(all_dates[:], All_stds, legend=["Std of the portfolio return"], nf=0) gl.savefig(folder_images + 'returnsEvolYears.png', dpi=150, sizeInches=[2 * 8, 2 * 6]) #### Crazy idea !! Lets plot where the f*****g efficient frontier went nf_flag = 1 PortfolioReturns = [] IndexReturns = [] all_dates = [] gl.set_subplots(2, 3) for year_test in range(year_start, year_start + 6): # +1 !! # Set the dates self.pf.set_interval(dt.datetime(year_test, 1, 1), dt.datetime(year_test + window, 1, 1)) optimal, portfolios = self.efficient_frontier(kind="Tangent") self.plot_allocations( portfolios, labels=["Evolution of the efficient frontier"], legend=["Frontier " + str(year_test + window) + " before"], color="k", nf=1) self.pf.set_interval(dt.datetime(year_test + window, 1, 1), dt.datetime(year_test + window + 1, 1, 1)) self.set_allocation(self.TangentPortfolio(Rf=Rf)) self.plot_allocations( portfolios, legend=["Frontier " + str(year_test + window) + " after"], color="r", nf=0) gl.savefig(folder_images + 'effEvol.png', dpi=80, sizeInches=[4 * 8, 3 * 6])
if (plot_time_stuff): new_ll = myEM.get_loglikelihood(Xdata, myDManager, theta_list[-1], mode_theta_list[-1]) r = myEM.get_responsibilities(Xdata, myDManager, theta_list[-1], mode_theta_list[-1]) if (myEM.clusters_relation == "independent"): Nsam, K = r.shape elif (myEM.clusters_relation == "MarkovChain1"): Nsam, K = r[0].shape Npeople_plot = Npeople legend = [" K = %i" % i for i in range(K)] gl.set_subplots(Npeople, 1) ax1 = None legend = [] labels_title = "Cluster responsibility for the EM" Ndiv = 4 for i in range(Npeople_plot): if (myEM.clusters_relation == "independent"): resp = r[N * i:N * (i + 1), :] elif (myEM.clusters_relation == "MarkovChain1"): resp = r[i] Nclusters = resp.shape[1] ax_ii = gl.subplot2grid((Npeople_plot, Ndiv), (i, 0), rowspan=1,
def IFE_e (self, ObjectiveR = 0.003, Rf = 0.0, year_start = 1996, year_finish = 2016, window = 10): # Just, choose a desired return, # Using training Samples calculate using the market line # the optimal porfolio for that. # Then, using also the last year ( test), recalculate the portfolio needed # for that return, and the difference between is the turnover self.set_Rf(Rf) nf_flag = 1 desired_Portfolios = [] all_dates = [] for year_test in range(year_start,year_finish - window + 1): # +1 !! # Set the dates self.pf.set_interval(dt.datetime(year_test,1,1),dt.datetime(year_test + window,1,1)) # Obtain the market line !! w = self.TangentPortfolio(Rf = Rf) # Obtain allocation # Obtain the expected return and std when using all our money ! self.set_allocation(w) expRet, stdRet = self.get_metrics (investRf = "no") param = bMl.obtain_equation_line(Rf, expRet, stdRet) bias, slope = param # Once we have the equation of the line, we obtain how much money # we need to use to reach the desired Expecred Return. # Rt = (1 - X)Rf + XRp with X = sum(w) # For a desired Rt we solve the X X = (ObjectiveR - Rf)/(expRet - Rf) # print X # So the desired porfolio is: wdesired = w*X desired_Portfolios.append(wdesired) gl.plot([0,1.3*abs(X*stdRet)],[bias, bias + 1.3*abs(slope*stdRet*X)], labels = ["Desired Portfolios", "Risk (std)", "Return (%)"], legend = ["%s, X: %0.3f" %((year_test + window ), X[0])], nf = nf_flag, loc = 2) nf_flag = 0 gl.scatter([abs(X*stdRet)],[ObjectiveR], nf = 0) dates = self.get_dates() all_dates.append(dates[-1]) # print wdesired gl.savefig(folder_images +'desiredPortfolios.png', dpi = 150, sizeInches = [2*8, 2*6]) # Now we calculate the turnovers Turnovers = [] prev_abs_alloc = [] # Previous, absolute allocation percentaje_changed = [] Nport = len(desired_Portfolios) for i in range(Nport-1): to = bMl.get_TurnOver(desired_Portfolios[i], desired_Portfolios[i+1]) Turnovers.append(to) prev_abs_alloc.append(np.sum(np.abs(desired_Portfolios[i]))) percentaje_changed.append(Turnovers[-1]/prev_abs_alloc[-1]) print Turnovers gl.set_subplots(1,3) gl.bar(all_dates[1:], Turnovers, color = "g", labels = ["Portfolio turnovers", "Year","Value"]) gl.add_text([all_dates[1:][3],max(Turnovers)*0.80], "Mean: %0.2f" % np.mean(Turnovers), 30) gl.bar(all_dates[0:-1], prev_abs_alloc, color = "r", labels = ["Absolute allocations", "Year","Value"]) gl.bar(all_dates[1:], percentaje_changed, color = "b", labels = ["Percentage turnover", "Year","Value"]) gl.add_text([all_dates[1:][3],max(percentaje_changed)*0.80], "Mean: %0.2f" % np.mean(percentaje_changed), 30) gl.savefig(folder_images +'turnovers.png', dpi = 150, sizeInches = [2*8, 1*6])
def IFE_f (self, ObjectiveR = 0.003, Rf = 0.0, year_start = 1996, year_finish = 2016, window = 10): ### The official one can be done executing the exercise c with another Rf ## Just another graph to show that now we should not use all the data. # Just, choose a desired return, # Using training Samples calculate using the market line # the optimal porfolio for that. # Then calculate for the next year, the real return # for that portfolio. # Do this for several years as well. self.set_Rf(Rf) nf_flag = 1 All_stds = [] PortfolioReturns = [] IndexReturns = [] all_dates = [] for year_test in range(year_start,year_finish - window + 1 - 1): # +1 !! # Set the dates self.pf.set_interval(dt.datetime(year_test,1,1),dt.datetime(year_test + window,1,1)) # Obtain the market line !! w = self.TangentPortfolio(Rf = Rf) # Obtain allocation self.set_allocation(w) # Obtain the expected return and std when using all our money ! expRet, stdRet = self.get_metrics (investRf = "no") param = bMl.obtain_equation_line(Rf, expRet, stdRet) bias, slope = param X = (ObjectiveR - Rf)/(expRet - Rf) wdesired = w*X ## Check that the output of this portfolio is the desired one. self.set_allocation(wdesired) # Set the allocation expRet, stdRet = self.get_metrics() # Get the expected return for that year # print ret ## Now that we have the desired w*X, we will calculate the resturn of ## the portfolio in the following year. # To do so, we set the dates, only to the next year, set the portfolio allocation # And calculate the yearly expected return !! # Set the dates to only the next year !! # Also, one month before in order to get the returns of the first month. self.pf.set_interval(dt.datetime(year_test + window,1,1),dt.datetime(year_test + window + 1,1,1)) self.set_allocation(wdesired) # Set the allocation expRet, stdRet = self.get_metrics() # Get the expected return for that year PortfolioRet = self.yearly_Return(expRet) # Get yearly returns PortfolioReturns.append(PortfolioRet) All_stds.append(self.yearly_covMatrix(stdRet)) indexRet = self.get_indexMeanReturn() indexRet = self.yearly_Return(indexRet) IndexReturns.append(indexRet) # dates = self.get_dates() all_dates.append(year_test + window + 1) ## Graph with the evolutio of the portfolio price after the assignment gl.plot(range(1,13), np.cumsum(self.get_PortfolioReturn()), nf = nf_flag, labels = ["Evolution of returns by month", "Months passed", "Cumulative Return"], legend = [str(year_test + window +1)]) nf_flag = 0 # print ret gl.savefig(folder_images +'returnsEvolMonth.png', dpi = 150, sizeInches = [2*8, 2*6]) ## Graph with the desired, the obtained returns and the returns of the index gl.bar(all_dates[:], IndexReturns, labels = ["Obtained returns", "Time (years)", "Return (%)"], legend = ["Index Return"], alpha = 0.8, nf = 1) gl.bar(all_dates[:], PortfolioReturns, labels = ["Returns of year", "Year","Value"], legend = ["Porfolio Return"], alpha = 0.8, nf = 0) gl.scatter(all_dates[:], self.yearly_Return(ObjectiveR) * np.ones((len(all_dates[:]),1)), legend = ["Objective Return"], nf = 0) gl.scatter(all_dates[:], All_stds, legend = ["Std of the portfolio return"], nf = 0) gl.savefig(folder_images +'returnsEvolYears.png', dpi = 150, sizeInches = [2*8, 2*6]) #### Crazy idea !! Lets plot where the f*****g efficient frontier went nf_flag = 1 PortfolioReturns = [] IndexReturns = [] all_dates = [] gl.set_subplots(2,3) for year_test in range(year_start,year_start + 6): # +1 !! # Set the dates self.pf.set_interval(dt.datetime(year_test,1,1),dt.datetime(year_test + window,1,1)) optimal, portfolios = self.efficient_frontier(kind = "Tangent") self.plot_allocations(portfolios, labels = ["Evolution of the efficient frontier"], legend = ["Frontier " + str(year_test + window) + " before"], color = "k", nf = 1) self.pf.set_interval(dt.datetime(year_test + window,1,1),dt.datetime(year_test + window + 1,1,1)) self.set_allocation(self.TangentPortfolio(Rf = Rf)) self.plot_allocations(portfolios, legend = ["Frontier " + str(year_test + window) + " after"], color = "r",nf = 0) gl.savefig(folder_images +'effEvol.png', dpi = 80, sizeInches = [4*8, 3*6])
basic_joint_info = 0 # Obtaining info for the same period trading_platform_several = 1 # Plot the trading platfom for all of them ###### FUNCTIONS TO OPERATE ON THE SAME PERIOD ############# if (trading_platform_several): # Plot for the 3 quitites, their Barchart and returns symbolIDs_pf = myPortfolio.get_symbolIDs() # dataTransform = ["intraday", opentime, closetime] folder_images = "../pics/gl/" gl.set_subplots(3,2) # TODO: Be able to automatize the shareX thing axeshare = None period = periods[0] for i in range(len(symbolIDs_pf)): symbolID = symbolIDs_pf[i] myTimeData = myPortfolio.get_symbols([symbolID])[0].get_timeData(period) returns = myTimeData.get_timeSeriesReturn(["Close"]) dates = myTimeData.get_dates() AxesStyle = " - No xaxis" if (i == len(symbolIDs_pf) -1): AxesStyle = "" if (i == 0): title = "Bar Chart. " + str(symbolIDs) + r" . Price ($\$$)" title2 = "Return"
def IFE_g (self, Rf = 0, year_start = 1996, year_finish = 2016, window = 10): ## CAPM model question, calculate abs and doubt everything you know self.set_Rf(Rf) self.pf.set_interval(dt.datetime(year_start,1,1),dt.datetime(year_finish,1,1)) # Plot the correlation between some index and the stock gl.set_subplots(2,3) self.pf.set_interval(dt.datetime(year_start,1,1),dt.datetime(year_start + window,1,1)) for i in range(6): self.plot_corrab(self.symbol_names[i]) gl.savefig(folder_images +'SymbolAB.png', dpi = 80, sizeInches = [2*8, 2*6]) # Plot the jensen alpha of some of the stocks gl.set_subplots(2,3) self.pf.set_interval(dt.datetime(year_start,1,1),dt.datetime(year_start + window,1,1)) for i in range(6): JensenAlpha = self.get_symbol_JensenAlpha(self.symbol_names[i]) gl.histogram(JensenAlpha, labels = [self.symbol_names[i]]) gl.savefig(folder_images +'JensenAlphasAll.png', dpi = 80, sizeInches = [4*8, 3*6]) ## We set a stupid initial portfolio (Everything equal) param = self.get_symbol_ab(self.symbol_names[1]) print "Params of %s" % self.symbol_names[1] print param ########## TEST ONE SYMBOL ###### # self.test_symbol_ab(self.symbol_names[1]) # Print stupid portfolio # Param params = self.get_all_symbols_ab() print "All params" print params # Params of stupid porfolio print "Params of stupid portfolio" self.set_allocation([]) param = self.get_portfolio_ab(mode = "normal") # Obtained as definition print param param = self.get_portfolio_ab(mode = "gaussian") # Obtained first getting the cov matrix print param ########## TEST Portfolio ###### # Test the jensenAlpha of the portfolio JensenAlpha = self.get_portfolio_JensenAlpha() ## IDEA !! Maybe use the portfolio in the frontier that maximizes ## the alpha and minimizes the beta !!! Maybe minimizing beta is not as important ## In the CAMP we already have the total Exp and risk. ## Alpha and beta say: Does out portolio perform better than the market ? ## If we just follow the market, investing everything on the index, ## Thus investing in everything proportionally to their capital. ## Then we have alpha = 0 and beta = 1 # CAPMillo.test_symbol_ab(symbols[2]) # Plot random porfolios correlation with the index alloc = self.get_random_allocations(100, short = "yes", mode = "gaussian") gl.set_subplots(2,3) for i in range(6): self.set_allocation(alloc[i]) self.plot_portfoliocorrab( nf = 1) gl.savefig(folder_images +'randomPortCorr.png', dpi = 150, sizeInches = [2*8, 2*6]) # Plot Jesen Alpha for random portfolios flag_nf = 1 for i in range(5): self.set_allocation(alloc[i]) self.test_Jensens_Alpha(nf = flag_nf) flag_nf = 0 gl.savefig(folder_images +'randomPortJA.png', dpi = 150, sizeInches = [2*8, 2*6]) ############################################## ########### ANALIZE 3 optimal portfolios ##### ############################################## Rfs = [0,0.002, 0.0031] print "???????????????:?:::::::::::::::::::::::::::::::::::::::" flag_nf = 1 for Rf in Rfs: # Do it again with an optimal portolio w = self.TangentPortfolio(Rf = Rf) self.set_allocation(w) self.test_Jensens_Alpha(nf = flag_nf) flag_nf = 0 flag_nf = 1 gl.savefig(folder_images +'optimalPortJA.png', dpi = 150, sizeInches = [2*8, 2*6]) gl.set_subplots(1,3) for Rf in Rfs: # Do it again with an optimal portolio w = self.TangentPortfolio(Rf = Rf) self.set_allocation(w) self.plot_portfoliocorrab(nf = 1) flag_nf = 0 gl.savefig(folder_images +'optimalPortCorr.png', dpi = 150, sizeInches = [2*8, 1*6])
# Just one sample example Xangle = 0.5 *np.pi Xsample = [np.cos(Xangle), np.sin(Xangle)] prob = Wad.Watson_pdf(Xsample, mu, kappa) # Draw 2D samples as transformation of the angle Xalpha = np.linspace(0, 2*np.pi, Nsa) Xdata = np.array([np.cos(Xalpha), np.sin(Xalpha)]) probs = [] # Vector with probabilities for i in range(Nsa): probs.append(Wad.Watson_pdf(Xdata[:,i],mu,kappa )) ## Plotting gl.set_subplots(1,3) ## Plot it in terms of (angle, prob) gl.plot(Xalpha,np.array(probs), legend = ["pdf k:%f, mu_angle: %f"%(kappa,mu_angle)], labels = ["Watson Distribution", "Angle(rad)", "pdf"], nf = 1, na = 1) # Plot it in polar coordinates X1 = probs * np.cos(Xalpha) X2 = probs * np.sin(Xalpha) gl.plot(X1,X2, legend = ["pdf k:%f, mu_angle: %f"%(kappa,mu_angle)], labels = ["Watson Distribution", "Angle(rad)", "pdf"], nf = 1, na = 1)