Calculates the `CAGR (compound annual growth rate) <https://www.investopedia.com/terms/c/cagr.asp>`_ for a given price series.

    Args:
        * prices (pandas.Series): A Series of prices.
    Returns:
        * float -- cagr.
508699
def calc_cagr(prices):
    
    start = prices.index[0]
    end = prices.index[-1]
    return (prices.iloc[-1] / prices.iloc[0]) ** (1 / year_frac(start, end)) - 1
1020289
def calcEL(self,**kwargs):
                                   
        E,L= calcELStaeckel(self._R,self._vR,self._vT,self._z,self._vz,
                            self._pot)
        return (E,L)
703224
def _sumSeries(a: float, b: float, steps: int) -> float:
        
        return a * (exp(b * steps) - 1) / (exp(b) - 1)
773042
def average_returns(ts, **kwargs):
    ''' '''
    average_type = kwargs.get('type', 'net')
    if average_type == 'net':
        relative = 0
    else:
        relative = -1  # gross
    #start = kwargs.get('start', ts.index[0])
    #end = kwargs.get('end', ts.index[len(ts.index) - 1])
    #delta = kwargs.get('delta', ts.index[1] - ts.index[0])
    period = kwargs.get('period', None)
    if isinstance(period, int):
        pass
    #else:
        #ts = reIndexDF(ts, start=start, end=end, delta=delta)
        #period = 1
    avg_ret = 1
    for idx in range(len(ts.index)):
        if idx % period == 0:
            avg_ret *= (1 + ts[idx] + relative)
    return avg_ret - 1
723133
def drawdowns(returns, geometric=True):
    
    wealth = 1. + returns_cumulative(returns, geometric=geometric, expanding=True)
    values = wealth.values
    if values.ndim == 2:
        ncols = values.shape[-1]
        values = np.vstack(([1.] * ncols, values))
        maxwealth = pd.expanding_max(values)[1:]
        dds = wealth / maxwealth - 1.
        dds[dds > 0] = 0  # Can happen if first returns are positive
        return dds
    elif values.ndim == 1:
        values = np.hstack(([1.], values))
        maxwealth = pd.expanding_max(values)[1:]
        dds = wealth / maxwealth - 1.
        dds[dds > 0] = 0  # Can happen if first returns are positive
        return dds
    else:
        raise ValueError('unable to process array with %s dimensions' % values.ndim)
476065
def buildPrices(data, roles=None, regex=default_price_regex,
                default=None, additional={}):
    ''' '''
    if isinstance(data, dict):
        data = [(item[0], convertPrice(item[1])) for item in data.items()]
        return dict([v for v in data if v[1] is not None])
    elif isinstance(data, (str, float, int)) and not isinstance(data, bool):
        if default is None:
            raise ValueError('You have to call setAdditionalCharges '
                             'before it is possible to pass a string as price')
        basePrice = convertPrice(data)
        if basePrice is None:
            return {}
        prices = {default: basePrice}
        for role in additional:
            extraCharge = convertPrice(additional[role])
            if extraCharge is None:
                continue
            prices[role] = basePrice + extraCharge
        return prices
    elif roles:
        prices = {}
        priceRoles = iter(roles)
        for priceData in data:
            price = convertPrice(priceData)
            if price is None:
                continue
            prices[next(priceRoles)] = price
        return prices
    else:
        raise TypeError('This type is for prices not supported!')
873330
def rsi(series, window=14):
    

    # 100-(100/relative_strength)
    deltas = np.diff(series)
    seed = deltas[:window + 1]

    # default values
    ups = seed[seed > 0].sum() / window
    downs = -seed[seed < 0].sum() / window
    rsival = np.zeros_like(series)
    rsival[:window] = 100. - 100. / (1. + ups / downs)

    # period values
    for i in range(window, len(series)):
        delta = deltas[i - 1]
        if delta > 0:
            upval = delta
            downval = 0
        else:
            upval = 0
            downval = -delta

        ups = (ups * (window - 1) + upval) / window
        downs = (downs * (window - 1.) + downval) / window
        rsival[i] = 100. - 100. / (1. + ups / downs)

    # return rsival
    return pd.Series(index=series.index, data=rsival)
72269
def trend(self, **kwargs):
        ''''''
        return DataFrame({ name: series.trend(**kwargs) \
            for name, series in self.groups.iteritems() })
1038505
def get_avg_price_stat(self) -> Decimal:
        
        avg_price = Decimal(0)

        price_total = Decimal(0)
        price_count = 0

        for account in self.security.accounts:
            # Ignore trading accounts.
            if account.type == AccountType.TRADING.name:
                continue

            for split in account.splits:
                # Don't count the non-transactions.
                if split.quantity == 0:
                    continue

                price = split.value / split.quantity
                price_count += 1
                price_total += price

        if price_count:
            avg_price = price_total / price_count
        return avg_price
808149
def compute_discounts(self, precision=None):
        '''
        
        '''
        return sum([group.compute_discounts(precision) for group
                    in self.__groups])
1268214
def aroon_up(data, period):
    
    catch_errors.check_for_period_error(data, period)
    period = int(period)

    a_up = [((period -
            list(reversed(data[idx+1-period:idx+1])).index(np.max(data[idx+1-period:idx+1]))) /
            float(period)) * 100 for idx in range(period-1, len(data))]
    a_up = fill_for_noncomputable_vals(data, a_up)
    return a_up
321238
def _cost_gp_withGradients(self,x):
        
        m, _, dmdx, _= self.cost_model.predict_withGradients(x)
        return np.exp(m), np.exp(m)*dmdx
815221
def __calculate_moving_average(self, date, row):
        
        cal_data = self.__serial_price(row)
        result = []
        for dummy in range(len(cal_data) - int(date) + 1):
            result.append(round(sum(cal_data[-date:]) / date, 2))
            cal_data.pop()
        result.reverse()
        cont = self.__cal_continue(result)
        return result, cont
1203981
def plot_trunc_gr_model(
        aval, bval, min_mag, max_mag, dmag,
        catalogue=None, completeness=None, filename=None,
        figure_size=(8, 6), filetype='png', dpi=300, ax=None):
    
    input_model = TruncatedGRMFD(min_mag, max_mag, dmag, aval, bval)
    if not catalogue:
        # Plot only the modelled recurrence
        annual_rates, cumulative_rates = _get_recurrence_model(input_model)

        if ax is None:
            fig, ax = plt.subplots(figsize=figure_size)
        else:
            fig = ax.get_figure()

        ax.semilogy(annual_rates[:, 0], annual_rates[:, 1], 'b-')
        ax.semilogy(annual_rates[:, 0], cumulative_rates, 'r-')
        ax.xlabel('Magnitude')
        ax.set_ylabel('Annual Rate')
        ax.set_legend(['Incremental Rate', 'Cumulative Rate'])
        _save_image(fig, filename, filetype, dpi)

    else:
        completeness = _check_completeness_table(completeness, catalogue)
        plot_recurrence_model(
            input_model, catalogue, completeness, dmag, filename=filename,
            figure_size=figure_size, filetype=filetype, dpi=dpi, ax=ax)
442663
def _g(self, h, xp, s):
        """"""

        nphi = sum(self.phi)

        return (nphi / 2.0) * log(2 * pi) + nphi * \
            log(s) + 0.5 * sum((h - xp) ** 2) / (s ** 2)
618966
def sum(self):
        
        return self._constructor(self.values.sum(axis=self.baseaxes, keepdims=True))
1054486
def prices(self):
        
        if not self.__prices_aggregate:
            self.__prices_aggregate = PricesAggregate(self.book)
        return self.__prices_aggregate