Return the daily return series based on the capital
541724
def return_on_initial_capital(capital, period_pl, leverage=None):
    """"""
    if capital <= 0:
        raise ValueError('cost must be a positive number not %s' % capital)
    leverage = leverage or 1.
    eod = capital + (leverage * period_pl.cumsum())
    ltd_rets = (eod / capital) - 1.
    dly_rets = ltd_rets
    dly_rets.iloc[1:] = (1. + ltd_rets).pct_change().iloc[1:]
    return dly_rets
994835
def daily(self, symbol=None):
        '''
        
        '''
        reader = TdxDailyBarReader()
        vipdoc = self.find_path(symbol=symbol, subdir='lday', ext='day')

        if vipdoc is not None:
            return reader.get_df(vipdoc)

        return None
72269
def trend(self, **kwargs):
        ''''''
        return DataFrame({ name: series.trend(**kwargs) \
            for name, series in self.groups.iteritems() })
1104593
def market_value(self):
        
        if self.account.daily_hold is not None:
            if self.if_fq:

                return (
                    self.market_data.to_qfq().pivot('close').fillna(
                        method='ffill'
                    ) * self.account.daily_hold.apply(abs)
                ).fillna(method='ffill')
            else:
                return (
                    self.market_data.pivot('close').fillna(method='ffill') *
                    self.account.daily_hold.apply(abs)
                ).fillna(method='ffill')
        else:
            return None
97315
def cci(series, window=14):
    
    price = typical_price(series)
    typical_mean = rolling_mean(price, window)
    res = (price - typical_mean) / (.015 * np.std(typical_mean))
    return pd.Series(index=series.index, data=res)
1348250
def _get_history_daily_window(self,
                                  assets,
                                  end_dt,
                                  bar_count,
                                  field_to_use,
                                  data_frequency):
        
        session = self.trading_calendar.minute_to_session_label(end_dt)
        days_for_window = self._get_days_for_window(session, bar_count)

        if len(assets) == 0:
            return pd.DataFrame(None,
                                index=days_for_window,
                                columns=None)

        data = self._get_history_daily_window_data(
            assets, days_for_window, end_dt, field_to_use, data_frequency
        )
        return pd.DataFrame(
            data,
            index=days_for_window,
            columns=assets
        )
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)
883323
def next_weekday(weekday):
    """"""
    ix = WEEKDAYS.index(weekday)
    if ix == len(WEEKDAYS)-1:
        return WEEKDAYS[0]
    return WEEKDAYS[ix+1]
19056
def get_bars(self, assets, data_frequency, bar_count=500):
        '''
        
        '''
        assets_is_scalar = not isinstance(assets, (list, set, tuple))
        is_daily = 'd' in data_frequency  # 'daily' or '1d'
        if assets_is_scalar:
            symbols = [assets.symbol]
        else:
            symbols = [asset.symbol for asset in assets]

        symbol_bars = self._symbol_bars(
            symbols, 'day' if is_daily else 'minute', limit=bar_count)

        if is_daily:
            intra_bars = {}
            symbol_bars_minute = self._symbol_bars(
                symbols, 'minute', limit=1000)
            for symbol, df in symbol_bars_minute.items():
                agged = df.resample('1D').agg(dict(
                    open='first',
                    high='max',
                    low='min',
                    close='last',
                    volume='sum',
                )).dropna()
                intra_bars[symbol] = agged

        dfs = []
        for asset in assets if not assets_is_scalar else [assets]:
            symbol = asset.symbol
            df = symbol_bars.get(symbol)
            if df is None:
                dfs.append(pd.DataFrame(
                    [], columns=[
                        'open', 'high', 'low', 'close', 'volume']
                ))
                continue
            if is_daily:
                agged = intra_bars.get(symbol)
                if agged is not None and len(
                        agged.index) > 0 and agged.index[-1] not in df.index:
                    if not (agged.index[-1] > df.index[-1]):
                        log.warn(
                            ('agged.index[-1] = {}, df.index[-1] = {} '
                             'for {}').format(
                                agged.index[-1], df.index[-1], symbol))
                    df = df.append(agged.iloc[-1])
            df.columns = pd.MultiIndex.from_product([[asset, ], df.columns])
            dfs.append(df)

        return pd.concat(dfs, axis=1)
154323
def roc(series, window=14):
    
    res = (series - series.shift(window)) / series.shift(window)
    return pd.Series(index=series.index, data=res)
853140
def daily(self):
        
        if self._daily is None:
            self._daily = DailyList(self._version, account_sid=self._solution['account_sid'], )
        return self._daily
317860
def get_value(self, series, key):
        """"""
        if np.asarray(key).dtype == np.dtype(bool):
            return series.iloc[key]
        elif isinstance(key, slice):
            return series.iloc[self.slice_indexer(
                key.start, key.stop, key.step)]
        else:
            return series.iloc[self.get_loc(key)]
1255110
def rollsingle(self, func, window=20, name=None, fallback=False,
               align='right', **kwargs):
    '''
    '''
    rname = 'roll_{0}'.format(func)
    if fallback:
        rfunc = getattr(lib.fallback, rname)
    else:
        rfunc = getattr(lib, rname, None)
        if not rfunc:
            rfunc = getattr(lib.fallback, rname)
    data = np.array([list(rfunc(serie, window)) for serie in self.series()])
    name = name or self.makename(func, window=window)
    dates = asarray(self.dates())
    desc = settings.desc
    if (align == 'right' and not desc) or desc:
        dates = dates[window-1:]
    else:
        dates = dates[:-window+1]
    return self.clone(dates, data.transpose(), name=name)
16438
def group_by_day(self):
        
        hourly_data_by_day = OrderedDict()
        for d in xrange(1, 366):
            hourly_data_by_day[d] = []
        a_per = self.header.analysis_period
        indx_per_day = 24 * a_per.timestep
        start_doy = sum(a_per._num_of_days_each_month[:a_per.st_time.month-1]) \
            + a_per.st_time.day
        if not a_per.is_reversed:
            for i in range(0, len(self._values), indx_per_day):
                hourly_data_by_day[start_doy] = self._values[i:i + indx_per_day]
                start_doy += 1
        else:
            end_ind = 24 * a_per.timestep * (365 - start_doy)
            for i in range(0, end_ind + 1, indx_per_day):
                hourly_data_by_day[start_doy] = self._values[i:i + indx_per_day]
                start_doy += 1
            start_doy = 1
            for i in range(end_ind, len(self._values), indx_per_day):
                hourly_data_by_day[start_doy] = self._values[i:i + indx_per_day]
                start_doy += 1
        return hourly_data_by_day
722405
def S(self):
    "'"
    if self.data.day in (11, 12, 13): # Special case
      return u'th'
    last = self.data.day % 10
    if last == 1:
      return u'st'
    if last == 2:
      return u'nd'
    if last == 3:
      return u'rd'
    return u'th'
429144
def assert_daily(var):
    """

    t0, t1 = var.time[:2]

    # This won't work for non-standard calendars. Needs to be implemented in xarray. Comment for now
    if isinstance(t0.values, np.datetime64):
        if pd.infer_freq(var.time.to_pandas()) != 'D':
            raise ValueError("time series is not recognized as daily.")

    # Check that the first time step is one day.
    if np.timedelta64(dt.timedelta(days=1)) != (t1 - t0).data:
        raise ValueError("time series is not daily.")

    # Check that the series has the same time step throughout
    if not var.time.to_pandas().is_monotonic_increasing:
        raise ValueError("time index is not monotonically increasing.")
384413
def display(self):
        
        print('Stats for %s from %s - %s' % (self.name, self.start, self.end))
        if type(self.rf) is float:
            print('Annual risk-free rate considered: %s' % (fmtp(self.rf)))
        print('Summary:')
        data = [[fmtp(self.total_return), fmtn(self.daily_sharpe),
                 fmtp(self.cagr), fmtp(self.max_drawdown)]]
        print(tabulate(data, headers=['Total Return', 'Sharpe',
                                      'CAGR', 'Max Drawdown']))

        print('\nAnnualized Returns:')
        data = [[fmtp(self.mtd), fmtp(self.three_month), fmtp(self.six_month),
                 fmtp(self.ytd), fmtp(self.one_year), fmtp(self.three_year),
                 fmtp(self.five_year), fmtp(self.ten_year),
                 fmtp(self.incep)]]
        print(tabulate(data,
                       headers=['mtd', '3m', '6m', 'ytd', '1y',
                                '3y', '5y', '10y', 'incep.']))

        print('\nPeriodic:')
        data = [
            ['sharpe', fmtn(self.daily_sharpe), fmtn(self.monthly_sharpe),
             fmtn(self.yearly_sharpe)],
            ['mean', fmtp(self.daily_mean), fmtp(self.monthly_mean),
             fmtp(self.yearly_mean)],
            ['vol', fmtp(self.daily_vol), fmtp(self.monthly_vol),
             fmtp(self.yearly_vol)],
            ['skew', fmtn(self.daily_skew), fmtn(self.monthly_skew),
             fmtn(self.yearly_skew)],
            ['kurt', fmtn(self.daily_kurt), fmtn(self.monthly_kurt),
             fmtn(self.yearly_kurt)],
            ['best', fmtp(self.best_day), fmtp(self.best_month),
             fmtp(self.best_year)],
            ['worst', fmtp(self.worst_day), fmtp(self.worst_month),
             fmtp(self.worst_year)]]
        print(tabulate(data, headers=['daily', 'monthly', 'yearly']))

        print('\nDrawdowns:')
        data = [
            [fmtp(self.max_drawdown), fmtp(self.avg_drawdown),
             fmtn(self.avg_drawdown_days)]]
        print(tabulate(data, headers=['max', 'avg', '# days']))

        print('\nMisc:')
        data = [['avg. up month', fmtp(self.avg_up_month)],
                ['avg. down month', fmtp(self.avg_down_month)],
                ['up year %', fmtp(self.win_year_perc)],
                ['12m up %', fmtp(self.twelve_month_win_perc)]]
        print(tabulate(data))