function f = krgPortfolioOptimizer(x,Lambda,C,tradeData,PortfolioDollars,k,scenario)
%KRGPORTFOLIOOPTIMIZER Example objective function for KRGPORTFOLIOOPTIMIZATIONEXAMPLE.
%   F = KRGPORTFOLIOOPTIMIZER(X,LAMBDA,C,TRADEDATA,PORTFOLIODOLLARS,K,SCENARIO)
%   returns value based on optimization scenario choice, SCENARIO.   LAMBDA
%   is the risk aversion value, C is the covariance array, TRADEDATA is the
%   portfolio data, PORTFOLIODOLLARS is the value of the portfolio, K is
%   the KRG object.

%   Copyright 2016-2020 The MathWorks, Inc.

% Calculate Shares from weights, portfolio value, and stock price
% Market impact cost is always positive and based on positive shares
% quantities.
tradeData.Shares = abs(x * PortfolioDollars ./ tradeData.Price);

% ADV factor in TradeTime is different than tradetime2pov calc.
tradeData.TradeTime = tradeData.TradeTime .* tradeData.ADV;
tradeData.POV = krg.tradetime2pov(tradeData.TradeTime,tradeData.Shares);

% marketImpact calculation, convert from bp to decimal
MI = marketImpact(k,tradeData)/10000;

% Calculate return value based on scenario choice
switch scenario
  
  case 1 

    % Scenario #1: Maximize Returns - Lambda*Risk 
    f = -(tradeData.EstReturn' * x - MI' * abs(x)) + Lambda * x' * C * x; 

  case 2 

    % Scenario #2: Minimize Risk subject to Net Returns >= minReturn 
    f = x' * C * x; 

  case 3 

    % Scenario #3: Max NetReturn subject to Risk <= maxRisk 
    f = -(tradeData.EstReturn' * x - MI' * abs(x));   

end