Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 1 addition & 5 deletions docs/source/dev/vbench.rst
Original file line number Diff line number Diff line change
Expand Up @@ -64,11 +64,7 @@ For these cases, the easiest way to compare performance pre- to post-API change

.. code-block:: python

try:
rng = date_range('1/1/2000', periods=N, freq='min')
except NameError:
rng = DateRange('1/1/2000', periods=N, offset=datetools.Minute())
date_range = DateRange
rng = date_range('1/1/2000', periods=N, freq='min')

Pre-PR
~~~~~~
Expand Down
24 changes: 23 additions & 1 deletion statsmodels/compat/pandas.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
from __future__ import absolute_import
import pandas

from distutils.version import LooseVersion

import numpy as np
import pandas


version = LooseVersion(pandas.__version__)

if version >= '0.17.0':
Expand All @@ -23,3 +27,21 @@ def sort_values(df, *args, **kwargs):
df = df.copy()
df.sort(*args, **kwargs)
return df

try:
from pandas import RangeIndex
except ImportError:
RangeIndex = tuple()

try:
from pandas.core.common import is_numeric_dtype
except ImportError:
# Pandas <= 0.14
def is_numeric_dtype(arr_or_dtype):
# Crude implementation only suitable for array-like types
try:
tipo = arr_or_dtype.dtype.type
except AttributeError:
tipo = type(None)
return (issubclass(tipo, (np.number, np.bool_)) and
not issubclass(tipo, (np.datetime64, np.timedelta64)))
5 changes: 3 additions & 2 deletions statsmodels/tsa/ar_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -885,8 +885,9 @@ class ARResultsWrapper(wrap.ResultsWrapper):
#should this be up to the user, or should it be done in TSM init?
#NOTE: not anymore, it's end of year now
ts_dr = ts.date_array(start_date=d1, length=len(sunspots.endog))
pandas_dr = pandas.DateRange(start=d1.datetime,
periods=len(sunspots.endog), timeRule='A@DEC')
pandas_dr = pandas.DatetimeIndex(start=d1.datetime,
periods=len(sunspots.endog),
freq='A-DEC')
#pandas_dr = pandas_dr.shift(-1, pandas.datetools.yearBegin)

dates = np.arange(1700, 1700 + len(sunspots.endog))
Expand Down
87 changes: 32 additions & 55 deletions statsmodels/tsa/base/datetools.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,25 +2,35 @@
asstr, reduce, zip, map)
import re
import datetime
from pandas import Period
from pandas.tseries.frequencies import to_offset

from pandas import datetools as pandas_datetools
from pandas import Period, DatetimeIndex
import numpy as np

#NOTE: All of these frequencies assume end of period (except wrt time)
from pandas.tseries.frequencies import to_offset
class _freq_to_pandas_class(object):
# being lazy, don't want to replace dictionary below
def __getitem__(self, key):
return to_offset(key)
_freq_to_pandas = _freq_to_pandas_class()


def _maybe_convert_period(d, how='end'):
# we usually assume timestamp -> end. maybe make configurable sometime
# see pandas #6779 and #6780
if hasattr(d, 'to_timestamp'):
return d.to_timestamp(how=how)
return d


def _is_datetime_index(dates):
if isinstance(dates[0], (datetime.datetime, Period)):
return True # TimeStamp is a datetime subclass
else:
return False


def _index_date(date, dates):
"""
Gets the index number of a date in a date index.
Expand All @@ -36,16 +46,9 @@ def _index_date(date, dates):
if isinstance(date, string_types):
date = date_parser(date)
try:
if hasattr(dates, 'indexMap'): # 0.7.x
return dates.indexMap[date]
else:
date = dates.get_loc(date)
try: # pandas 0.8.0 returns a boolean array
len(date)
return np.where(date)[0].item()
except TypeError: # expected behavior
return date
except KeyError as err:
date = dates.get_loc(date)
return date
except KeyError:
freq = _infer_freq(dates)
if freq is None:
#TODO: try to intelligently roll forward onto a date in the
Expand All @@ -64,6 +67,7 @@ def _index_date(date, dates):
"date that is in the dates index or use an integer"
% date)


def _date_from_idx(d1, idx, freq):
"""
Returns the date from an index beyond the end of a date series.
Expand All @@ -76,7 +80,8 @@ def _date_from_idx(d1, idx, freq):
This does not do any rounding to make sure that d1 is actually on the
offset. For now, this needs to be taken care of before you get here.
"""
return d1 + idx * _freq_to_pandas[freq]
return _maybe_convert_period(d1) + idx * _freq_to_pandas[freq]


def _idx_from_dates(d1, d2, freq):
"""
Expand All @@ -89,9 +94,10 @@ def _idx_from_dates(d1, d2, freq):
Does not check the start date to see whether it is on the offest but
assumes that it is.
"""
from pandas import DatetimeIndex
return len(DatetimeIndex(start=d1, end=d2,
freq = _freq_to_pandas[freq])) - 1
return len(DatetimeIndex(start=_maybe_convert_period(d1),
end=_maybe_convert_period(d2),
freq=_freq_to_pandas[freq])) - 1


_quarter_to_day = {
"1" : (3, 31),
Expand All @@ -104,6 +110,7 @@ def _idx_from_dates(d1, d2, freq):
"IV" : (12, 31)
}


_mdays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
_months_with_days = lzip(lrange(1,13), _mdays)
_month_to_day = dict(zip(map(str,lrange(1,13)), _months_with_days))
Expand Down Expand Up @@ -164,15 +171,7 @@ def date_parser(timestr, parserinfo=None, **kwargs):
month, day = 12, 31
year = int(timestr)
else:
if (hasattr(pandas_datetools, 'parser') and
not callable(pandas_datetools.parser)):
# exists in 0.8.0 pandas, but it's the class not the module
return pandas_datetools.parser.parse(timestr, parserinfo,
**kwargs)
else: # 0.8.1 pandas version didn't import this into namespace
from dateutil import parser
return parser.parse(timestr, parserinfo, **kwargs)

return pandas_datetools.to_datetime(timestr, **kwargs)

return datetime.datetime(year, month, day)

Expand Down Expand Up @@ -284,33 +283,11 @@ def _infer_freq(dates):
maybe_freqstr = getattr(dates, 'freqstr', None)
if maybe_freqstr is not None:
return maybe_freqstr
try:
from pandas.tseries.api import infer_freq
freq = infer_freq(dates)
return freq
except ImportError:
pass

timedelta = datetime.timedelta
nobs = min(len(dates), 6)
if nobs == 1:
raise ValueError("Cannot infer frequency from one date")
if hasattr(dates, 'values'):
dates = dates.values # can't do a diff on a DateIndex
diff = np.diff(dates[:nobs])
delta = _add_datetimes(diff)
nobs -= 1 # after diff
if delta == timedelta(nobs): #greedily assume 'D'
return 'D'
elif delta == timedelta(nobs + 2):
return 'B'
elif delta == timedelta(7*nobs):
return 'W'
elif delta >= timedelta(28*nobs) and delta <= timedelta(31*nobs):
return 'M'
elif delta >= timedelta(90*nobs) and delta <= timedelta(92*nobs):
return 'Q'
elif delta >= timedelta(365 * nobs) and delta <= timedelta(366 * nobs):
return 'A'
else:
return

# might be a DatetimeIndex
elif hasattr(dates, "inferred_freq"): # see pandas/6637 and others
return dates.inferred_freq
# try to infer from a regular index or something
from pandas.tseries.api import infer_freq
freq = infer_freq(dates)
return freq
4 changes: 3 additions & 1 deletion statsmodels/tsa/base/tests/test_base.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import numpy as np
import numpy.testing as npt
import pandas as pd

from statsmodels.tsa.base.tsa_model import TimeSeriesModel
import numpy.testing as npt
from statsmodels.tools.testing import assert_equal


def test_pandas_nodates_index():

data = [988, 819, 964]
Expand Down
31 changes: 16 additions & 15 deletions statsmodels/tsa/base/tests/test_datetools.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from datetime import datetime
from pandas import DatetimeIndex
import numpy.testing as npt
from statsmodels.tsa.base.datetools import (_date_from_idx,
_idx_from_dates, date_parser, date_range_str, dates_from_str,
Expand Down Expand Up @@ -108,8 +109,6 @@ def test_dates_from_range():
dt_range = dates_from_range("1959m3", length=len(results))




def test_infer_freq():
d1 = datetime(2008, 12, 31)
d2 = datetime(2012, 9, 30)
Expand All @@ -120,21 +119,23 @@ def test_infer_freq():
m = DatetimeIndex(start=d1, end=d2, freq=_freq_to_pandas['M']).values
a = DatetimeIndex(start=d1, end=d2, freq=_freq_to_pandas['A']).values
q = DatetimeIndex(start=d1, end=d2, freq=_freq_to_pandas['Q']).values
assert _infer_freq(w) == 'W-SUN'
assert _infer_freq(a) == 'A-DEC'
assert _infer_freq(q) == 'Q-DEC'
assert _infer_freq(w[:3]) == 'W-SUN'
assert _infer_freq(a[:3]) == 'A-DEC'
assert _infer_freq(q[:3]) == 'Q-DEC'

assert _infer_freq(b[2:5]) == 'B'
assert _infer_freq(b[:3]) == 'D'
assert _infer_freq(b) == 'B'
assert _infer_freq(d) == 'D'
assert _infer_freq(m) == 'M'
assert _infer_freq(d[:3]) == 'D'
assert _infer_freq(m[:3]) == 'M'
npt.assert_(_infer_freq(w) == 'W-SUN')
npt.assert_(_infer_freq(a) == 'A-DEC')
npt.assert_(_infer_freq(q) == 'Q-DEC')
npt.assert_(_infer_freq(w[:3]) == 'W-SUN')
npt.assert_(_infer_freq(a[:3]) == 'A-DEC')
npt.assert_(_infer_freq(q[:3]) == 'Q-DEC')
npt.assert_(_infer_freq(b[2:5]) == 'B')
npt.assert_(_infer_freq(b[:3]) == 'D')
npt.assert_(_infer_freq(b) == 'B')
npt.assert_(_infer_freq(d) == 'D')
npt.assert_(_infer_freq(m) == 'M')
npt.assert_(_infer_freq(d[:3]) == 'D')
npt.assert_(_infer_freq(m[:3]) == 'M')

def test_period_index():
# tests 1285
from pandas import PeriodIndex
dates = PeriodIndex(start="1/1/1990", periods=20, freq="M")
npt.assert_(_infer_freq(dates) == "M")
Loading