Forward-month returns of the replicating portfolio.
321685
def replicate(self):
        """"""
        return np.sum(
            self.proxies[self.window :] * self._xs[:-1], axis=1
        ).reindex(self.r.index)
752112
def rollback(self, date):
        """"""
        if self.onOffset(date):
            return date
        else:
            return date - QuarterBegin(month=self.month)
778948
def efficient_frontier(
        self,
        returns,
        cov_matrix,
        min_return,
        max_return,
        count
    ):
        

        columns = [coin for coin in self.SUPPORTED_COINS]
        # columns.append('Return')
        # columns.append('Risk')
        values = pd.DataFrame(columns=columns)
        weights = [1/len(self.SUPPORTED_COINS)] * len(self.SUPPORTED_COINS)

        def func(weights):
            """The objective function that minimizes variance."""
            return np.matmul(np.matmul(weights.transpose(), cov_matrix), weights)

        def func_deriv(weights):
            """The derivative of the objective function."""
            return (
                np.matmul(weights.transpose(), cov_matrix.transpose()) +
                np.matmul(weights.transpose(), cov_matrix)
            )

        for point in np.linspace(min_return, max_return, count):
            constraints = (
                {'type': 'eq', 'fun': lambda weights: (weights.sum() - 1)},
                {'type': 'ineq', 'fun': lambda weights, i=point: (
                    np.dot(weights, returns.values) - i
                )}
            )

            solution = self.solve_minimize(func, weights, constraints, func_deriv=func_deriv)

            columns = {}
            for index, coin in enumerate(self.SUPPORTED_COINS):
                columns[coin] = math.floor(solution.x[index] * 100 * 100) / 100

            # NOTE: These lines could be helpful, but are commented out right now.
            # columns['Return'] = round(np.dot(solution.x, returns), 6)
            # columns['Risk'] = round(solution.fun, 6)

            values = values.append(columns, ignore_index=True)

        return values
987207
@Override
	public RandomVariable getCovariance(int timeIndex, int component1, int component2, RandomVariable[] realizationAtTimeIndex) {

		RandomVariable volatilityOfComponent1 = volatilityModel.getVolatility(timeIndex, component1);
		RandomVariable volatilityOfComponent2 = volatilityModel.getVolatility(timeIndex, component2);

		double					correlationOfComponent1And2 = correlationModel.getCorrelation(timeIndex, component1, component2);

		RandomVariable covariance = volatilityOfComponent1.mult(volatilityOfComponent2).mult(correlationOfComponent1And2);

		return covariance;
	}
344248
def forward(self, observations):
        
        observations = self.input_block(observations)
        advantage_features, value_features = self.backbone(observations)
        q_values = self.q_head(advantage_features, value_features)

        return q_values
43004
def rollforward(self, date):
        """"""
        if self.onOffset(date):
            return date
        else:
            return date + YearEnd(month=self.month)
1174182
def Kdiag(self, X):
        """"""
        X_prod = self._comp_prod(X)
        return self.variance*four_over_tau*np.arcsin(X_prod/(X_prod+1.))
93905
def profit_money(self):
        

        return float(round(self.assets.iloc[-1] - self.assets.iloc[0], 2))
611102
def rshares_to_steem (self, rshares):
        ''' 
        '''
        self.reward_pool_balances()
        return round(
            rshares 
            * self.reward_balance 
            / self.recent_claims 
            * self.base, 4)
35113
@Override
	public RandomVariable getForward(AnalyticModel model, double fixingTime, double paymentOffset)
	{
		if(model==null) {
			throw new IllegalArgumentException(this.getName() + ": model==null");
		}
		DiscountCurveInterface referenceDiscountCurveForForwards = model.getDiscountCurve(referenceDiscountCurveForForwardsName); // do not use discountCurveName here (usually this is an OIS curve)
		if(referenceDiscountCurveForForwards==null) {
			throw new IllegalArgumentException(this.getName() + ": referenceDiscountCurveForForwards " + referenceDiscountCurveForForwardsName + " not found in the model:\n" + model.toString());
		}
		if(Double.isNaN(paymentOffset) || paymentOffset<=0.0) {
			throw new IllegalArgumentException(this.getName() + ": Requesting forward with paymentOffset " + paymentOffset + " not allowed.");
		}

		double daycount = paymentOffset * daycountScaling;
		return referenceDiscountCurveForForwards.getDiscountFactor(model, fixingTime+periodOffset).div(referenceDiscountCurveForForwards.getDiscountFactor(model, fixingTime+paymentOffset+periodOffset)).sub(1.0).div(daycount);
	}
1092195
def trade(args):
    """"""
    print args
    print vars(args)['funds']
    print args.funds
    portfolio = { '$CASH': args.funds }
    print portfolio
    csvreader = csv.reader(args.infile, dialect='excel', quoting=csv.QUOTE_MINIMAL)
    csvwriter = csv.writer(args.outfile, dialect='excel', quoting=csv.QUOTE_MINIMAL)
    detailed = not args.simple
    history = []
    portfolio_history = []

    #trading_days = du.getNYSEdays(datetime.datetime(2010,01,01), datetime.datetime(2012,01,01), datetime.timedelta(hours=16))
    for row in csvreader:
        # print '-'*30 + ' CSV Row ' + '-'*30
        # print ', '.join(row)
        trade_date = datetime.datetime(*[int(i) for i in (row[:3] + [16])])

        if history:
            last_date = datetime.datetime(*(history[-1][:3] + [16])) + datetime.timedelta(days=1)
            # print (date.date() - last_date).days
            while (trade_date - last_date).days > 0:
                print 'Filling in the blanks for {0}'.format(last_date)
                value = portfolio_value(portfolio, last_date, price='close')
                print '   the portfolio value on that date is: {0}'.format(value)
                assert(value != None)
                # NaN for porfolio value indicates a non-trading day
                if not np.isnan(value):
                    history += [[last_date.year, last_date.month, last_date.day] 
                                + (["$CASH", "0.0", "0.0"] if args.trades else [])
                                + ([json.dumps(portfolio)] if detailed else []) + [value]]
                    portfolio_history += [datetime.datetime(last_date.year, last_date.month, last_date.day, 16), portfolio]
                    csvwriter.writerow(history[-1])
                last_date += datetime.timedelta(days=1)
    
        trade_symbol = row[3]
        trade_shares = float(row[5])
        trade_sign = 1 - 2 * int(row[4].strip().upper()[0]=='S')
        # If this the first row in the CSV and the symbol is $CASH then it represents an initial deposit (Sell) or withdrawal (Buy) of cash
        # otherwise se need to add or deduct whatever security was bought or sold.
        # if not (trade_symbol == '$CASH') or history:
        portfolio[trade_symbol] = portfolio.get(trade_symbol, 0) + trade_sign * trade_shares
        trade_price = get_price(symbol=trade_symbol, date=trade_date, price='close')
        while trade_price == None or np.isnan(trade_price) or float(trade_price) == float('nan'):
            trade_date += datetime.timedelta(days=1)
            trade_price = get_price(symbol=trade_symbol, date=trade_date, price='close')
        #print trade_date, trade_symbol, trade_sign, trade_shares, trade_price
        if trade_price and trade_shares and trade_sign in (-1, 1):
            print 'spending cash: {0}'.format(trade_sign * trade_shares * trade_price)
            portfolio['$CASH'] = portfolio.get('$CASH',0.) - trade_sign * trade_shares * trade_price
        else:
            print 'ERROR: bad price, sign, shares: ', trade_price, trade_sign, trade_shares
        history += [[trade_date.year, trade_date.month, trade_date.day, trade_symbol, trade_sign, trade_shares] + ([json.dumps(portfolio)] if detailed else []) + [portfolio_value(portfolio, trade_date, price='close')]]
        csvwriter.writerow(history[-1])
    return metrics(history)
982667
def view_portfolio_loss(token, dstore):
    
    data = portfolio_loss(dstore)  # shape (R, L)
    loss_types = list(dstore['oqparam'].loss_dt().names)
    header = ['portfolio_loss'] + loss_types
    mean = ['mean'] + [row.mean() for row in data.T]
    stddev = ['stddev'] + [row.std(ddof=1) for row in data.T]
    return rst_table([mean, stddev], header)
555940
def hybrid_forward(self, F, x, sampled_values, label, w_all, b_all):
        """"""
        sampled_candidates, expected_count_sampled, expected_count_true = sampled_values
        # (num_sampled, in_unit)
        w_sampled = w_all.slice(begin=(0, 0), end=(self._num_sampled, None))
        w_true = w_all.slice(begin=(self._num_sampled, 0), end=(None, None))
        b_sampled = b_all.slice(begin=(0,), end=(self._num_sampled,))
        b_true = b_all.slice(begin=(self._num_sampled,), end=(None,))
        # true pred
        # (batch_size, 1)
        x = x.reshape((-1, self._in_unit))
        pred_true = (w_true * x).sum(axis=1) + b_true
        # samples pred
        # (batch_size, num_sampled)
        b_sampled = F.reshape(b_sampled, (-1,))
        pred_sampled = F.FullyConnected(x, weight=w_sampled, bias=b_sampled,
                                        num_hidden=self._num_sampled)

        # remove accidental hits
        if self._remove_accidental_hits:
            label_vec = F.reshape(label, (-1, 1))
            sample_vec = F.reshape(sampled_candidates, (1, -1))
            mask = F.broadcast_equal(label_vec, sample_vec) * -1e37
            pred_sampled = pred_sampled + mask

        # subtract log(q)
        expected_count_sampled = F.reshape(expected_count_sampled,
                                           shape=(1, self._num_sampled))
        expected_count_true = expected_count_true.reshape((-1,))
        pred_true = pred_true - F.log(expected_count_true)
        pred_true = pred_true.reshape((-1, 1))
        pred_sampled = F.broadcast_sub(pred_sampled, F.log(expected_count_sampled))

        # pred and new_labels
        # (batch_size, 1+num_sampled)
        pred = F.concat(pred_true, pred_sampled, dim=1)
        if self._sparse_label:
            new_label = F.zeros_like(label)
        else:
            label_vec = F.reshape(label, (-1, 1))
            new_label_true = F.ones_like(label_vec)
            new_label_sampled = F.zeros_like(pred_sampled)
            new_label = F.Concat(new_label_true, new_label_sampled, dim=1)
        return pred, new_label
198858
function incrmvariance( W ) {
	if ( !isPositiveInteger( W ) ) {
		throw new TypeError( 'incrmvariance()::invalid input argument. Window size must be a positive integer. Value: `' + W + '`.' );
	}
	var arr = new Array( W ),
		n = W - 1,
		M2 = 0,
		mu = 0,
		N = 0,
		i = -1,
		delta,
		tmp,
		d1,
		d2;
	/**
	* FUNCTION: incrmvariance( [value] )
	*	If a `value` is provided, updates and returns the updated sample variance. If no `value` is provided, returns the current sample variance.
	*
	* @param {Number} [value] - value used to update the moving sample variance
	* @returns {Number|Null} sample variance or null
	*/
	return function incrmvariance( x ) {
		if ( !arguments.length ) {
			if ( N === 0 ) {
				return null;
			}
			if ( N === 1 ) {
				return 0;
			}
			if ( N < W ) {
				return M2 / (N-1);
			}
			return M2 / n;
		}
		// Update the index for managing the circular buffer...
		i = (i+1) % W;

		// Fill up the initial window; else, update the existing window...
		if ( N < W ) {
			arr[ i ] = x;
			N += 1;
			delta = x - mu;
			mu += delta / N;
			M2 += delta * (x - mu);
			if ( N === 1 ) {
				return 0;
			}
			return M2 / (N-1);
		}
		if ( N === 1 ) {
			return 0;
		}
		tmp = arr[ i ];
		arr[ i ] = x;
		delta = x - tmp;
		d1 = tmp - mu;
		mu += delta / W;
		d2 = x - mu;
		M2 += delta * (d1 + d2);

		return M2 / n;
	};
}
757089
def portfolio(self) -> List[PortfolioItem]:
        
        account = self.wrapper.accounts[0]
        return [v for v in self.wrapper.portfolio[account].values()]
220493
def hybrid_forward(self, F, x):
        """"""
        f = self._factor
                                             # (N, C*f, W)
        x = F.reshape(x, (0, -4, -1, f, 0))  # (N, C, f, W)
        x = F.transpose(x, (0, 1, 3, 2))     # (N, C, W, f)
        x = F.reshape(x, (0, 0, -3))         # (N, C, W*f)
        return x
410377
def update(self, portfolio, date, perfs=None):
        '''
        
        '''
        # Make the manager aware of current simulation
        self.portfolio = portfolio
        self.perfs = perfs
        self.date = date