:returns: the total asset value for `loss_type`
548161
def value(self, loss_type, time_event=None):
        
        if loss_type == 'occupants':
            return self.values['occupants_' + str(time_event)]
        try:  # extract from the cache
            val = self._cost[loss_type]
        except KeyError:  # compute
            val = self.calc(loss_type, self.values, self.area, self.number)
            self._cost[loss_type] = val
        return val
946908
def __getCashToBuyStock(self):
        '''  '''
        account=self.__strategy.getAccountCopy()

        if (account.buyingPower >= account.getTotalValue() / self.__buyingRatio):
            return account.getTotalValue() / self.__buyingRatio
        else:
            return 0
1044612
def get_risk_models(oqparam, kind='vulnerability vulnerability_retrofitted '
                    'fragility consequence'):
    
    kinds = kind.split()
    rmodels = AccumDict()
    for kind in kinds:
        for key in sorted(oqparam.inputs):
            mo = re.match('(occupants|%s)_%s$' % (COST_TYPE_REGEX, kind), key)
            if mo:
                loss_type = mo.group(1)  # the cost_type in the key
                # can be occupants, structural, nonstructural, ...
                rmodel = nrml.to_python(oqparam.inputs[key])
                if len(rmodel) == 0:
                    raise InvalidFile('%s is empty!' % oqparam.inputs[key])
                rmodels[loss_type, kind] = rmodel
                if rmodel.lossCategory is None:  # NRML 0.4
                    continue
                cost_type = str(rmodel.lossCategory)
                rmodel_kind = rmodel.__class__.__name__
                kind_ = kind.replace('_retrofitted', '')  # strip retrofitted
                if not rmodel_kind.lower().startswith(kind_):
                    raise ValueError(
                        'Error in the file "%s_file=%s": is '
                        'of kind %s, expected %s' % (
                            key, oqparam.inputs[key], rmodel_kind,
                            kind.capitalize() + 'Model'))
                if cost_type != loss_type:
                    raise ValueError(
                        'Error in the file "%s_file=%s": lossCategory is of '
                        'type "%s", expected "%s"' %
                        (key, oqparam.inputs[key],
                         rmodel.lossCategory, loss_type))
    rdict = AccumDict(accum={})
    rdict.limit_states = []
    for (loss_type, kind), rm in sorted(rmodels.items()):
        if kind == 'fragility':
            # build a copy of the FragilityModel with different IM levels
            newfm = rm.build(oqparam.continuous_fragility_discretization,
                             oqparam.steps_per_interval)
            for (imt, riskid), ffl in newfm.items():
                if not rdict.limit_states:
                    rdict.limit_states.extend(rm.limitStates)
                # we are rejecting the case of loss types with different
                # limit states; this may change in the future
                assert rdict.limit_states == rm.limitStates, (
                    rdict.limit_states, rm.limitStates)
                rdict[riskid][loss_type, kind] = ffl
                # TODO: see if it is possible to remove the attribute
                # below, used in classical_damage
                ffl.steps_per_interval = oqparam.steps_per_interval
        elif kind == 'consequence':
            for riskid, cf in rm.items():
                rdict[riskid][loss_type, kind] = cf
        else:  # vulnerability
            cl_risk = oqparam.calculation_mode in (
                'classical', 'classical_risk')
            # only for classical_risk reduce the loss_ratios
            # to make sure they are strictly increasing
            for (imt, riskid), rf in rm.items():
                rdict[riskid][loss_type, kind] = (
                    rf.strictly_increasing() if cl_risk else rf)
    return rdict
879965
def average_sharded_losses(sharded_losses):
  
  losses = {}
  for loss_name in sorted(sharded_losses[0]):
    all_shards = [shard_losses[loss_name] for shard_losses in sharded_losses]
    if isinstance(all_shards[0], tuple):
      sharded_num, sharded_den = zip(*all_shards)
      mean_loss = (
          tf.add_n(sharded_num) / tf.maximum(
              tf.cast(1.0, sharded_den[0].dtype), tf.add_n(sharded_den)))
    else:
      mean_loss = tf.reduce_mean(all_shards)

    losses[loss_name] = mean_loss
  return losses
455357
def buy_holding_pnl(self):
        
        return (self.last_price - self.buy_avg_holding_price) * self.buy_quantity * self.contract_multiplier
121221
def get_loss(self, pred: mx.sym.Symbol, labels: mx.sym.Symbol) -> mx.sym.Symbol:
        
        labels = mx.sym.reshape(labels, shape=(-1, 1))
        loss_value = self.loss_config.length_task_weight / 2 * mx.sym.square(pred - labels)
        loss_value = mx.sym.MakeLoss(data=loss_value,
                                     normalization='batch',
                                     name=self.name)
        return loss_value
356750
def __getCashToBuyStock(self):
        '''  '''
        account=self.__strategy.getAccountCopy()
        if (account.getCash() >= account.getTotalValue() / self.buying_ratio):
            return account.getTotalValue() / self.buying_ratio
        else:
            return 0
1045432
def asset_view_atype(self, ):
        
        if not self.cur_asset:
            return

        atype = self.cur_asset.atype
        self.view_atype(atype)
564378
def top_losses(self, k:int=None, largest=True):
        ""
        return self.losses.topk(ifnone(k, len(self.losses)), largest=largest)
175453
def export_avg_losses(ekey, dstore):
    
    dskey = ekey[0]
    oq = dstore['oqparam']
    dt = oq.loss_dt()
    name, value, tags = _get_data(dstore, dskey, oq.hazard_stats().items())
    writer = writers.CsvWriter(fmt=writers.FIVEDIGITS)
    assets = get_assets(dstore)
    for tag, values in zip(tags, value.transpose(1, 0, 2)):
        dest = dstore.build_fname(name, tag, 'csv')
        array = numpy.zeros(len(values), dt)
        for l, lt in enumerate(dt.names):
            array[lt] = values[:, l]
        writer.save(compose_arrays(assets, array), dest)
    return writer.getsaved()
1202951
def scalloping_loss(wnd):
  
  return -dB20(abs(sum(wnd * cexp(line(len(wnd), 0, -1j * pi)))) / sum(wnd))
1359668
def get_last_traded_dt(self, asset, dt, data_frequency):
        
        return self._get_pricing_reader(data_frequency).get_last_traded_dt(
            asset, dt)
178115
def to_dict(self):
        
        return {
            'sid': self.asset,
            'amount': self.amount,
            'cost_basis': self.cost_basis,
            'last_sale_price': self.last_sale_price
        }
1318716
def calculate_set_values(self):
        
        for ac in self.asset_classes:
            ac.alloc_value = self.total_amount * ac.allocation / Decimal(100)
795437
def add_loss(self, loss, name=None):
    """"""
    self.bookkeeper.add_loss(loss, name=name)
    return Loss(self.bookkeeper, tensor=loss, name=name)
1069924
def _summarize_losses(self, losses_dict):
    """"""
    if common_layers.should_generate_summaries():
      with tf.name_scope("losses"):
        for loss_name, loss_val in sorted(losses_dict.items()):
          tf.summary.scalar(loss_name, loss_val)
859946
def value_percent(self):
        
        accounts = Environment.get_instance().portfolio.accounts
        if DEFAULT_ACCOUNT_TYPE.STOCK.name not in accounts:
            return 0
        total_value = accounts[DEFAULT_ACCOUNT_TYPE.STOCK.name].total_value
        return 0 if total_value == 0 else self.market_value / total_value