Returns an efficient portfolio allocation for the given risk index.
960537
def allocate(self):
        
        df = self.manager.get_historic_data()[self.SUPPORTED_COINS]

        #==== Calculate the daily changes ====#
        change_columns = []
        for column in df:
            if column in self.SUPPORTED_COINS:
                change_column = '{}_change'.format(column)
                values = pd.Series(
                    (df[column].shift(-1) - df[column]) /
                    -df[column].shift(-1)
                ).values
                df[change_column] = values
                change_columns.append(change_column)

        # print(df.head())
        # print(df.tail())

        #==== Variances and returns ====#
        columns = change_columns
        # NOTE: `risks` is not used, but may be used in the future
        risks = df[columns].apply(np.nanvar, axis=0)
        # print('\nVariance:\n{}\n'.format(risks))
        returns = df[columns].apply(np.nanmean, axis=0)
        # print('\nExpected returns:\n{}\n'.format(returns))

        #==== Calculate risk and expected return ====#
        cov_matrix = df[columns].cov()
        # NOTE: The diagonal variances weren't calculated correctly, so here is a fix.
        cov_matrix.values[[np.arange(len(self.SUPPORTED_COINS))] * 2] = df[columns].apply(np.nanvar, axis=0)
        weights = np.array([1/len(self.SUPPORTED_COINS)] * len(self.SUPPORTED_COINS)).reshape(len(self.SUPPORTED_COINS), 1)

        #==== Calculate portfolio with the minimum risk ====#
        min_risk = self.get_min_risk(weights, cov_matrix)
        min_return = np.dot(min_risk, returns.values)

        #==== Calculate portfolio with the maximum return ====#
        max_return = self.get_max_return(weights, returns)

        #==== Calculate efficient frontier ====#
        frontier = self.efficient_frontier(
            returns, cov_matrix, min_return, max_return, 6
        )
        return frontier
399190
def randiter(iterable):
    '''
'''

    iter_len = len(iterable)

    for index in xrandrange(iter_len):
        yield iterable[index]
482131
def build(values):
		'''
		
		'''
		idxstore = IndexStore()
		idxstore._i2val = list(values)
		idxstore._val2i = {term:i for i,term in enumerate(values)}
		idxstore._next_i = len(values)
		return idxstore
745531
def efficient_frontier(self, points):
        """"""
        mu, sigma, weights = [], [], []
        # remove the 1, to avoid duplications
        a = np.linspace(0, 1, points / len(self.w))[:-1]
        b = list(range(len(self.w) - 1))
        for i in b:
            w0, w1 = self.w[i], self.w[i + 1]
            if i == b[-1]:
                # include the 1 in the last iteration
                a = np.linspace(0, 1, points / len(self.w))
            for j in a:
                w = w1 * j + (1 - j) * w0
                weights.append(np.copy(w))
                mu.append(np.dot(w.T, self.mean)[0, 0])
                sigma.append(np.dot(np.dot(w.T, self.cov_matrix), w)[0, 0] ** 0.5)
        return mu, sigma, weights
1241428
def _get_index(n_items, item_size, n):
    """"""
    index = np.arange(n_items)
    index = np.repeat(index, item_size)
    index = index.astype(np.float64)
    assert index.shape == (n,)
    return index
486272
def _get_index_list_of_values(d, k, def_value=None):
    """"""
    v = d.get(k, def_value)
    if v is None:
        return []
    if isinstance(v, list):
        return v
    return [v]
44985
def get_value_index(self, indices):
        
        size = self['size'] if self.get('size') else self['dimension']['size']
        ndims = len(size)
        mult = 1
        num = 0
        for idx, dim in enumerate(size):
            mult *= size[ndims - idx] if (idx > 0) else 1
            num += mult * indices[ndims - idx - 1]
        return num
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
141412
function( index ) {
		var val,
			vals,
			i;

		if ( arguments.length ) {
			val = this.options.values[ index ];
			val = this._trimAlignValue( val );

			return val;
		} else if ( this._hasMultipleValues() ) {

			// .slice() creates a copy of the array
			// this copy gets trimmed by min and max and then returned
			vals = this.options.values.slice();
			for ( i = 0; i < vals.length; i += 1 ) {
				vals[ i ] = this._trimAlignValue( vals[ i ] );
			}

			return vals;
		} else {
			return [];
		}
	}
387954
def each_indexed_object(collection, index_name, **where):
    """"""
    index = _db[collection].indexes[index_name]
    for id in index.value_map.get(indexed_value(index, where), []):
        yield get_object(collection, id)
422034
def rand(x_bounds, x_types, lowerbound, upperbound, max_retries=100):
    '''
    
    '''
    outputs = None

    if check_feasibility(x_bounds, lowerbound, upperbound) is True:
        # Order parameters by their range size. We want the smallest range first,
        # because the corresponding parameter has less numbers to choose from
        x_idx_sorted = []
        for i, _ in enumerate(x_bounds):
            if x_types[i] == "discrete_int":
                x_idx_sorted.append([i, len(x_bounds[i])])
            elif (x_types[i] == "range_int") or (x_types[i] == "range_continuous"):
                x_idx_sorted.append([i, math.floor(x_bounds[i][1] - x_bounds[i][0])])
        x_idx_sorted = sorted(x_idx_sorted, key=itemgetter(1))

        for _ in range(max_retries):
            budget_allocated = 0
            outputs = [None] * len(x_bounds)

            for i, _ in enumerate(x_idx_sorted):
                x_idx = x_idx_sorted[i][0]
                # The amount of unallocated space that we have
                budget_max = upperbound - budget_allocated
                # NOT the Last x that we need to assign a random number
                if i < (len(x_idx_sorted) - 1):
                    if x_bounds[x_idx][0] <= budget_max:
                        if x_types[x_idx] == "discrete_int":
                            # Note the valid integer
                            temp = []
                            for j in x_bounds[x_idx]:
                                if j <= budget_max:
                                    temp.append(j)
                            # Randomly pick a number from the integer array
                            if temp:
                                outputs[x_idx] = temp[random.randint(0, len(temp) - 1)]

                        elif (x_types[x_idx] == "range_int") or \
                                    (x_types[x_idx] == "range_continuous"):
                            outputs[x_idx] = random.randint(x_bounds[x_idx][0],
                                                            min(x_bounds[x_idx][-1], budget_max))

                else:
                    # The last x that we need to assign a random number
                    randint_lowerbound = lowerbound - budget_allocated
                    randint_lowerbound = 0 if randint_lowerbound < 0 else randint_lowerbound

                    # This check:
                    # is our smallest possible value going to overflow the available budget space,
                    # and is our largest possible value going to underflow the lower bound
                    if (x_bounds[x_idx][0] <= budget_max) and \
                            (x_bounds[x_idx][-1] >= randint_lowerbound):
                        if x_types[x_idx] == "discrete_int":
                            temp = []
                            for j in x_bounds[x_idx]:
                                # if (j <= budget_max) and (j >= randint_lowerbound):
                                if randint_lowerbound <= j <= budget_max:
                                    temp.append(j)
                            if temp:
                                outputs[x_idx] = temp[random.randint(0, len(temp) - 1)]
                        elif (x_types[x_idx] == "range_int") or \
                                (x_types[x_idx] == "range_continuous"):
                            outputs[x_idx] = random.randint(randint_lowerbound,
                                                            min(x_bounds[x_idx][1], budget_max))
                if outputs[x_idx] is None:
                    break
                else:
                    budget_allocated += outputs[x_idx]
            if None not in outputs:
                break
    return outputs
839896
public LazyObject optJSONObject(int index) throws LazyException{
		LazyNode token=getOptionalValueToken(index);
		if(token==null)return null;
		if(token.type==LazyNode.VALUE_NULL)return null;
		if(token.type!=LazyNode.OBJECT)return null;
		LazyObject obj= new LazyObject(token);
		obj.parent=this;
		return obj;
	}
187231
public LazyArray optJSONArray(int index) throws LazyException{
		LazyNode token=getOptionalValueToken(index);
		if(token==null)return null;
		if(token.type==LazyNode.VALUE_NULL)return null;
		if(token.type!=LazyNode.ARRAY)return null;
		LazyArray arr= new LazyArray(token);
		arr.parent=this;
		return arr;
	}
461981
def _get_position(self):
        
        portfolio_code = self.account_config["portfolio_code"]
        portfolio_info = self._get_portfolio_info(portfolio_code)
        position = portfolio_info["view_rebalancing"]  # 仓位结构
        stocks = position["holdings"]  # 持仓股票
        return stocks
851642
def max_sharpe(self):
        """"""
        if not self.w:
            self.solve()
        # 1) Compute the local max SR portfolio between any two neighbor turning points
        w_sr, sr = [], []
        for i in range(len(self.w) - 1):
            w0 = np.copy(self.w[i])
            w1 = np.copy(self.w[i + 1])
            kargs = {"minimum": False, "args": (w0, w1)}
            a, b = self.golden_section(self.eval_sr, 0, 1, **kargs)
            w_sr.append(a * w0 + (1 - a) * w1)
            sr.append(b)
        # return max(sr), w_sr[sr.index(max(sr))]
        self.weights = w_sr[sr.index(max(sr))].reshape((self.n_assets,))
        return dict(zip(self.tickers, self.weights))
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))
762581
def get(self, index):
        """"""
        assert index <= self.count
        assert index < self.size
        offset = index * self.chunk_size
        return self.data[offset:offset + self.chunk_size]