Calculates performance stats of a given object.

    If object is Series, a PerformanceStats object is
    returned. If object is DataFrame, a GroupStats object
    is returned.

    Args:
        * prices (Series, DataFrame): Set of prices
979448
def calc_stats(prices):
    
    if isinstance(prices, pd.Series):
        return PerformanceStats(prices)
    elif isinstance(prices, pd.DataFrame):
        return GroupStats(*[prices[x] for x in prices.columns])
    else:
        raise NotImplementedError('Unsupported type')
93615
def rolling_performances(self, timestamp='one_month'):
        '''  '''
        # TODO Study the impact of month choice
        # TODO Check timestamp in an enumeration
        # TODO Implement other benchmarks for perf computation
        # (zipline issue, maybe expected)

        if self.metrics:
            perfs = {}
            length = range(len(self.metrics[timestamp]))
            index = self._get_index(self.metrics[timestamp])
            perf_keys = self.metrics[timestamp][0].keys()
            perf_keys.pop(perf_keys.index('period_label'))

            perfs['period'] = np.array(
                [pd.datetime.date(date) for date in index])
            for key in perf_keys:
                perfs[key] = self._to_perf_array(timestamp, key, length)
        else:
            # TODO Get it from DB if it exists
            raise NotImplementedError()

        return pd.DataFrame(perfs, index=index)
538119
def stats(self, columns):
        
        def reduce_func(sc1, sc2):
            return sc1.merge_pstats(sc2)

        return self._rdd.mapPartitions(lambda partition: [
            PStatCounter(dataframes=partition, columns=columns)])\
            .reduce(reduce_func)
1125056
def get_ftype_counts(self):
        
        if hasattr(self, "ftype"):
            return pandas.Series({self.ftype: 1})
        return self.ftypes.value_counts().sort_index()
763609
def get_object_stats(self, obj_name):
        

        return dict(zip(self.captions, self.statistics[obj_name]))
819863
def _return_result(self, result, comparison_vectors=None):
        
        return_type = cf.get_option('classification.return_type')

        if type(result) != np.ndarray:
            raise ValueError("numpy.ndarray expected.")

        # return the pandas.MultiIndex
        if return_type == 'index':
            return comparison_vectors.index[result.astype(bool)]

        # return a pandas.Series
        elif return_type == 'series':
            return pandas.Series(
                result,
                index=comparison_vectors.index,
                name='classification')

        # return a numpy.ndarray
        elif return_type == 'array':
            return result

        # return_type not known
        else:
            raise ValueError(
                "return_type {} unknown. Choose 'index', 'series' or "
                "'array'".format(return_type))
341498
def aggregate(self, *args, **kwargs):
        
        obj = self._clone()
        obj._facets = [] #reset facets
        from django.db.models import Avg, Max, Min

        for arg in args:
            if isinstance(arg, (Avg, Max, Min)):

                field, djfield = self._django_to_es_field(arg.lookup)
                if not djfield:
                    obj = obj.annotate(field)
                from pyes.facets import StatisticalFacet

                obj = obj.annotate(StatisticalFacet(field, field))
        facets = obj.get_facets()
        #collecting results
        result = {}
        for name, values in facets.items():
            for k, v in values.items():
                if k.startswith("_"):
                    continue
                result[u'%s__%s' % (name, k)] = v

        return result
208167
def _get_resampler_for_grouping(self, groupby, **kwargs):
        
        return self._resampler_for_grouping(self, groupby=groupby, **kwargs)
258596
def stats_for(self, dt):
        
        # TODO - this would be nicer if we formatted the stats
        if not isinstance(dt, datetime):
            raise TypeError('stats_for requires a datetime object!')
        return self._client.get('{}/stats/'.format(dt.strftime('%Y/%m')))
823247
def sum_stats(stats_data):
    
    t_bounces = 0
    t_complaints = 0
    t_delivery_attempts = 0
    t_rejects = 0
    for dp in stats_data:
        t_bounces += int(dp['Bounces'])
        t_complaints += int(dp['Complaints'])
        t_delivery_attempts += int(dp['DeliveryAttempts'])
        t_rejects += int(dp['Rejects'])

    return {
        'Bounces': t_bounces,
        'Complaints': t_complaints,
        'DeliveryAttempts': t_delivery_attempts,
        'Rejects': t_rejects,
    }
753736
def stats(self) -> pd.DataFrame:
        
        key = ["icao24", "callsign"] if self.flight_ids is None else "flight_id"
        return (
            self.data.groupby(key)[["timestamp"]]
            .count()
            .sort_values("timestamp", ascending=False)
            .rename(columns={"timestamp": "count"})
        )
616934
def get_value(self, series, key):
        
        if not is_scalar(key):
            raise InvalidIndexError

        k = com.values_from_object(key)
        loc = self.get_loc(k)
        new_values = com.values_from_object(series)[loc]

        return new_values
474372
def df_weighted_average_grouped(dataframe, groupe, varlist):
    '''
    
    '''
    return DataFrame(
        dict([
            (var, collapse(dataframe, groupe, var)) for var in varlist
            ])
        )
976320
def get_info(df, group, info=['mean', 'std']):
    
    agg = df.groupby(group).agg(info)
    agg.columns = agg.columns.droplevel(0)
    return agg
185679
def evaluate(self, dataset):
        
        if not isinstance(dataset, DataFrame):
            raise ValueError("dataset must be a DataFrame but got %s." % type(dataset))
        java_glr_summary = self._call_java("evaluate", dataset)
        return GeneralizedLinearRegressionSummary(java_glr_summary)
615094
def levels_for(self, time_op, groups, df):
        
        levels = {}
        for i in range(0, len(groups) + 1):
            agg_df = df.groupby(groups[:i]) if i else df
            levels[i] = (
                agg_df.mean() if time_op == 'agg_mean'
                else agg_df.sum(numeric_only=True))
        return levels
783682
def query_rates(self, pairs=[]):
        '''  '''
        # If no pairs, TrueFx will use the ones given the last time
        payload = {'id': self._session}
        if pairs:
            payload['c'] = _clean_pairs(pairs)
        response = requests.get(self._api_url, params=payload)

        mapped_data = _fx_mapping(response.content.split('\n')[:-2])
        return Series(mapped_data) if len(mapped_data) == 1 \
            else DataFrame(mapped_data)