Will calculate the risk aversion factor that is the best fit for an observed pair of market portfolio
weights and equilibrium/historical excess returns.
426905
Scalar<?> calculateImpliedRiskAversion(final PrimitiveMatrix assetWeights, final PrimitiveMatrix assetReturns) {

        Scalar<?> retVal = myCovariances.multiply(assetWeights).solve(assetReturns).toScalar(0, 0);

        if (retVal.isSmall(PrimitiveMath.ONE)) {
            retVal = BigScalar.ONE;
        } else if (!retVal.isAbsolute()) {
            retVal = retVal.negate();
        }

        return retVal;
    }
286887
def infer_x(self, y, sigma=None, k=None, **kwargs):
        
        assert len(y) == self.fmodel.dim_y, "Wrong dimension for y. Expected %i, got %i" % (self.fmodel.dim_y, len(y))
        k = k or self.k
        sigma = sigma or self.sigma
        x_guess = self._guess_x(y, k = k)[0]
        dists, index = self.fmodel.dataset.nn_x(x_guess, k = k)
        w = self._weights(index, dists, sigma*sigma,  y)
        return [np.sum([wi*self.fmodel.dataset.get_x(idx)
                for wi, idx in zip(w, index)], axis = 0)]
792669
def _compute_acq(self, x):
        
        m, s = self.model.predict(x)
        fmin = self.model.get_fmin()
        phi, Phi, u = get_quantiles(self.jitter, fmin, m, s)
        f_acqu = s * (u * Phi + phi)
        return f_acqu
1152866
private Pair<Factor, Assignment> getRegressableFactorForFamily(BoostingFactorFamily family, VariableMatch match,
      List<Integer> conditionedVariables, MarginalSet marginals) {
    VariableNumMap marginalVars = match.getMatchedVariables().removeAll(conditionedVariables);
    VariableNumMap fixedVars = match.getMatchedVariables().intersection(conditionedVariables);
    Factor factorMarginal = marginals.getMarginal(marginalVars.getVariableNums())
        .relabelVariables(match.getMappingToTemplate());

    Assignment assignment = marginals.getConditionedValues().intersection(fixedVars)
        .mapVariables(match.getMappingToTemplate().getVariableIndexReplacementMap());

    VariableNumMap outerProductVars = family.getUnconditionalVariables().removeAll(factorMarginal.getVars());
    if (outerProductVars.size() > 0) {
      factorMarginal = factorMarginal.outerProduct(TableFactor.pointDistribution(outerProductVars,
          assignment.intersection(outerProductVars)));
      assignment = assignment.removeAll(outerProductVars.getVariableNumsArray());
    }

    return Pair.of(factorMarginal, assignment);
  }
907925
def calculate_generalized_advantage_estimator(
    reward, value, done, gae_gamma, gae_lambda):
  # pylint: disable=g-doc-args
  
  # pylint: enable=g-doc-args

  next_value = value[1:, :]
  next_not_done = 1 - tf.cast(done[1:, :], tf.float32)
  delta = (reward[:-1, :] + gae_gamma * next_value * next_not_done
           - value[:-1, :])

  return_ = tf.reverse(tf.scan(
      lambda agg, cur: cur[0] + cur[1] * gae_gamma * gae_lambda * agg,
      [tf.reverse(delta, [0]), tf.reverse(next_not_done, [0])],
      tf.zeros_like(delta[0, :]),
      parallel_iterations=1), [0])
  return tf.check_numerics(return_, "return")
723133
def drawdowns(returns, geometric=True):
    
    wealth = 1. + returns_cumulative(returns, geometric=geometric, expanding=True)
    values = wealth.values
    if values.ndim == 2:
        ncols = values.shape[-1]
        values = np.vstack(([1.] * ncols, values))
        maxwealth = pd.expanding_max(values)[1:]
        dds = wealth / maxwealth - 1.
        dds[dds > 0] = 0  # Can happen if first returns are positive
        return dds
    elif values.ndim == 1:
        values = np.hstack(([1.], values))
        maxwealth = pd.expanding_max(values)[1:]
        dds = wealth / maxwealth - 1.
        dds[dds > 0] = 0  # Can happen if first returns are positive
        return dds
    else:
        raise ValueError('unable to process array with %s dimensions' % values.ndim)
1164754
def K(self, X, X2, target):
        """"""
        if X2 is None: X2 = X
       # i1 = X[:,1]
       # i2 = X2[:,1]
       # X = X[:,0].reshape(-1,1)
       # X2 = X2[:,0].reshape(-1,1)
        dist = np.abs(X - X2.T)
        
        ly=1/self.lengthscaleY
        lu=np.sqrt(3)/self.lengthscaleU
        #ly=self.lengthscaleY
        #lu=self.lengthscaleU

        k1 = np.exp(-ly*dist)*(2*lu+ly)/(lu+ly)**2
        k2 = (np.exp(-lu*dist)*(ly-2*lu+lu*ly*dist-lu**2*dist) + np.exp(-ly*dist)*(2*lu-ly) ) / (ly-lu)**2 
        k3 = np.exp(-lu*dist) * ( (1+lu*dist)/(lu+ly) + (lu)/(lu+ly)**2 )

        np.add(self.varianceU*self.varianceY*(k1+k2+k3), target, target)
1174182
def Kdiag(self, X):
        """"""
        X_prod = self._comp_prod(X)
        return self.variance*four_over_tau*np.arcsin(X_prod/(X_prod+1.))
638107
def default_estimate(
    opt_meth: Type[OptimizationMethod], mo_prob: MOProblem, dp: int = 2
) -> Tuple[List[float], List[float]]:
    
    return round_off(estimate_payoff_table(opt_meth, mo_prob), dp)
503758
def expected_bar_value(asset_id, date, colname):
    
    from_asset = asset_id * 100000
    from_colname = OHLCV.index(colname) * 1000
    from_date = (date - PSEUDO_EPOCH).days
    return from_asset + from_colname + from_date
383777
@Override
    protected PrimitiveMatrix calculateAssetWeights() {

        if (this.getOptimisationOptions().logger_appender != null) {
            BasicLogger.debug();
            BasicLogger.debug("###################################################");
            BasicLogger.debug("BEGIN RAF: {} MarkowitzModel optimisation", this.getRiskAversion());
            BasicLogger.debug("###################################################");
            BasicLogger.debug();
        }

        Optimisation.Result tmpResult;

        if ((myTargetReturn != null) || (myTargetVariance != null)) {

            final double tmpTargetValue;
            if (myTargetVariance != null) {
                tmpTargetValue = myTargetVariance.doubleValue();
            } else if (myTargetReturn != null) {
                tmpTargetValue = myTargetReturn.doubleValue();
            } else {
                tmpTargetValue = _0_0;
            }

            tmpResult = this.generateOptimisationModel(_0_0).minimise();

            double tmpTargetNow = _0_0;
            double tmpTargetDiff = _0_0;
            double tmpTargetLast = _0_0;

            if (tmpResult.getState().isFeasible()) {

                double tmpCurrent;
                double tmpLow;
                double tmpHigh;
                if (this.isDefaultRiskAversion()) {
                    tmpCurrent = INIT;
                    tmpLow = MAX;
                    tmpHigh = MIN;
                } else {
                    tmpCurrent = this.getRiskAversion().doubleValue();
                    tmpLow = tmpCurrent * INIT;
                    tmpHigh = tmpCurrent / INIT;
                }

                do {

                    final ExpressionsBasedModel tmpModel = this.generateOptimisationModel(tmpCurrent);
                    tmpResult = tmpModel.minimise();

                    tmpTargetLast = tmpTargetNow;
                    if (myTargetVariance != null) {
                        tmpTargetNow = this.calculatePortfolioVariance(tmpResult).doubleValue();
                    } else if (myTargetReturn != null) {
                        tmpTargetNow = this.calculatePortfolioReturn(tmpResult, this.calculateAssetReturns()).doubleValue();
                    } else {
                        tmpTargetNow = tmpTargetValue;
                    }
                    tmpTargetDiff = tmpTargetNow - tmpTargetValue;

                    if (this.getOptimisationOptions().logger_appender != null) {
                        BasicLogger.debug();
                        BasicLogger.debug("RAF:   {}", tmpCurrent);
                        BasicLogger.debug("Last: {}", tmpTargetLast);
                        BasicLogger.debug("Now: {}", tmpTargetNow);
                        BasicLogger.debug("Target: {}", tmpTargetValue);
                        BasicLogger.debug("Diff:   {}", tmpTargetDiff);
                        BasicLogger.debug("Iteration:   {}", tmpResult);
                        BasicLogger.debug();
                    }

                    if (tmpTargetDiff < _0_0) {
                        tmpLow = tmpCurrent;
                    } else if (tmpTargetDiff > _0_0) {
                        tmpHigh = tmpCurrent;
                    }
                    tmpCurrent = PrimitiveMath.SQRT.invoke(tmpLow * tmpHigh);

                } while (!TARGET_CONTEXT.isSmall(tmpTargetValue, tmpTargetDiff) && TARGET_CONTEXT.isDifferent(tmpHigh, tmpLow));
            }

        } else {

            tmpResult = this.generateOptimisationModel(this.getRiskAversion().doubleValue()).minimise();

        }

        return this.handle(tmpResult);
    }
606028
public PrimitiveMatrix calculateAssetWeights(final PrimitiveMatrix assetReturns) {
        final PrimitiveMatrix tmpAssetWeights = myCovariances.solve(assetReturns);
        if (myRiskAversion.compareTo(DEFAULT_RISK_AVERSION) == 0) {
            return tmpAssetWeights;
        } else {
            return tmpAssetWeights.divide(myRiskAversion);
        }
    }
1297812
def obfn_fvarf(self):
        

        return self.Xf if self.opt['fEvalX'] else \
            sl.rfftn(self.Y, None, self.cri.axisN)
1369558
def __get_model_for_portfolio_value(input_model: PortfolioValueInputModel
        ) -> PortfolioValueViewModel:
    
    result = PortfolioValueViewModel()
    result.filter = input_model

    ref_datum = Datum()
    ref_datum.from_datetime(input_model.as_of_date)
    ref_date = ref_datum.end_of_day()

    result.stock_rows = []
    with BookAggregate() as svc:
        book = svc.book
        stocks_svc = svc.securities

        if input_model.stock:
            symbols = input_model.stock.split(",")
            stocks = stocks_svc.get_stocks(symbols)
        else:
            stocks = stocks_svc.get_all()

        for stock in stocks:
            row: StockViewModel = portfoliovalue.get_stock_model_from(
                book, stock, as_of_date=ref_date)
            if row and row.balance > 0:
                result.stock_rows.append(row)

    return result
924711
def obfn_fvar(self):
        

        if self.opt['fEvalX']:
            return self.X
        else:
            return self.cnst_c() - self.cnst_B(self.Y)
532801
def optimize(self, to_buy, to_sell):
        '''
        
        '''
        allocations = {}

        # Process every stock the same way
        for s in to_buy:
            quantity = self.properties.get('buy_amount', 100)
            if s in self.properties.get('scale', {}):
                quantity *= self.properties['scale'][s]
            # Allocate defined amount to buy
            allocations[s] = int(quantity)

        # NOTE You must provide sell_amount if you want to short
        for s in to_sell:
            quantity = self.properties.get(
                'sell_amount', self.portfolio.positions[s].amount)
            if s in self.properties.get('scale', {}):
                quantity *= self.properties['scale'][s]
            # Allocate defined amount to buy
            allocations[s] = -int(quantity)

        # Defaults values
        e_ret = 0
        e_risk = 1
        return allocations, e_ret, e_risk
415265
def print_portfolio_info(returns, avg_rets, weights):
    
    ret = (weights * avg_rets).sum()
    std = (weights * returns).sum(1).std()
    sharpe = ret / std
    print("Optimal weights:\n{}\n".format(weights))
    print("Expected return:   {}".format(ret))
    print("Expected variance: {}".format(std**2))
    print("Expected Sharpe:   {}".format(sharpe))