compute the returns for the specified prices.
     method: [simple,compound,log], compound is log
542481
def returns(prices, method='simple', periods=1, fill_method='pad', limit=None, freq=None):
    
    if method not in ('simple', 'compound', 'log'):
        raise ValueError("Invalid method type. Valid values are ('simple', 'compound')")

    if method == 'simple':
        return prices.pct_change(periods=periods, fill_method=fill_method, limit=limit, freq=freq)
    else:
        if freq is not None:
            raise NotImplementedError("TODO: implement this logic if needed")

        if isinstance(prices, pd.Series):
            if fill_method is None:
                data = prices
            else:
                data = prices.fillna(method=fill_method, limit=limit)

            data = np.log(data / data.shift(periods=periods))
            mask = pd.isnull(prices.values)
            np.putmask(data.values, mask, np.nan)
            return data
        else:
            return pd.DataFrame(
                {name: returns(col, method, periods, fill_method, limit, freq) for name, col in prices.iteritems()},
                columns=prices.columns,
                index=prices.index)
376694
void log(ECoordinate v) {
		double d = v.m_eps / v.m_value;
		m_value = Math.log(v.m_value);
		m_eps = d * (1.0 + 0.5 * d) + epsCoordinate() * Math.abs(m_value);
	}
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)
639173
def step(self):
        
        logy = self.loglike - rexponential(1)

        L = self.stochastic.value - runiform(0, self.w)
        R = L + self.w

        if self.doubling:
            # Doubling procedure
            K = self.m
            while (K and (logy < self.fll(L) or logy < self.fll(R))):
                if random() < 0.5:
                    L -= R - L
                else:
                    R += R - L
                K -= 1
        else:
            # Stepping out procedure
            J = np.floor(runiform(0, self.m))
            K = (self.m - 1) - J
            while(J > 0 and logy < self.fll(L)):
                L -= self.w
                J -= 1
            while(K > 0 and logy < self.fll(R)):
                R += self.w
                K -= 1

        # Shrinkage procedure
        self.stochastic.value = runiform(L, R)
        try:
            logy_new = self.loglike
        except ZeroProbability:
            logy_new = -np.infty
        while(logy_new < logy):
            if (self.stochastic.value < self.stochastic.last_value):
                L = float(self.stochastic.value)
            else:
                R = float(self.stochastic.value)
            self.stochastic.revert()
            self.stochastic.value = runiform(L, R)
            try:
                logy_new = self.loglike
            except ZeroProbability:
                logy_new = -np.infty
841061
function lagrange(at, x, y){
	var sum = 0,
		product, 
		i, j;
		
	for(var i=0, len = x.length; i<len; i++){
		if(!y[i]){
			continue; 
		}
			
		product = config.logs[y[i]];
		for(var j=0; j<len; j++){
			if(i === j){ continue; }
			if(at === x[j]){ // happens when computing a share that is in the list of shares used to compute it
				product = -1; // fix for a zero product term, after which the sum should be sum^0 = sum, not sum^1
				break; 
			}
			product = ( product + config.logs[at ^ x[j]] - config.logs[x[i] ^ x[j]] + config.max/* to make sure it's not negative */ ) % config.max;
		}
			
		sum = product === -1 ? sum : sum ^ config.exps[product]; // though exps[-1]= undefined and undefined ^ anything = anything in chrome, this behavior may not hold everywhere, so do the check
	}
	return sum;
}
686993
def _calc_cost(self, *args, **kwargs):
        

        return np.sum([op.cost(*args, **kwargs) for op in self._operators])
985378
def calculateOptionPrice(self, reqId, contract, volatility, underPrice):
        """"""
        return _swigibpy.EClient_calculateOptionPrice(self, reqId, contract, volatility, underPrice)
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))
983699
def _computeP(self):
        
        P = []
        for i in range(self.width):
            #print i,
            _p = {}
            for L in ACGT: _p[L] = math.pow(2.0,self.logP[i][L])
            P.append(_p)
        #print
        self.P = P
318163
def calculateOptionPrice(self, reqId, contract, volatility, underPrice):
        """"""
        return _swigibpy.EClientSocketBase_calculateOptionPrice(self, reqId, contract, volatility, underPrice)
1076423
def compute(self, base, *args, **kwargs):
        '''
        
        '''
        return min(base, super(Discount, self).compute(base, *args, **kwargs))
163921
def _compute(self):
        
        r = self
        for func, args, kwargs in self._todo:
            r = func(self)(*args, **kwargs)
        return r
169788
def recalculate_stock_values_into_base(self):
        
        from .currency import CurrencyConverter

        conv = CurrencyConverter()
        cash = self.model.get_cash_asset_class()

        for stock in self.model.stocks:
            if stock.currency != self.base_currency:
                # Recalculate into base currency
                conv.load_currency(stock.currency)
                assert isinstance(stock.value, Decimal)
                val_base = stock.value * conv.rate.value
            else:
                # Already in base currency.
                val_base = stock.value

            stock.value_in_base_currency = val_base
1340020
def compute_taxes(self, precision=None):
        '''
        
        '''
        base = self.gross - self.total_discounts
        return quantize(sum([t.compute(base, precision) for t in self.__taxes]),
                        precision)
895183
def compute(self, x):
        '''
        
        '''
        q_learning = copy(self.__greedy_q_learning)
        q_learning.epsilon_greedy_rate = x[0]
        q_learning.alpha_value = x[1]
        q_learning.gamma_value = x[2]
        if self.__init_state_key is not None:
            q_learning.learn(state_key=self.__init_state_key, limit=int(x[3]))
        else:
            q_learning.learn(limit=x[3])
        q_sum = q_learning.q_df.q_value.sum()
        if q_sum != 0:
            cost = q_learning.q_df.shape[0] / q_sum
        else:
            cost = q_learning.q_df.shape[0] / 1e-4

        return cost
1094037
def _calculate_price_by_slippage(self, action: str, price: float) -> float:
        
        if action == "buy":
            return price * (1 + self.slippage)
        if action == "sell":
            return price * (1 - self.slippage)
        return price
557424
def given(self):
        """"""
        if self._primary.value[0] and self._primary.value[2]:
            return self._primary.value[0] + ' ' + self._primary.value[2]
        return self._primary.value[0] or self._primary.value[2]