/*===================================================================================*/
/*	Comment																			*/
/*	Application short title: PDBVRAR 														*/
/*	Application full title: Portfolio Diversification Benefits via Risk Adjusted Return					*/
/*	Authors: Abdulnasser Hatemi-J and Alan Mustafa											*/
/*	The UAE University and the IEEE														*/
/*	E-mails: (AHatemi@uaeu.ac.ae) and (alan.mustafa@ieee.org)								*/
/*																					*/
/*	The potential benefits of portfolio diversification have been known to investors for a long time.	*/
/*	Markowitz (1952) suggested the seminal approach for optimizing the portfolio problem based		*/
/*	on finding the weights as budget shares that minimize the variance of the underlying portfolio.	*/
/*	Hatemi-J and El-Khatib (2015) suggested finding the weights that will result in maximizing the		*/
/*	risk adjusted return of the portfolio. This approach seems to be preferred by the rational investors	*/
/*	since it combines risk and return when the optimal budget shares are sought for. The current 		*/
/*	paper provides a general solution for this risk adjusted return problem that can be utilized for any	*/
/*	potential number of assets that are included in the portfolio."								*/
/*																					*/
/*	- Markowitz, H. (1952), Portfolio selection. Journal of Finance 7, (1), 77-91.						*/
/*	- Hatemi-J, A. and El-Khatib Y. (2015), Portfolio selection: An alternative approach, Economics		*/
/*	Letters, 135, 141-143.																*/
/*	- Hatemi-J, A., Hajji, M.A., and El-Khatib, Y. (2019), Exact Solution for the Portfolio Diversification	*/
/*	Problem Based on Maximizing the Risk Adjusted Return. arXiv:1903.01082v1.					*/
/*																					*/
/*	This program code is the copyright of the authors. Applications are allowed only if proper reference	*/
/*	and acknowledgments are provided. For non-Commercial applications only. No performance		*/
/*	guarantee is made. Bug reports are welcome. If this code is used for research or in any other		*/
/*	code, proper attribution needs to be included.											*/
/*																					*/
/*	© 2020 Prof. Abdulnasser Hatemi-J and Dr. Alan Mustafa									*/
/*===================================================================================*/

/*===================================================================================*/
/*	INSTRUCTION ON USING THIS APPLICATION											*/
/*																					*/
/*	Step 1: Dataset must includes labels for each column of asset. Enter prices only.				*/
/*	Step 2: Dataset must not inlcude the 'date' column. The dataset file must only include data.		*/
/*	Step 3: Within the code below, the file name for 'load' section must reflect the dataset filename.	*/
/*			The extension of the file can be of txt or csv.										*/
/*	Step 4: The value for 'no_asset' variable must the same as the number of columns in the dataset.	*/
/*	Step 5: The code is ready to run.														*/
/*===================================================================================*/

/*=======================================================*/
/*				Start of Clearing off the screen				*/
/*=======================================================*/
new;
cls;
/*=======================================================*/
/*				End of Clearing off the screen					*/
/*=======================================================*/

/*=======================================================*/
/*				Start of importing dataSet as data1			*/
/*=======================================================*/

/*=======================================================*/
load data1[]  = pd_data8.txt;
no_asset = 8;				/* The number of assets in the portfolio. */
/*=======================================================*/

data0 = (rows(data1)/no_asset);
data1 = Reshape(data1, data0, no_asset);


no_rows = rows(data1);
no_cols = cols(data1);

/*=======================================================*/
/*				End of importing dataSet as data1				*/
/*=======================================================*/

/*=======================================================*/
/*	Start of restructuring dataSet into data and asset headings 		*/
/*=======================================================*/

data_lbl = data1[1,.];
noOfRows = rows(data1);
data2 = data1[2:noOfRows,.];

aRows = rows(data2);
aCols = cols(data2);

/*=======================================================*/
/*	End of restructuring dataSet into data and asset headings 		*/
/*=======================================================*/

/*=======================================================*/
/*			Start of calculating Return on Assets				*/
/*=======================================================*/

roa=zeros(no_rows,no_cols);			/*	roa: return on asseet	*/

icol=1;
irow = 1;
irow_ = 0;

noRows = rows(data2);
noCols = cols(data2);


for icol(1,noCols,1);
	for irow(2,noRows,1);
		irow_ = irow - 1;
		roa[irow,icol] = (data2[irow,icol] - data2[irow_,icol]) / data2[irow_,icol]; 
	endfor;
endfor;

/*=======================================================*/
/*			End of calculating Return on Assets				*/
/*=======================================================*/

/*=======================================================*/
/*			Start of redefining the dataSet					*/
/*=======================================================*/

roa = roa[2:rows(data2),.];

/*=======================================================*/
/*			End of redefining the dataSet						*/
/*=======================================================*/

/*=======================================================*/
/*			Start of calculating Expected Values - ev			*/
/*=======================================================*/

ev = meanc(roa);

/*=======================================================*/
/*			End of calculating Expected Values - ev				*/
/*=======================================================*/

/*=======================================================*/
/*			Start of calculating Standard Deviation - SD			*/
/*=======================================================*/

sd = stdc(roa);

/*=======================================================*/
/*			End of calculating Standard Deviation - SD			*/
/*=======================================================*/

/*=======================================================*/
/*			Start of calculating Covariance - cov				*/
/*=======================================================*/

cov_ = vcx(roa);

/*=======================================================*/
/*			End of calculating Covariance - cov				*/
/*=======================================================*/

/*=======================================================*/
/*			Start of calculating Hs & Ks						*/
/*=======================================================*/

k_mtx=zeros(no_cols,no_cols);
e_mtx=zeros(no_cols,no_cols);

for h_row(1,no_cols,1);
	for h_col(1,no_cols,1);
		if h_row == no_cols;
			k_mtx[h_row,h_col] = 1;
			e_mtx[h_row,h_col] = 1;
		else;
			h_row_1 = h_row + 1;
			ev_1 = ev[h_row_1];
			cov1 = cov_[h_row_1, h_col];
			cov0 = cov_[h_row, h_col];
			
			k_mtx[h_row,h_col] = (ev[h_row] * 2 * cov1) - (ev_1 * 2 * cov0);
			e_mtx[h_row, h_col] = (2 * cov1) - (2 * cov0);
		endif;
	endfor;
endfor;
det_k_mtx = det(k_mtx);
det_e_mtx = det(e_mtx);

/*=======================================================*/
/*			End of calculating Hs & Ks						*/
/*=======================================================*/

/*=======================================================*/
/*		Start of calculating Optimal Budget Share (w_obs)		*/
/*=======================================================*/

sign_ = 1;

w_obs_arr_sum = 0;
w_D_obs_arr_sum = 0;

no_asset0 = no_asset;
no_asset1 = no_asset - 1;

w_mtx = zeros(no_asset1,no_asset1);
w_D_mtx = zeros(no_asset1,no_asset1);

w_obs_values = zeros(no_asset0,1);
w_D_obs_values = zeros(no_asset0,1);

for noOfAssets(1,no_asset0,1);
	w_col = 0;
	w_k_col = 1;
	w_row = 1;

	w_D_col = 0;
	w_D_E_col = 1;
	w_D_row = 1;

	for w_k_col(1, no_asset0,1);
		for w_row(1, no_asset1,1);

			if w_k_col < noOfAssets;
				w_col = w_k_col;
				w_D_col = w_D_E_col;
			elseif w_k_col == noOfAssets;
				If noOfAssets /= no_asset0;
					/*' skip this column*/
					w_col = w_k_col;
					w_D_col = w_D_E_col;
			else;						/*no_of_assets is on the last count and there is no need for checking the last column*/
				break;
				break;
				endif;
            
			else;						/* w_k_col > no_of_assets*/
				w_col = w_k_col - 1;
				w_D_col = w_D_E_col - 1;
			endif;
			w_mtx[w_row, w_col] = k_mtx[w_row, w_k_col];
                	w_D_mtx[w_row, w_col] = E_mtx[w_row, w_k_col];
		endfor;
		w_row = 1;
		w_D_row = 1;
	endfor;

	/*
	=====================================================================
	|								START								|
	|				Calculating the forula of Optimal Budget Share(w_obs)			|
	=====================================================================
	*/
	sign_p = noOfAssets + no_asset0;
	sign_ = (-1)^sign_p;
	
	det_w_mtx = det(w_mtx);
	det_w_D_mtx = det(w_D_mtx);

	w_obs_values0 = sign_ * (det_w_mtx / det_k_mtx);
	w_D_obs_values0 = sign_ * (det_w_D_mtx / det_e_mtx);

	w_obs_values[noOfAssets,1] = w_obs_values0;
	w_D_obs_values[noOfAssets,1] = w_D_obs_values0;

	w_obs_arr_sum = w_obs_arr_sum + w_obs_values0;
	w_D_obs_arr_sum = w_D_obs_arr_sum + w_D_obs_values0;

endfor;

/*=======================================================*/
/*		End of calculating Optimal Budget Share (w_obs)			*/
/*=======================================================*/

/*=======================================================*/
/*						START							*/
/*				Printing Few More Results					*/
/*=======================================================*/

/*>>>>>>>>>>>>>>>>>>>>>     Printing Average Return for the Portfolio (arp)     <<<<<<<<<<<<<<<<<<<<<<<<*/

ar_p = 0;
ar_p_c = 0;

for arp_loop(1,no_asset0,1);
    ar_p = ar_p + (w_obs_values[arp_loop] * ev[arp_loop]);
    ar_p_c = ar_p_c + (w_D_obs_values[arp_loop] * ev[arp_loop]);
endfor;

/*>>>>>>>>>>>>>>>>>>>>>     Printing Standard Deviation to the Portfolio     <<<<<<<<<<<<<<<<<<<<<<<<*/
sigma_p_ = 0;
sigma_p = 0;
sigma_p_c_ = 0;
sigma_p_c = 0;

just_row = 0;

for sd_i(1,no_asset0,1);
	for sd_j(1,no_asset0,1);

        w_sd_i = w_obs_values[sd_i];
        w_sd_j = w_obs_values[sd_j];
        
        w_D_sd_i = w_D_obs_values[sd_i];
        w_D_sd_j = w_D_obs_values[sd_j];
        
        sigma_p_ = sigma_p_ + (w_sd_i * w_sd_j * cov_[sd_i, sd_j]);
        sigma_p_c_ = sigma_p_c_ + (w_D_sd_i * w_D_sd_j * cov_[sd_i, sd_j]);
        
        just_row = just_row + 1;
	endfor;
endfor;

sigma_p = sqrt(sigma_p_);
sigma_p_c = sqrt(sigma_p_c_);
rar =0;
rar_p = 0;
rar_p_c = 0;

rar_p = ar_p / sigma_p;
rar_p_c = ar_p_c / sigma_p_c;

print "====================================================================================================================";
print "\t\t\t\t\t\t\t\t\t\t\t\tESTIMATION RESULTS";
print "====================================================================================================================";

/*>>>>>>>>>>>>>>>>>>>>>     Printing Details of Estimation Results <<<<<<<<<<<<<<<<<<<<<<<<*/

print "|\tAssets\t|\tAverage Return\t|\tStandar Deviation\t|\tRisk Adjusted Return\t|\t\tw for MV\t\t|\t\tw for MRAR\t|";
print "|\t------------\t|\t------------------------\t|\t------------------------------\t|\t-------------------------------------\t|\t  --------------------------\t|\t  ----------------------------\t|";

for asset_hd(1,no_asset0,1);
	rar = ev[asset_hd] /sd[asset_hd] ;
	print "|\t   " cvtos(data_lbl[asset_hd]) "\t|\t" ev[asset_hd] "\t|\t" sd[asset_hd] "\t|\t" rar "\t\t|\t" w_D_obs_values[asset_hd] "\t|\t" w_obs_values[asset_hd] "\t|";
endfor;

	print "|																													|";
	print "====================================================================================================================";
	print "";
	print "";
	print "============================================================================================================";
	print "|																											|";
	print "|\t\t\t\t\t\t\t\t\t\t\t|\tAverage Return\t|\tStandar Deviation\t|\tRisk Adjusted Return\t|";
	print "|\t\t\t\t\t\t\t\t\t\t\t|\t------------------------\t|\t------------------------------\t|\t-------------------------------------\t|";
	print "|Portfolio - Minimum Variance (MV)\t\t\t\t\t|\t" ar_p_c  "\t|\t" sigma_p_c "\t|\t" rar_p_c "\t\t|";
	print "|Portfolio - Maximum Risk Adjusted Return (MRAR)\t|\t" ar_p  "\t|\t" sigma_p "\t|\t" rar_p "\t\t|";
	print "|																											|";
	print "============================================================================================================";
	print "";

	print "";
	print "============================================================================================================";
	print "| References:																									|";
	print "| - Markowitz, H. (1952), Portfolio selection. Journal of Finance, 7 (1), 77-91.												|";
	print "| - Hatemi-J, A. and El-Khatib Y. (2015), Portfolio selection: An alternative approach. Economics Letters, 135, 141-143.				|";
	print "| - Hatemi-J, A., Hajji, M.A., and El-Khatib, Y. (2019), Exact Solution for the Portfolio Diversification	Problem Based on Maximizing 	|";
	print "| 	the Risk Adjusted Return. arXiv:1903.01082v1.																	|";
	print "|																											|";
	print "============================================================================================================";

/*=======================================================*/
/*						END								*/
/*				Printing Few More Results					*/
/*=======================================================*/