Run calmar, stores new weights and returns adjusted margins
964266
def _update_weights(self, margins, parameters = {}):
        
        data = self._build_calmar_data()
        assert self.initial_weight_name is not None
        parameters['initial_weight'] = self.initial_weight_name
        val_pondfin, lambdasol, updated_margins = calmar(
            data, margins, **parameters)
        # Updating only afetr filtering weights
        self.weight = val_pondfin * self.filter_by + self.weight * (logical_not(self.filter_by))
        return updated_margins
1318911
def calmar(sharpe, T = 1.0):
    '''
    
    '''
    x = 0.5*T*sharpe*sharpe
    return x/qp(x)
580211
def update_numeric_results(ac, ar, val)
      cval = ac.convert(val)
      ar[:min] = cval if ar[:min].nil? || cval < ar[:min]
      ar[:max] = cval if ar[:max].nil? || cval > ar[:max]
    end
700024
def create_adjusted_model_for_percentages(model_src, model_use):
    """"""
    # Copy model file
    shutil.copyfile(model_src, model_use)
    # Adjust model file
    with open(model_src) as f:
        content = f.read()
    content = content.replace("logreg", "sigmoid")
    with open(model_use, "w") as f:
        f.write(content)
673946
def up_alpha_beta(returns, factor_returns, **kwargs):
    
    return up(returns, factor_returns, function=alpha_beta_aligned, **kwargs)
125395
def setup(self, **kwargs):
        """"""
        # Keep labels in case of map
        if getattr(self, 'x_labels', None) is not None:
            self.x_labels = list(self.x_labels)
        if getattr(self, 'y_labels', None) is not None:
            self.y_labels = list(self.y_labels)
        self.state = State(self, **kwargs)
        if isinstance(self.style, type):
            self.style = self.style()
        self.series = self.prepare_values([
            rs for rs in self.raw_series if not rs[1].get('secondary')
        ]) or []
        self.secondary_series = self.prepare_values([
            rs for rs in self.raw_series if rs[1].get('secondary')
        ], len(self.series)) or []
        self.horizontal = getattr(self, 'horizontal', False)
        self.svg = Svg(self)
        self._x_labels = None
        self._y_labels = None
        self._x_2nd_labels = None
        self._y_2nd_labels = None
        self.nodes = {}
        self.margin_box = Margin(
            self.margin_top or self.margin, self.margin_right or self.margin,
            self.margin_bottom or self.margin, self.margin_left or self.margin
        )
        self._box = Box()
        self.view = None
        if self.logarithmic and self.zero == 0:
            # Explicit min to avoid interpolation dependency
            positive_values = list(
                filter(
                    lambda x: x > 0, [
                        val[1] or 1 if self._dual else val
                        for serie in self.series for val in serie.safe_values
                    ]
                )
            )

            self.zero = min(positive_values or (1, )) or 1
        if self._len < 3:
            self.interpolate = None
        self._draw()
        self.svg.pre_render()
885937
def _prep_inputs(align_bams, ref_file, items):
    
    broad_runner = broad.runner_from_path("picard", items[0]["config"])
    broad_runner.run_fn("picard_index_ref", ref_file)
    for x in align_bams:
        bam.index(x, items[0]["config"])
989917
function initializeWithEval() {
  var dbTest = new loki('perfInsertWithEval');

  var start, end, totalTime;
  var totalTimes = [];
  var totalMS = 0.0;

  var coll = dbTest.addCollection('samplecoll',
    {
      indices: ['customId'],
      asyncListeners: false,
      disableChangesApi: true,
      transactional: false,
      clone: false
    }
  );

  var dv = coll.addDynamicView('test');
  dv.applyFind({'customId': {'$lt': arraySize/4 }});

  for (var idx=0; idx < arraySize; idx++) {
    var v1 = genRandomVal();
    var v2 = genRandomVal();

    start = performance.now();
    coll.insert({
      customId: idx,
      val: v1,
      val2: v2,
      val3: "more data 1234567890"
    });
    end = performance.now() - start;
    totalTimes.push([0, end * 1e6]);
  }

  for(idx=0; idx < totalTimes.length; idx++) {
    totalMS += totalTimes[idx][0] * 1e3 + totalTimes[idx][1]/1e6;
  }

  totalMS = totalMS.toFixed(2);
  var rate = arraySize * 1000 / totalMS;
  rate = rate.toFixed(2);
  trace("load (insert with dynamic view registered) : " + totalMS + "ms (" + rate + ") ops/s");
}
701701
def run(ctx,
        algofile,
        algotext,
        define,
        data_frequency,
        capital_base,
        bundle,
        bundle_timestamp,
        start,
        end,
        output,
        trading_calendar,
        print_algo,
        metrics_set,
        local_namespace,
        blotter):
    
    # check that the start and end dates are passed correctly
    if start is None and end is None:
        # check both at the same time to avoid the case where a user
        # does not pass either of these and then passes the first only
        # to be told they need to pass the second argument also
        ctx.fail(
            "must specify dates with '-s' / '--start' and '-e' / '--end'",
        )
    if start is None:
        ctx.fail("must specify a start date with '-s' / '--start'")
    if end is None:
        ctx.fail("must specify an end date with '-e' / '--end'")

    if (algotext is not None) == (algofile is not None):
        ctx.fail(
            "must specify exactly one of '-f' / '--algofile' or"
            " '-t' / '--algotext'",
        )

    trading_calendar = get_calendar(trading_calendar)

    perf = _run(
        initialize=None,
        handle_data=None,
        before_trading_start=None,
        analyze=None,
        algofile=algofile,
        algotext=algotext,
        defines=define,
        data_frequency=data_frequency,
        capital_base=capital_base,
        bundle=bundle,
        bundle_timestamp=bundle_timestamp,
        start=start,
        end=end,
        output=output,
        trading_calendar=trading_calendar,
        print_algo=print_algo,
        metrics_set=metrics_set,
        local_namespace=local_namespace,
        environ=os.environ,
        blotter=blotter,
        benchmark_returns=None,
    )

    if output == '-':
        click.echo(str(perf))
    elif output != os.devnull:  # make the zipline magic not write any data
        perf.to_pickle(output)

    return perf
409493
def standartDeviation(self, series, start, limit):
        '''
        
        '''
        return float(np.std(series[start:limit]))
453757
def add_noise(weights, other_weights):
    '''
    '''
    w_range = np.ptp(other_weights.flatten())
    noise_range = NOISE_RATIO * w_range
    noise = np.random.uniform(-noise_range / 2.0, noise_range / 2.0, weights.shape)
    return np.add(noise, weights)
368759
def sharpe(returns, rfr=0, expanding=0):
    
    if expanding:
        excess = excess_returns(returns, rfr)
        return pd.expanding_mean(excess) / pd.expanding_std(returns)
    else:
        return excess_returns(returns, rfr).mean() / returns.std()
902055
def insert_seperator_results(results):
    """"""
    sepbench = BenchmarkResult(*[' ' * w for w in COLUMN_WIDTHS])
    last_bm = None
    for r in results:
        if last_bm is None:
            last_bm = r.benchmark
        elif last_bm != r.benchmark:
            yield sepbench
            last_bm = r.benchmark
        yield r
523958
def optimize(self, piter=3, pmaxf=300, ppert=0.1):
        '''
        

        '''

        self._save_npz()
        optimized = pPLD(self.ID, piter=piter, pmaxf=pmaxf,
                         ppert=ppert, debug=True, clobber=True)
        optimized.publish()
        self.reset()
863042
def portfolio_value(portfolio, date, price='close'):
    
    value = 0.0
    for (sym, sym_shares) in portfolio.iteritems():
        sym_price = None
        if sym_shares:
            sym_price = get_price(symbol=sym, date=date, price=price)
        # print sym, sym_shares, sym_price
        # print last_date, k, price
        if sym_price != None:
            if np.isnan(sym_price):
                print 'Invalid price, shares, value, total: ', sym_price, sym_shares, (float(sym_shares) * float(sym_price)) if sym_shares and sym_price else 'Invalid', value
                if sym_shares:
                    return float('nan')
            else:
                # print ('{0} shares of {1} = {2} * {3} = {4}'.format(sym_shares, sym, sym_shares, sym_price, sym_shares * sym_price))
                value += sym_shares * sym_price
                # print 'new price, value = {0}, {1}'.format(sym_price, value)
    return value
481934
def initialize_weights(self):
        """"""
        n = self._outputSize
        m = self._inputSize
        self._Q = self._random.sample((n,m))

        # Normalize the weights of each units
        for i in range(n):
            self._Q[i] /=  np.sqrt( np.dot(self._Q[i], self._Q[i]) )
918776
def run(self, data):
        
        if self.normalize_data:
            data = cell_normalize(data)
        M, W, ll = poisson_estimate_state(data, **self.params)
        outputs = []
        if self.return_w:
            outputs.append(W)
        if self.return_m:
            outputs.append(M)
        if self.return_mw:
            outputs.append(M.dot(W))
        if self.return_mds:
            X = dim_reduce(M, W, 2)
            outputs.append(X.T.dot(W))
        return outputs, ll