www.gusucode.com > GAVPai_Book_MathworksCntrlFileEx_May2019 > GAVPai_Book_MathworksCntrlFileEx_May2019/adjustPosNegWgts_lowbounds.m

    
% standardize lower bounds

function [ PosWgt_Adj,NegWgt_Adj, UPBOUNDS_FLAG ] = adjustPosNegWgts_lowbounds( 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 fell below their lower bound and are now adjusted

R=[];
c_R=0;
DEPOSIT = 0;
EPSILON = 0.0001;
for i=1:col_vec   
    if ((First_Weights(1,i)~=0) &&(First_Weights(1,i) < lowupbounds(1,i))) 
        DEFICIT = (lowupbounds(1,i)-First_Weights(1,i));
        DEPOSIT = DEPOSIT - DEFICIT;
        First_Weights(1,i) = lowupbounds(1,i);
        c_R = c_R+1;
        R(c_R) = i;  
    end
end

% Q: those weights which satisfy their lower bounds
Q = setdiff(1:col_vec, R);
sharing_wgts = sum(First_Weights(1,Q)~=0);
if (sharing_wgts ~=0)
    redistr_share = DEPOSIT/(sharing_wgts);
    [~,t] = size(Q);

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

if (abs(DEPOSIT) > EPSILON)
    clear  redistr_share
    non_zero_wgts = sum(Second_Weights(1,:)~=0);
    if (Signal ==1)
                redistr_share = DEPOSIT/(a*non_zero_wgts);           
    else
                redistr_share = (DEPOSIT/non_zero_wgts);  
        
    end
    for i=1:col_vec   
                if (Second_Weights(1,i) ~= 0) 
                    Second_Weights(1,i) = Second_Weights (1,i) + abs(redistr_share);
                end
    end
                
end

UPBOUNDS_FLAG =1;
for j=1:col_vec
    if ((Second_Weights(1,j)~=0)&&(Second_Weights(1,j) > lowupbounds(2,j))) 
    UPBOUNDS_FLAG = 0;
    end
end;
if (Signal ==1)
    PosWgt_Adj = First_Weights; 
    NegWgt_Adj = Second_Weights;
else
    PosWgt_Adj = Second_Weights;
    NegWgt_Adj = First_Weights;   
end
end