gusucode.com > GAVPai_Book_MathworksCntrlFileEx_May2019 > GAVPai_Book_MathworksCntrlFileEx_May2019/adjustPosNegWgts_upbounds.m

    % standardize upper bounds

function [ PosWgt_Adj, NegWgt_Adj ] = adjustPosNegWgts_upbounds( PosWgtsVec, NegWgtsVec, lowupbounds, Signal, a )
[~, col_vec]= size(PosWgtsVec);
 

% Whichever category (buy or sell) exceeds its sum of weights is
% First_Weights, the other is Second_Weights
if (Signal ==1)
    First_Weights = PosWgtsVec;   % Test and adjust positive weights first
    Second_Weights = NegWgtsVec;
else
    First_Weights = NegWgtsVec;   % Test and adjust negative weights first
    Second_Weights = PosWgtsVec;
end

% R: those weights that exceeded their upper bounds and are now adjusted

R=[];
c_R=0;
DEPOSIT = 0;
EPSILON = 0.0001;
for i=1:col_vec   
    if ((Second_Weights(1,i)~=0) && (Second_Weights(1,i) > lowupbounds(2,i))) 
        EXCESS = (-lowupbounds(2,i)+Second_Weights(1,i));
        DEPOSIT = DEPOSIT + EXCESS;
        Second_Weights(1,i) = lowupbounds(2,i);
        c_R = c_R+1;
        R(c_R) = i;  
    end
end

% Q: those weights which satisfy their upper bounds 
Q = setdiff([1:col_vec], R);  
sharing_wgts = sum(Second_Weights(1,Q)~=0);
if (sharing_wgts ~=0)
    if (Signal==1)
        redistr_share = DEPOSIT/(a * sharing_wgts);
    else 
        redistr_share = DEPOSIT/ sharing_wgts;
    end
    [~,t] = size(Q);


    for i=1:t
    if (Second_Weights(1,Q(i))>0)&&((Second_Weights(1,Q(i))+redistr_share)<= lowupbounds(2,Q(i)))
        Second_Weights(1,Q(i)) = Second_Weights(1, Q(i)) + redistr_share;
        DEPOSIT = DEPOSIT-redistr_share;
        if ((DEPOSIT) <= EPSILON) 
        break;
        else continue;
        end
    end
    end
end

if (DEPOSIT > EPSILON) 
    
    actual_total = sum(First_Weights(1,:));
    NZ_FirstWeights_Indx = find(First_Weights(1,:));
    total = actual_total -(DEPOSIT/a)-sum(lowupbounds(1,NZ_FirstWeights_Indx));
    for i=1:col_vec   
    if (First_Weights(1,i) ~= 0)

        proportion = (First_Weights(1,i)/actual_total)*total;
        First_Weights(1,i) = lowupbounds(1,i) + proportion;
    end

    end               
end
if (Signal ==1)
    PosWgt_Adj = First_Weights; 
    NegWgt_Adj = Second_Weights;
else
    PosWgt_Adj = Second_Weights;
    NegWgt_Adj = First_Weights;   
end
           
end