Roll date forward to nearest end of quarter
771159
def rollforward(self, date):
        """"""
        if self.onOffset(date):
            return date
        else:
            return date + QuarterEnd(month=self.month)
747516
def get_previous_month(self):
        """"""
        end = utils.get_month_start() - relativedelta(days=1)
        end = utils.to_datetime(end)
        start = utils.get_month_start(end)
        return start, end
1242162
def end_of_quarter(year, quarter)
      case quarter
      when QUARTER_1
        end_of_month(year, 3)
      when QUARTER_2
        end_of_month(year, 6)
      when QUARTER_3
        end_of_month(year, 9)
      when QUARTER_4
        end_of_month(year, 12)
      else
        raise "invalid quarter"
      end
    end
1021418
def roll_sd(input, window, scale = 1.0, ddof = 0):
    ''''''
    nobs, i, j, sx, sxx = 0,0,0,0.,0.
    N = len(input)
    sqrt = np.sqrt

    if window > N:
        raise ValueError('Out of bound')

    output = np.ndarray(N-window+1,dtype=input.dtype)

    for val in input[:window]:
        if val == val:
            nobs += 1
            sx += val
            sxx += val*val

    nn = nobs - ddof
    output[j] = NaN if nn<=0 else sqrt(scale * (sxx - sx*sx/nobs) / nn)

    for val in input[window:]:
        prev = input[j]
        if prev == prev:
            sx -= prev
            sxx -= prev*prev
            nobs -= 1

        if val == val:
            nobs += 1
            sx += val
            sxx += val*val

        j += 1
        nn = nobs - ddof
        output[j] = NaN if nn<=0 else sqrt(scale * (sxx - sx*sx/nobs) / nn)

    return output
199858
def quarter(dt):
    
    quarters = rrule.rrule(
       rrule.MONTHLY,
       bymonth = (1, 4, 7, 10),
       bysetpos = -1,
       dtstart = datetime(dt.year, 1, 1),
       count = 8
    )
    first_day = quarters.before(dt, True)
    last_day = quarters.after(dt) - relativedelta.relativedelta(days=1)
    return (first_day, last_day)
818614
def rollforward(self, dt):
        
        dt = as_timestamp(dt)
        if not self.onOffset(dt):
            dt = dt + self.__class__(1, normalize=self.normalize, **self.kwds)
        return dt
1140111
function calculateDatePos(startDayOfMonth, day) {
	const start = startDayOfMonth - 1;
	day = day - 1;
	const weekDayIndex = (start + day) % WEEKDAYS;
	const weekIndex = Math.ceil((start + day + 1) / WEEKDAYS) - 1;
	return {
		weekIndex,
		weekDayIndex
	};
}
750571
def _apply_index_days(self, i, roll):
        
        nanos = (roll % 2) * Timedelta(days=self.day_of_month - 1).value
        return i + nanos.astype('timedelta64[ns]')
1047511
def cbday_roll(self):
        
        cbday = CustomBusinessDay(n=self.n, normalize=False, **self.kwds)

        if self._prefix.endswith('S'):
            # MonthBegin
            roll_func = cbday.rollforward
        else:
            # MonthEnd
            roll_func = cbday.rollback
        return roll_func
706108
def month_roll(self):
        
        if self._prefix.endswith('S'):
            # MonthBegin
            roll_func = self.m_offset.rollback
        else:
            # MonthEnd
            roll_func = self.m_offset.rollforward
        return roll_func
43004
def rollforward(self, date):
        """"""
        if self.onOffset(date):
            return date
        else:
            return date + YearEnd(month=self.month)
1092195
def trade(args):
    """"""
    print args
    print vars(args)['funds']
    print args.funds
    portfolio = { '$CASH': args.funds }
    print portfolio
    csvreader = csv.reader(args.infile, dialect='excel', quoting=csv.QUOTE_MINIMAL)
    csvwriter = csv.writer(args.outfile, dialect='excel', quoting=csv.QUOTE_MINIMAL)
    detailed = not args.simple
    history = []
    portfolio_history = []

    #trading_days = du.getNYSEdays(datetime.datetime(2010,01,01), datetime.datetime(2012,01,01), datetime.timedelta(hours=16))
    for row in csvreader:
        # print '-'*30 + ' CSV Row ' + '-'*30
        # print ', '.join(row)
        trade_date = datetime.datetime(*[int(i) for i in (row[:3] + [16])])

        if history:
            last_date = datetime.datetime(*(history[-1][:3] + [16])) + datetime.timedelta(days=1)
            # print (date.date() - last_date).days
            while (trade_date - last_date).days > 0:
                print 'Filling in the blanks for {0}'.format(last_date)
                value = portfolio_value(portfolio, last_date, price='close')
                print '   the portfolio value on that date is: {0}'.format(value)
                assert(value != None)
                # NaN for porfolio value indicates a non-trading day
                if not np.isnan(value):
                    history += [[last_date.year, last_date.month, last_date.day] 
                                + (["$CASH", "0.0", "0.0"] if args.trades else [])
                                + ([json.dumps(portfolio)] if detailed else []) + [value]]
                    portfolio_history += [datetime.datetime(last_date.year, last_date.month, last_date.day, 16), portfolio]
                    csvwriter.writerow(history[-1])
                last_date += datetime.timedelta(days=1)
    
        trade_symbol = row[3]
        trade_shares = float(row[5])
        trade_sign = 1 - 2 * int(row[4].strip().upper()[0]=='S')
        # If this the first row in the CSV and the symbol is $CASH then it represents an initial deposit (Sell) or withdrawal (Buy) of cash
        # otherwise se need to add or deduct whatever security was bought or sold.
        # if not (trade_symbol == '$CASH') or history:
        portfolio[trade_symbol] = portfolio.get(trade_symbol, 0) + trade_sign * trade_shares
        trade_price = get_price(symbol=trade_symbol, date=trade_date, price='close')
        while trade_price == None or np.isnan(trade_price) or float(trade_price) == float('nan'):
            trade_date += datetime.timedelta(days=1)
            trade_price = get_price(symbol=trade_symbol, date=trade_date, price='close')
        #print trade_date, trade_symbol, trade_sign, trade_shares, trade_price
        if trade_price and trade_shares and trade_sign in (-1, 1):
            print 'spending cash: {0}'.format(trade_sign * trade_shares * trade_price)
            portfolio['$CASH'] = portfolio.get('$CASH',0.) - trade_sign * trade_shares * trade_price
        else:
            print 'ERROR: bad price, sign, shares: ', trade_price, trade_sign, trade_shares
        history += [[trade_date.year, trade_date.month, trade_date.day, trade_symbol, trade_sign, trade_shares] + ([json.dumps(portfolio)] if detailed else []) + [portfolio_value(portfolio, trade_date, price='close')]]
        csvwriter.writerow(history[-1])
    return metrics(history)
1270167
def previous_quarter(d):
    
    from django_toolkit.datetime_util import quarter as datetime_quarter
    return quarter( (datetime_quarter(datetime(d.year, d.month, d.day))[0] + timedelta(days=-1)).date() )
860644
def daterange_end(value):
    ''''''
    if not value:
        return None
    elif isinstance(value, datetime):
        return value.date()
    elif isinstance(value, date):
        return value

    result = parse_dt(value).date()
    dashes = value.count('-')

    if dashes >= 2:
        # Full date
        return result
    elif dashes == 1:
        # Year/Month
        return result + relativedelta(months=+1, days=-1, day=1)
    else:
        # Year only
        return result.replace(month=12, day=31)
941442
def tickEFP(self, tickerId, tickType, basisPoints, formattedBasisPoints, totalDividends, holdDays, futureExpiry, dividendImpact, dividendsToExpiry):
        """"""
        return _swigibpy.EWrapper_tickEFP(self, tickerId, tickType, basisPoints, formattedBasisPoints, totalDividends, holdDays, futureExpiry, dividendImpact, dividendsToExpiry)
63731
protected final void setReportFormDateRangeAndInterval(final F report) {
        // Determine default interval based on the intervals available for this aggregation
        if (report.getInterval() == null) {
            report.setInterval(AggregationInterval.DAY);
            final Set<AggregationInterval> intervals = this.getIntervals();
            for (final AggregationInterval preferredInterval : PREFERRED_INTERVAL_ORDER) {
                if (intervals.contains(preferredInterval)) {
                    report.setInterval(preferredInterval);
                    break;
                }
            }
        }

        // Set the report end date as today
        final DateMidnight reportEnd;
        if (report.getEnd() == null) {
            reportEnd = new DateMidnight();
            report.setEnd(reportEnd);
        } else {
            reportEnd = report.getEnd();
        }

        // Determine the best start date based on the selected interval
        if (report.getStart() == null) {
            final DateMidnight start;
            switch (report.getInterval()) {
                case MINUTE:
                    {
                        start = reportEnd.minusDays(1);
                        break;
                    }
                case FIVE_MINUTE:
                    {
                        start = reportEnd.minusDays(2);
                        break;
                    }
                case HOUR:
                    {
                        start = reportEnd.minusWeeks(1);
                        break;
                    }
                case DAY:
                    {
                        start = reportEnd.minusMonths(1);
                        break;
                    }
                case WEEK:
                    {
                        start = reportEnd.minusMonths(3);
                        break;
                    }
                case MONTH:
                    {
                        start = reportEnd.minusYears(1);
                        break;
                    }
                case ACADEMIC_TERM:
                    {
                        start = reportEnd.minusYears(2);
                        break;
                    }
                case CALENDAR_QUARTER:
                    {
                        start = reportEnd.minusYears(2);
                        break;
                    }
                case YEAR:
                    {
                        start = reportEnd.minusYears(10);
                        break;
                    }
                default:
                    {
                        start = reportEnd.minusWeeks(1);
                    }
            }

            report.setStart(start);
        }
    }
478078
def get_end_balance(self, after: date) -> Decimal:
        
        # create a new date without hours
        #date_corrected = datetimeutils.end_of_day(after)
        datum = Datum()
        datum.from_date(after)
        datum.end_of_day()
        #log(DEBUG, "getting balance on %s", date_corrected)
        return self.get_balance_on(datum.value)