Calculate market resources for all agents this period.

        Parameters
        ----------
        None

        Returns
        -------
        None
768493
def getStates(self):
        '''
        
        '''
        self.bLvlNow = self.Rfree*self.aLvlNow
        self.mLvlNow = self.bLvlNow + self.eStateNow
627098
def hold_price(self, datetime=None):
        

        def weights(x):
            if sum(x['amount']) != 0:
                return np.average(
                    x['price'],
                    weights=x['amount'],
                    returned=True
                )
            else:
                return np.nan

        if datetime is None:
            return self.history_table.set_index(
                'datetime',
                drop=False
            ).sort_index().groupby('code').apply(weights).dropna()
        else:
            return self.history_table.set_index(
                'datetime',
                drop=False
            ).sort_index().loc[:datetime].groupby('code').apply(weights
                                                               ).dropna()
10307
def get_pools(time_span=None, api_code=None):
    

    resource = 'pools'
    if time_span is not None:
        resource += '?timespan=' + time_span
    if api_code is not None:
        resource += '&api_code=' + api_code
    response = util.call_api(resource, base_url='https://api.blockchain.info/')
    json_response = json.loads(response)
    return {k: v for (k, v) in json_response.items()}
602205
def get_price(self):
        
        tick = self.get_ticks(lookback=1, as_dict=True)
        return None if tick is None else tick['last']
3138
def unreserve_resources(role):
    
    state = dcos_agents_state()
    if not state or 'slaves' not in state.keys():
        return False
    all_success = True
    for agent in state['slaves']:
        if not unreserve_resource(agent, role):
            all_success = False
    return all_success
897656
def grid(self, start=None, stop=None, St=None, **kwargs):
        

        lb = 0.75
        rb = 1.25
        if not any((start, stop, St)) and self.St is None:
            St = np.mean([op.K for op in self.options], axis=0)
            start = St * lb
            stop = St * rb
        elif not any((start, stop)):
            St = self.St if St is None else St
            start = np.max(St) * lb
            stop = np.max(St) * rb
        St = np.linspace(start, stop, **kwargs)
        payoffs = self.payoff(St=St)
        profits = self.profit(St=St)
        return St, payoffs, profits
51212
def solve(self):
        '''
        
        '''
        if self.AggShockBool:
            for agent in self.agents:
                agent.getEconomyData(self)
            Market.solve(self)
        else:
            self.solveAgents()
            self.makeHistory()
364470
def getReward(self):
        
        t = self.env.market.period

        # Compute revenue minus costs.
        totalEarnings = 0.0
        for g in self.env.generators:
            # Compute costs in $ (not $/hr).
            costs = g.total_cost(round(g.p, 4),
                                 self.env._g0[g]["p_cost"],
                                 self.env._g0[g]["pcost_model"])

            offbids = [ob for ob in self.env._lastAction if ob.generator == g]

            revenue = t * sum([ob.revenue for ob in offbids])
            if offbids:
                revenue += offbids[0].noLoadCost

            if g.is_load:
                earnings = costs - revenue
            else:
                earnings = revenue - costs#(fixedCost + variableCost)

            logger.debug("Generator [%s] earnings: %.2f (%.2f, %.2f)" %
                         (g.name, earnings, revenue, costs))

            totalEarnings += earnings

        # Startup/shutdown costs.
        onlineCosts = 0.0
        for i, g in enumerate(self.env.generators):
            if self._gOnline[i] and not g.online:
                onlineCosts += g.c_shutdown
            elif not self._gOnline[i] and g.online:
                onlineCosts += g.c_startup
        self._gOnline = [g.online for g in self.env.generators]

        reward = totalEarnings - onlineCosts
        self.addReward(reward)

        logger.debug("Task reward: %.2f (%.2f - %.2f)" %
                     (reward, totalEarnings, onlineCosts))

        return reward
351855
def requestMarketData(self, contracts=None, snapshot=False):
        
        if contracts == None:
            contracts = list(self.contracts.values())
        elif not isinstance(contracts, list):
            contracts = [contracts]

        for contract in contracts:
            if snapshot:
                reqType = ""
            else:
                reqType = dataTypes["GENERIC_TICKS_RTVOLUME"]
                if contract.m_secType in ("OPT", "FOP"):
                    reqType = dataTypes["GENERIC_TICKS_NONE"]

            # get market data for single contract
            # limit is 250 requests/second
            if not self.isMultiContract(contract):
                try:
                    tickerId = self.tickerId(self.contractString(contract))
                    self.ibConn.reqMktData(tickerId, contract, reqType, snapshot)
                    time.sleep(0.0042)  # 250 = 1.05s
                except KeyboardInterrupt:
                    sys.exit()
154278
def _run(handle_data,
         initialize,
         before_trading_start,
         analyze,
         algofile,
         algotext,
         defines,
         data_frequency,
         capital_base,
         bundle,
         bundle_timestamp,
         start,
         end,
         output,
         trading_calendar,
         print_algo,
         metrics_set,
         local_namespace,
         environ,
         blotter,
         benchmark_returns):
    
    if benchmark_returns is None:
        benchmark_returns, _ = load_market_data(environ=environ)

    if algotext is not None:
        if local_namespace:
            ip = get_ipython()  # noqa
            namespace = ip.user_ns
        else:
            namespace = {}

        for assign in defines:
            try:
                name, value = assign.split('=', 2)
            except ValueError:
                raise ValueError(
                    'invalid define %r, should be of the form name=value' %
                    assign,
                )
            try:
                # evaluate in the same namespace so names may refer to
                # eachother
                namespace[name] = eval(value, namespace)
            except Exception as e:
                raise ValueError(
                    'failed to execute definition for name %r: %s' % (name, e),
                )
    elif defines:
        raise _RunAlgoError(
            'cannot pass define without `algotext`',
            "cannot pass '-D' / '--define' without '-t' / '--algotext'",
        )
    else:
        namespace = {}
        if algofile is not None:
            algotext = algofile.read()

    if print_algo:
        if PYGMENTS:
            highlight(
                algotext,
                PythonLexer(),
                TerminalFormatter(),
                outfile=sys.stdout,
            )
        else:
            click.echo(algotext)

    if trading_calendar is None:
        trading_calendar = get_calendar('XNYS')

    # date parameter validation
    if trading_calendar.session_distance(start, end) < 1:
        raise _RunAlgoError(
            'There are no trading days between %s and %s' % (
                start.date(),
                end.date(),
            ),
        )

    bundle_data = bundles.load(
        bundle,
        environ,
        bundle_timestamp,
    )

    first_trading_day = \
        bundle_data.equity_minute_bar_reader.first_trading_day

    data = DataPortal(
        bundle_data.asset_finder,
        trading_calendar=trading_calendar,
        first_trading_day=first_trading_day,
        equity_minute_reader=bundle_data.equity_minute_bar_reader,
        equity_daily_reader=bundle_data.equity_daily_bar_reader,
        adjustment_reader=bundle_data.adjustment_reader,
    )

    pipeline_loader = USEquityPricingLoader(
        bundle_data.equity_daily_bar_reader,
        bundle_data.adjustment_reader,
    )

    def choose_loader(column):
        if column in USEquityPricing.columns:
            return pipeline_loader
        raise ValueError(
            "No PipelineLoader registered for column %s." % column
        )

    if isinstance(metrics_set, six.string_types):
        try:
            metrics_set = metrics.load(metrics_set)
        except ValueError as e:
            raise _RunAlgoError(str(e))

    if isinstance(blotter, six.string_types):
        try:
            blotter = load(Blotter, blotter)
        except ValueError as e:
            raise _RunAlgoError(str(e))

    perf = TradingAlgorithm(
        namespace=namespace,
        data_portal=data,
        get_pipeline_loader=choose_loader,
        trading_calendar=trading_calendar,
        sim_params=SimulationParameters(
            start_session=start,
            end_session=end,
            trading_calendar=trading_calendar,
            capital_base=capital_base,
            data_frequency=data_frequency,
        ),
        metrics_set=metrics_set,
        blotter=blotter,
        benchmark_returns=benchmark_returns,
        **{
            'initialize': initialize,
            'handle_data': handle_data,
            'before_trading_start': before_trading_start,
            'analyze': analyze,
        } if algotext is None else {
            'algo_filename': getattr(algofile, 'name', '<algorithm>'),
            'script': algotext,
        }
    ).run()

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

    return perf
972281
def getPrices(self, *args, **kwargs):
        

        return self._makeApiCall(self.funcinfo["getPrices"], *args, **kwargs)
892595
def get(self, max=None, timeout=None, wait=None):
        
        response = self.reserve(max, timeout, wait)
        return response
723590
def prices(self):
        
        if self.root.stale:
            self.root.update(self.now, None)
        return self._prices.loc[:self.now]
1302297
def get_market_last(symbols=None, **kwargs):
    
    import warnings
    warnings.warn(WNG_MSG % ("get_market_last", "iexdata.get_last"))
    return Last(symbols, **kwargs).fetch()
1282984
def resources(self):
        
        return sa.orm.relationship(
            "Resource",
            cascade="all",
            passive_deletes=True,
            passive_updates=True,
            backref="owner",
            lazy="dynamic",
        )
274189
def get_resources(resources):  # pylint:disable=too-many-branches
    
    limits = {}
    requests = {}
    if resources is None:
        return None
    if resources.cpu:
        if resources.cpu.limits:
            limits['cpu'] = resources.cpu.limits
        if resources.cpu.requests:
            requests['cpu'] = resources.cpu.requests

    if resources.memory:
        if resources.memory.limits:
            limits['memory'] = '{}Mi'.format(resources.memory.limits)
        if resources.memory.requests:
            requests['memory'] = '{}Mi'.format(resources.memory.requests)

    if resources.gpu:
        if resources.gpu.limits:
            limits[conf.get('K8S_GPU_RESOURCE_KEY')] = resources.gpu.limits
        if resources.gpu.requests:
            requests[conf.get('K8S_GPU_RESOURCE_KEY')] = resources.gpu.requests

    if resources.tpu:
        if resources.tpu.limits:
            limits[conf.get('K8S_TPU_RESOURCE_KEY')] = resources.tpu.limits
        if resources.tpu.requests:
            requests[conf.get('K8S_TPU_RESOURCE_KEY')] = resources.tpu.requests
    return client.V1ResourceRequirements(limits=limits or None, requests=requests or None)
413956
def all(cls, client, **kwargs):
        
        max_date = kwargs['max_date'] if 'max_date' in kwargs else None
        max_fetches = \
            kwargs['max_fetches'] if 'max_fetches' in kwargs else None

        url = 'https://api.robinhood.com/options/positions/'
        params = {}
        data = client.get(url, params=params)
        results = data["results"]

        if is_max_date_gt(max_date, results[-1]['updated_at'][0:10]):
            return results
        if max_fetches == 1:
            return results

        fetches = 1
        while data["next"]:
            fetches = fetches + 1
            data = client.get(data["next"])
            results.extend(data["results"])
            if is_max_date_gt(max_date, results[-1]['updated_at'][0:10]):
                return results
            if max_fetches and (fetches >= max_fetches):
                return results
        return results