If the input vector of asset weights are the weights of the market portfolio, then the ouput is the
equilibrium excess returns.
170008
public PrimitiveMatrix calculateAssetReturns(final PrimitiveMatrix assetWeights) {
        final PrimitiveMatrix tmpAssetWeights = myRiskAversion.compareTo(DEFAULT_RISK_AVERSION) == 0 ? assetWeights : assetWeights.multiply(myRiskAversion);
        return myCovariances.multiply(tmpAssetWeights);
    }
634176
private function equaliseWeight(PackedBox &$boxA, PackedBox &$boxB, float $targetWeight): bool
    {
        $anyIterationSuccessful = false;

        if ($boxA->getWeight() > $boxB->getWeight()) {
            $overWeightBox = $boxA;
            $underWeightBox = $boxB;
        } else {
            $overWeightBox = $boxB;
            $underWeightBox = $boxA;
        }

        $overWeightBoxItems = $overWeightBox->getItems()->asItemArray();
        $underWeightBoxItems = $underWeightBox->getItems()->asItemArray();

        foreach ($overWeightBoxItems as $key => $overWeightItem) {
            if ($overWeightItem->getWeight() + $boxB->getWeight() > $targetWeight) {
                continue; // moving this item would harm more than help
            }

            $newLighterBoxes = $this->doVolumeRepack(array_merge($underWeightBoxItems, [$overWeightItem]));
            if (count($newLighterBoxes) !== 1) {
                continue; //only want to move this item if it still fits in a single box
            }

            $underWeightBoxItems[] = $overWeightItem;

            if (count($overWeightBoxItems) === 1) { //sometimes a repack can be efficient enough to eliminate a box
                $boxB = $newLighterBoxes->top();
                $boxA = null;

                return true;
            } else {
                unset($overWeightBoxItems[$key]);
                $newHeavierBoxes = $this->doVolumeRepack($overWeightBoxItems);
                if (count($newHeavierBoxes) !== 1) {
                    continue;
                }

                if ($this->didRepackActuallyHelp($boxA, $boxB, $newHeavierBoxes->top(), $newLighterBoxes->top())) {
                    $boxB = $newLighterBoxes->top();
                    $boxA = $newHeavierBoxes->top();
                    $anyIterationSuccessful = true;
                }
            }
        }

        return $anyIterationSuccessful;
    }
145045
public SDVariable weightedCrossEntropyWithLogits(String name, SDVariable targets, SDVariable inputs,
                                                     SDVariable weights) {
        validateFloatingPoint("weighted cross entropy with logits", "inputs", inputs);
        validateNumerical("weighted cross entropy with logits", "targets", targets);
        SDVariable result = f().weightedCrossEntropyWithLogits(targets, inputs, weights);
        result = updateVariableNameAndReference(result, name);
        result.markAsLoss();
        return result;
    }
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);
        }
    }
1256722
def override_account_fields(self,
                                settled_cash=not_overridden,
                                accrued_interest=not_overridden,
                                buying_power=not_overridden,
                                equity_with_loan=not_overridden,
                                total_positions_value=not_overridden,
                                total_positions_exposure=not_overridden,
                                regt_equity=not_overridden,
                                regt_margin=not_overridden,
                                initial_margin_requirement=not_overridden,
                                maintenance_margin_requirement=not_overridden,
                                available_funds=not_overridden,
                                excess_liquidity=not_overridden,
                                cushion=not_overridden,
                                day_trades_remaining=not_overridden,
                                leverage=not_overridden,
                                net_leverage=not_overridden,
                                net_liquidation=not_overridden):
        
        # mark that the portfolio is dirty to override the fields again
        self._dirty_account = True
        self._account_overrides = kwargs = {
            k: v for k, v in locals().items() if v is not not_overridden
        }
        del kwargs['self']
792936
def _compute_acq_withGradients(self, x):
        
        m, s, dmdx, dsdx = self.model.predict_withGradients(x) 
        f_acqu = -m + self.exploration_weight * s       
        df_acqu = -dmdx + self.exploration_weight * dsdx
        return f_acqu, df_acqu
266915
@Override
  public void put(double val, double weight) {
    if(weight == 0.) {
      return;
    }
    if(n <= 0) {
      n = weight;
      sum = val * weight;
      return;
    }
    val *= weight;
    final double tmp = n * val - sum * weight;
    final double oldn = n; // tmp copy
    n += weight;
    sum += val;
    m2 += tmp * tmp / (weight * n * oldn);
  }
541724
def return_on_initial_capital(capital, period_pl, leverage=None):
    """"""
    if capital <= 0:
        raise ValueError('cost must be a positive number not %s' % capital)
    leverage = leverage or 1.
    eod = capital + (leverage * period_pl.cumsum())
    ltd_rets = (eod / capital) - 1.
    dly_rets = ltd_rets
    dly_rets.iloc[1:] = (1. + ltd_rets).pct_change().iloc[1:]
    return dly_rets
697645
function constrainedMDSGradient(x, fxprime, distances, constraints) {
        var loss = 0, i;
        for (i = 0; i < fxprime.length; ++i) {
            fxprime[i] = 0;
        }

        for (i = 0; i < distances.length; ++i) {
            var xi = x[2 * i], yi = x[2 * i + 1];
            for (var j = i + 1; j < distances.length; ++j) {
                var xj = x[2 * j], yj = x[2 * j + 1],
                    dij = distances[i][j],
                    constraint = constraints[i][j];

                var squaredDistance = (xj - xi) * (xj - xi) + (yj - yi) * (yj - yi),
                    distance$$1 = Math.sqrt(squaredDistance),
                    delta = squaredDistance - dij * dij;

                if (((constraint > 0) && (distance$$1 <= dij)) ||
                    ((constraint < 0) && (distance$$1 >= dij))) {
                    continue;
                }

                loss += 2 * delta * delta;

                fxprime[2*i]     += 4 * delta * (xi - xj);
                fxprime[2*i + 1] += 4 * delta * (yi - yj);

                fxprime[2*j]     += 4 * delta * (xj - xi);
                fxprime[2*j + 1] += 4 * delta * (yj - yi);
            }
        }
        return loss;
    }
263814
def SetBalanceFor(self, assetId, fixed8_val):
        
        found = False
        for key, val in self.Balances.items():
            if key == assetId:
                self.Balances[key] = fixed8_val
                found = True

        if not found:
            self.Balances[assetId] = fixed8_val
1259908
public void plus(LinearSparseVector sv, float w) {
		if (sv == null)
			return;
		for (int i = 0; i < sv.length; i++) {
			float val = (float) sv.data[i] * w;
			add(sv.index[i], val);
		}
	}
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;
    }
1260598
private void adjustWeights() {
        for (int l = 1; l < net.length; l++) {
            for (int i = 0; i < net[l].units; i++) {
                for (int j = 0; j <= net[l - 1].units; j++) {
                    double out = net[l - 1].output[j];
                    double err = net[l].error[i];
                    double delta = (1 - alpha) * eta * err * out + alpha * net[l].delta[i][j];
                    net[l].delta[i][j] = delta;
                    net[l].weight[i][j] += delta;
                    if (lambda != 0.0 && j < net[l-1].units) {
                        net[l].weight[i][j] *= (1.0 - eta * lambda);
                    }
                }
            }
        }
    }
93905
def profit_money(self):
        

        return float(round(self.assets.iloc[-1] - self.assets.iloc[0], 2))
567372
def hmean(x, weights=None):
    
    w_arr, x_arr = _preprocess_inputs(x, weights)
    return w_arr.sum(axis=0) / (w_arr/x_arr).sum(axis=0)
126419
@Override
	public double varianceOfStockPrice(double time) {
		return Math.pow(initialValue, 2) * Math.exp(2 * riskFreeRate * time)
				* (Math.exp(Math.pow(volatility, 2) * time) - 1);
	}
755970
private Data<Input, Output> derive_(Input input) {
        Data<Input, Output> result = new Data<>(input, fn_.apply(input));
        recent_.set(result);
        return result;
    }