We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Try to coerce index into datetime before failing.
See what we can do for these types of problems (maybe with a warning about the copy/conversion).

http://stackoverflow.com/questions/19892830/issue-with-dates-in-statsmodels-and-pandas


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `statsmodels/tsa/base/tsa_model.py`
Content:
```
1 from statsmodels.compat.python import lrange
2 import statsmodels.base.model as base
3 from statsmodels.base import data
4 import statsmodels.base.wrapper as wrap
5 from statsmodels.tsa.base import datetools
6 from numpy import arange, asarray
7 from pandas import Index
8 from pandas import datetools as pandas_datetools
9 import datetime
10 
11 _freq_to_pandas = datetools._freq_to_pandas
12 
13 _tsa_doc = """
14     %(model)s
15 
16     Parameters
17     ----------
18     %(params)s
19     dates : array-like of datetime, optional
20         An array-like object of datetime objects. If a pandas object is given
21         for endog or exog, it is assumed to have a DateIndex.
22     freq : str, optional
23         The frequency of the time-series. A Pandas offset or 'B', 'D', 'W',
24         'M', 'A', or 'Q'. This is optional if dates are given.
25     %(extra_params)s
26     %(extra_sections)s
27 """
28 
29 _model_doc = "Timeseries model base class"
30 
31 _generic_params = base._model_params_doc
32 _missing_param_doc = base._missing_param_doc
33 
34 class TimeSeriesModel(base.LikelihoodModel):
35 
36     __doc__ = _tsa_doc % {"model" : _model_doc, "params" : _generic_params,
37                           "extra_params" : _missing_param_doc,
38                           "extra_sections" : ""}
39 
40     def __init__(self, endog, exog=None, dates=None, freq=None, missing='none'):
41         super(TimeSeriesModel, self).__init__(endog, exog, missing=missing)
42         self._init_dates(dates, freq)
43 
44     def _init_dates(self, dates, freq):
45         if dates is None:
46             dates = self.data.row_labels
47 
48         if dates is not None:
49             if (not datetools._is_datetime_index(dates) and
50                     isinstance(self.data, data.PandasData)):
51                 raise ValueError("Given a pandas object and the index does "
52                                  "not contain dates")
53             if not freq:
54                 try:
55                     freq = datetools._infer_freq(dates)
56                 except:
57                     raise ValueError("Frequency inference failed. Use `freq` "
58                             "keyword.")
59             dates = Index(dates)
60         self.data.dates = dates
61         if freq:
62             try: #NOTE: Can drop this once we move to pandas >= 0.8.x
63                 _freq_to_pandas[freq]
64             except:
65                 raise ValueError("freq %s not understood" % freq)
66         self.data.freq = freq
67 
68     def _get_exog_names(self):
69         return self.data.xnames
70 
71     def _set_exog_names(self, vals):
72         if not isinstance(vals, list):
73             vals = [vals]
74         self.data.xnames = vals
75 
76     #overwrite with writable property for (V)AR models
77     exog_names = property(_get_exog_names, _set_exog_names)
78 
79     def _get_dates_loc(self, dates, date):
80         if hasattr(dates, 'indexMap'): # 0.7.x
81             date = dates.indexMap[date]
82         else:
83             date = dates.get_loc(date)
84             try: # pandas 0.8.0 returns a boolean array
85                 len(date)
86                 from numpy import where
87                 date = where(date)[0].item()
88             except TypeError: # this is expected behavior
89                 pass
90         return date
91 
92     def _str_to_date(self, date):
93         """
94         Takes a string and returns a datetime object
95         """
96         return datetools.date_parser(date)
97 
98     def _set_predict_start_date(self, start):
99         dates = self.data.dates
100         if dates is None:
101             return
102         if start > len(dates):
103             raise ValueError("Start must be <= len(endog)")
104         if start == len(dates):
105             self.data.predict_start = datetools._date_from_idx(dates[-1],
106                                                     1, self.data.freq)
107         elif start < len(dates):
108             self.data.predict_start = dates[start]
109         else:
110             raise ValueError("Start must be <= len(dates)")
111 
112     def _get_predict_start(self, start):
113         """
114         Returns the index of the given start date. Subclasses should define
115         default behavior for start = None. That isn't handled here.
116 
117         Start can be a string or an integer if self.data.dates is None.
118         """
119         dates = self.data.dates
120         if isinstance(start, str):
121             if dates is None:
122                 raise ValueError("Got a string for start and dates is None")
123             dtstart = self._str_to_date(start)
124             self.data.predict_start = dtstart
125             try:
126                 start = self._get_dates_loc(dates, dtstart)
127             except KeyError:
128                 raise ValueError("Start must be in dates. Got %s | %s" %
129                         (str(start), str(dtstart)))
130 
131         self._set_predict_start_date(start)
132         return start
133 
134 
135     def _get_predict_end(self, end):
136         """
137         See _get_predict_start for more information. Subclasses do not
138         need to define anything for this.
139         """
140 
141         out_of_sample = 0 # will be overwritten if needed
142         if end is None: # use data for ARIMA - endog changes
143             end = len(self.data.endog) - 1
144 
145         dates = self.data.dates
146         freq = self.data.freq
147 
148         if isinstance(end, str) or (dates is not None
149                                     and isinstance(end, type(dates[0]))):
150             if dates is None:
151                 raise ValueError("Got a string or date for `end` and `dates` is None")
152 
153             if isinstance(end, str):
154                 dtend = self._str_to_date(end)
155             else:
156                 dtend = end  # end could be a pandas TimeStamp not a datetime
157 
158             self.data.predict_end = dtend
159             try:
160                 end = self._get_dates_loc(dates, dtend)
161             except KeyError as err: # end is greater than dates[-1]...probably
162                 if dtend > self.data.dates[-1]:
163                     end = len(self.data.endog) - 1
164                     freq = self.data.freq
165                     out_of_sample = datetools._idx_from_dates(dates[-1], dtend,
166                                             freq)
167                 else:
168                     if freq is None:
169                         raise ValueError("There is no frequency for these "
170                                          "dates and date %s is not in dates "
171                                          "index. Try giving a date that is in "
172                                          "the dates index or use an integer."
173                                          % dtend)
174                     else: #pragma: no cover
175                         raise err # should never get here
176             self._make_predict_dates() # attaches self.data.predict_dates
177 
178         elif isinstance(end, int) and dates is not None:
179             try:
180                 self.data.predict_end = dates[end]
181             except IndexError as err:
182                 nobs = len(self.data.endog) - 1 # as an index
183                 out_of_sample = end - nobs
184                 end = nobs
185                 if freq is not None:
186                     self.data.predict_end = datetools._date_from_idx(dates[-1],
187                             out_of_sample, freq)
188                 elif out_of_sample <= 0: # have no frequency but are in sample
189                     #TODO: what error to catch here to make sure dates is
190                     #on the index?
191                     try:
192                         self.data.predict_end = self._get_dates_loc(dates,
193                                                 end)
194                     except KeyError:
195                         raise
196                 else:
197                     self.data.predict_end = end + out_of_sample
198                     self.data.predict_start = self._get_dates_loc(dates,
199                                                 self.data.predict_start)
200 
201             self._make_predict_dates()
202 
203         elif isinstance(end, int):
204             nobs = len(self.data.endog) - 1 # is an index
205             if end > nobs:
206                 out_of_sample = end - nobs
207                 end = nobs
208 
209         elif freq is None: # should have a date with freq = None
210             raise ValueError("When freq is None, you must give an integer "
211                              "index for end.")
212 
213         else:
214             raise ValueError("no rule for interpreting end")
215 
216         return end, out_of_sample
217 
218     def _make_predict_dates(self):
219         data = self.data
220         dtstart = data.predict_start
221         dtend = data.predict_end
222         freq = data.freq
223 
224         if freq is not None:
225             pandas_freq = _freq_to_pandas[freq]
226             try:
227                 from pandas import DatetimeIndex
228                 dates = DatetimeIndex(start=dtstart, end=dtend,
229                                         freq=pandas_freq)
230             except ImportError as err:
231                 from pandas import DateRange
232                 dates = DateRange(dtstart, dtend, offset = pandas_freq).values
233         # handle
234         elif freq is None and (isinstance(dtstart, int) and
235                                isinstance(dtend, int)):
236             from pandas import Index
237             dates = Index(lrange(dtstart, dtend+1))
238         # if freq is None and dtstart and dtend aren't integers, we're
239         # in sample
240         else:
241             dates = self.data.dates
242             start = self._get_dates_loc(dates, dtstart)
243             end = self._get_dates_loc(dates, dtend)
244             dates = dates[start:end+1] # is this index inclusive?
245         self.data.predict_dates = dates
246 
247 class TimeSeriesModelResults(base.LikelihoodModelResults):
248     def __init__(self, model, params, normalized_cov_params, scale=1.):
249         self.data = model.data
250         super(TimeSeriesModelResults,
251                 self).__init__(model, params, normalized_cov_params, scale)
252 
253 class TimeSeriesResultsWrapper(wrap.ResultsWrapper):
254     _attrs = {}
255     _wrap_attrs = wrap.union_dicts(base.LikelihoodResultsWrapper._wrap_attrs,
256                                     _attrs)
257     _methods = {'predict' : 'dates'}
258     _wrap_methods = wrap.union_dicts(base.LikelihoodResultsWrapper._wrap_methods,
259                                      _methods)
260 wrap.populate_wrapper(TimeSeriesResultsWrapper,
261                       TimeSeriesModelResults)
262 
263 if __name__ == "__main__":
264     import statsmodels.api as sm
265     import datetime
266     import pandas
267 
268     data = sm.datasets.macrodata.load()
269 
270     #make a DataFrame
271     #TODO: attach a DataFrame to some of the datasets, for quicker use
272     dates = [str(int(x[0])) +':'+ str(int(x[1])) \
273              for x in data.data[['year','quarter']]]
274 
275     df = pandas.DataFrame(data.data[['realgdp','realinv','realcons']], index=dates)
276     ex_mod = TimeSeriesModel(df)
277     #ts_series = pandas.Series()
278 
279 
280
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/statsmodels/tsa/base/tsa_model.py b/statsmodels/tsa/base/tsa_model.py
--- a/statsmodels/tsa/base/tsa_model.py
+++ b/statsmodels/tsa/base/tsa_model.py
@@ -4,7 +4,7 @@
 import statsmodels.base.wrapper as wrap
 from statsmodels.tsa.base import datetools
 from numpy import arange, asarray
-from pandas import Index
+from pandas import Index, to_datetime
 from pandas import datetools as pandas_datetools
 import datetime
 
@@ -48,8 +48,11 @@
         if dates is not None:
             if (not datetools._is_datetime_index(dates) and
                     isinstance(self.data, data.PandasData)):
-                raise ValueError("Given a pandas object and the index does "
-                                 "not contain dates")
+                try:
+                    dates = to_datetime(dates)
+                except ValueError:
+                    raise ValueError("Given a pandas object and the index does "
+                                     "not contain dates")
             if not freq:
                 try:
                     freq = datetools._infer_freq(dates)

{"golden_diff": "diff --git a/statsmodels/tsa/base/tsa_model.py b/statsmodels/tsa/base/tsa_model.py\n--- a/statsmodels/tsa/base/tsa_model.py\n+++ b/statsmodels/tsa/base/tsa_model.py\n@@ -4,7 +4,7 @@\n import statsmodels.base.wrapper as wrap\n from statsmodels.tsa.base import datetools\n from numpy import arange, asarray\n-from pandas import Index\n+from pandas import Index, to_datetime\n from pandas import datetools as pandas_datetools\n import datetime\n \n@@ -48,8 +48,11 @@\n         if dates is not None:\n             if (not datetools._is_datetime_index(dates) and\n                     isinstance(self.data, data.PandasData)):\n-                raise ValueError(\"Given a pandas object and the index does \"\n-                                 \"not contain dates\")\n+                try:\n+                    dates = to_datetime(dates)\n+                except ValueError:\n+                    raise ValueError(\"Given a pandas object and the index does \"\n+                                     \"not contain dates\")\n             if not freq:\n                 try:\n                     freq = datetools._infer_freq(dates)\n", "issue": "Try to coerce index into datetime before failing.\nSee what we can do for these types of problems (maybe with a warning about the copy/conversion).\n\nhttp://stackoverflow.com/questions/19892830/issue-with-dates-in-statsmodels-and-pandas\n\n", "before_files": [{"content": "from statsmodels.compat.python import lrange\nimport statsmodels.base.model as base\nfrom statsmodels.base import data\nimport statsmodels.base.wrapper as wrap\nfrom statsmodels.tsa.base import datetools\nfrom numpy import arange, asarray\nfrom pandas import Index\nfrom pandas import datetools as pandas_datetools\nimport datetime\n\n_freq_to_pandas = datetools._freq_to_pandas\n\n_tsa_doc = \"\"\"\n    %(model)s\n\n    Parameters\n    ----------\n    %(params)s\n    dates : array-like of datetime, optional\n        An array-like object of datetime objects. If a pandas object is given\n        for endog or exog, it is assumed to have a DateIndex.\n    freq : str, optional\n        The frequency of the time-series. A Pandas offset or 'B', 'D', 'W',\n        'M', 'A', or 'Q'. This is optional if dates are given.\n    %(extra_params)s\n    %(extra_sections)s\n\"\"\"\n\n_model_doc = \"Timeseries model base class\"\n\n_generic_params = base._model_params_doc\n_missing_param_doc = base._missing_param_doc\n\nclass TimeSeriesModel(base.LikelihoodModel):\n\n    __doc__ = _tsa_doc % {\"model\" : _model_doc, \"params\" : _generic_params,\n                          \"extra_params\" : _missing_param_doc,\n                          \"extra_sections\" : \"\"}\n\n    def __init__(self, endog, exog=None, dates=None, freq=None, missing='none'):\n        super(TimeSeriesModel, self).__init__(endog, exog, missing=missing)\n        self._init_dates(dates, freq)\n\n    def _init_dates(self, dates, freq):\n        if dates is None:\n            dates = self.data.row_labels\n\n        if dates is not None:\n            if (not datetools._is_datetime_index(dates) and\n                    isinstance(self.data, data.PandasData)):\n                raise ValueError(\"Given a pandas object and the index does \"\n                                 \"not contain dates\")\n            if not freq:\n                try:\n                    freq = datetools._infer_freq(dates)\n                except:\n                    raise ValueError(\"Frequency inference failed. Use `freq` \"\n                            \"keyword.\")\n            dates = Index(dates)\n        self.data.dates = dates\n        if freq:\n            try: #NOTE: Can drop this once we move to pandas >= 0.8.x\n                _freq_to_pandas[freq]\n            except:\n                raise ValueError(\"freq %s not understood\" % freq)\n        self.data.freq = freq\n\n    def _get_exog_names(self):\n        return self.data.xnames\n\n    def _set_exog_names(self, vals):\n        if not isinstance(vals, list):\n            vals = [vals]\n        self.data.xnames = vals\n\n    #overwrite with writable property for (V)AR models\n    exog_names = property(_get_exog_names, _set_exog_names)\n\n    def _get_dates_loc(self, dates, date):\n        if hasattr(dates, 'indexMap'): # 0.7.x\n            date = dates.indexMap[date]\n        else:\n            date = dates.get_loc(date)\n            try: # pandas 0.8.0 returns a boolean array\n                len(date)\n                from numpy import where\n                date = where(date)[0].item()\n            except TypeError: # this is expected behavior\n                pass\n        return date\n\n    def _str_to_date(self, date):\n        \"\"\"\n        Takes a string and returns a datetime object\n        \"\"\"\n        return datetools.date_parser(date)\n\n    def _set_predict_start_date(self, start):\n        dates = self.data.dates\n        if dates is None:\n            return\n        if start > len(dates):\n            raise ValueError(\"Start must be <= len(endog)\")\n        if start == len(dates):\n            self.data.predict_start = datetools._date_from_idx(dates[-1],\n                                                    1, self.data.freq)\n        elif start < len(dates):\n            self.data.predict_start = dates[start]\n        else:\n            raise ValueError(\"Start must be <= len(dates)\")\n\n    def _get_predict_start(self, start):\n        \"\"\"\n        Returns the index of the given start date. Subclasses should define\n        default behavior for start = None. That isn't handled here.\n\n        Start can be a string or an integer if self.data.dates is None.\n        \"\"\"\n        dates = self.data.dates\n        if isinstance(start, str):\n            if dates is None:\n                raise ValueError(\"Got a string for start and dates is None\")\n            dtstart = self._str_to_date(start)\n            self.data.predict_start = dtstart\n            try:\n                start = self._get_dates_loc(dates, dtstart)\n            except KeyError:\n                raise ValueError(\"Start must be in dates. Got %s | %s\" %\n                        (str(start), str(dtstart)))\n\n        self._set_predict_start_date(start)\n        return start\n\n\n    def _get_predict_end(self, end):\n        \"\"\"\n        See _get_predict_start for more information. Subclasses do not\n        need to define anything for this.\n        \"\"\"\n\n        out_of_sample = 0 # will be overwritten if needed\n        if end is None: # use data for ARIMA - endog changes\n            end = len(self.data.endog) - 1\n\n        dates = self.data.dates\n        freq = self.data.freq\n\n        if isinstance(end, str) or (dates is not None\n                                    and isinstance(end, type(dates[0]))):\n            if dates is None:\n                raise ValueError(\"Got a string or date for `end` and `dates` is None\")\n\n            if isinstance(end, str):\n                dtend = self._str_to_date(end)\n            else:\n                dtend = end  # end could be a pandas TimeStamp not a datetime\n\n            self.data.predict_end = dtend\n            try:\n                end = self._get_dates_loc(dates, dtend)\n            except KeyError as err: # end is greater than dates[-1]...probably\n                if dtend > self.data.dates[-1]:\n                    end = len(self.data.endog) - 1\n                    freq = self.data.freq\n                    out_of_sample = datetools._idx_from_dates(dates[-1], dtend,\n                                            freq)\n                else:\n                    if freq is None:\n                        raise ValueError(\"There is no frequency for these \"\n                                         \"dates and date %s is not in dates \"\n                                         \"index. Try giving a date that is in \"\n                                         \"the dates index or use an integer.\"\n                                         % dtend)\n                    else: #pragma: no cover\n                        raise err # should never get here\n            self._make_predict_dates() # attaches self.data.predict_dates\n\n        elif isinstance(end, int) and dates is not None:\n            try:\n                self.data.predict_end = dates[end]\n            except IndexError as err:\n                nobs = len(self.data.endog) - 1 # as an index\n                out_of_sample = end - nobs\n                end = nobs\n                if freq is not None:\n                    self.data.predict_end = datetools._date_from_idx(dates[-1],\n                            out_of_sample, freq)\n                elif out_of_sample <= 0: # have no frequency but are in sample\n                    #TODO: what error to catch here to make sure dates is\n                    #on the index?\n                    try:\n                        self.data.predict_end = self._get_dates_loc(dates,\n                                                end)\n                    except KeyError:\n                        raise\n                else:\n                    self.data.predict_end = end + out_of_sample\n                    self.data.predict_start = self._get_dates_loc(dates,\n                                                self.data.predict_start)\n\n            self._make_predict_dates()\n\n        elif isinstance(end, int):\n            nobs = len(self.data.endog) - 1 # is an index\n            if end > nobs:\n                out_of_sample = end - nobs\n                end = nobs\n\n        elif freq is None: # should have a date with freq = None\n            raise ValueError(\"When freq is None, you must give an integer \"\n                             \"index for end.\")\n\n        else:\n            raise ValueError(\"no rule for interpreting end\")\n\n        return end, out_of_sample\n\n    def _make_predict_dates(self):\n        data = self.data\n        dtstart = data.predict_start\n        dtend = data.predict_end\n        freq = data.freq\n\n        if freq is not None:\n            pandas_freq = _freq_to_pandas[freq]\n            try:\n                from pandas import DatetimeIndex\n                dates = DatetimeIndex(start=dtstart, end=dtend,\n                                        freq=pandas_freq)\n            except ImportError as err:\n                from pandas import DateRange\n                dates = DateRange(dtstart, dtend, offset = pandas_freq).values\n        # handle\n        elif freq is None and (isinstance(dtstart, int) and\n                               isinstance(dtend, int)):\n            from pandas import Index\n            dates = Index(lrange(dtstart, dtend+1))\n        # if freq is None and dtstart and dtend aren't integers, we're\n        # in sample\n        else:\n            dates = self.data.dates\n            start = self._get_dates_loc(dates, dtstart)\n            end = self._get_dates_loc(dates, dtend)\n            dates = dates[start:end+1] # is this index inclusive?\n        self.data.predict_dates = dates\n\nclass TimeSeriesModelResults(base.LikelihoodModelResults):\n    def __init__(self, model, params, normalized_cov_params, scale=1.):\n        self.data = model.data\n        super(TimeSeriesModelResults,\n                self).__init__(model, params, normalized_cov_params, scale)\n\nclass TimeSeriesResultsWrapper(wrap.ResultsWrapper):\n    _attrs = {}\n    _wrap_attrs = wrap.union_dicts(base.LikelihoodResultsWrapper._wrap_attrs,\n                                    _attrs)\n    _methods = {'predict' : 'dates'}\n    _wrap_methods = wrap.union_dicts(base.LikelihoodResultsWrapper._wrap_methods,\n                                     _methods)\nwrap.populate_wrapper(TimeSeriesResultsWrapper,\n                      TimeSeriesModelResults)\n\nif __name__ == \"__main__\":\n    import statsmodels.api as sm\n    import datetime\n    import pandas\n\n    data = sm.datasets.macrodata.load()\n\n    #make a DataFrame\n    #TODO: attach a DataFrame to some of the datasets, for quicker use\n    dates = [str(int(x[0])) +':'+ str(int(x[1])) \\\n             for x in data.data[['year','quarter']]]\n\n    df = pandas.DataFrame(data.data[['realgdp','realinv','realcons']], index=dates)\n    ex_mod = TimeSeriesModel(df)\n    #ts_series = pandas.Series()\n\n\n", "path": "statsmodels/tsa/base/tsa_model.py"}], "after_files": [{"content": "from statsmodels.compat.python import lrange\nimport statsmodels.base.model as base\nfrom statsmodels.base import data\nimport statsmodels.base.wrapper as wrap\nfrom statsmodels.tsa.base import datetools\nfrom numpy import arange, asarray\nfrom pandas import Index, to_datetime\nfrom pandas import datetools as pandas_datetools\nimport datetime\n\n_freq_to_pandas = datetools._freq_to_pandas\n\n_tsa_doc = \"\"\"\n    %(model)s\n\n    Parameters\n    ----------\n    %(params)s\n    dates : array-like of datetime, optional\n        An array-like object of datetime objects. If a pandas object is given\n        for endog or exog, it is assumed to have a DateIndex.\n    freq : str, optional\n        The frequency of the time-series. A Pandas offset or 'B', 'D', 'W',\n        'M', 'A', or 'Q'. This is optional if dates are given.\n    %(extra_params)s\n    %(extra_sections)s\n\"\"\"\n\n_model_doc = \"Timeseries model base class\"\n\n_generic_params = base._model_params_doc\n_missing_param_doc = base._missing_param_doc\n\nclass TimeSeriesModel(base.LikelihoodModel):\n\n    __doc__ = _tsa_doc % {\"model\" : _model_doc, \"params\" : _generic_params,\n                          \"extra_params\" : _missing_param_doc,\n                          \"extra_sections\" : \"\"}\n\n    def __init__(self, endog, exog=None, dates=None, freq=None, missing='none'):\n        super(TimeSeriesModel, self).__init__(endog, exog, missing=missing)\n        self._init_dates(dates, freq)\n\n    def _init_dates(self, dates, freq):\n        if dates is None:\n            dates = self.data.row_labels\n\n        if dates is not None:\n            if (not datetools._is_datetime_index(dates) and\n                    isinstance(self.data, data.PandasData)):\n                try:\n                    dates = to_datetime(dates)\n                except ValueError:\n                    raise ValueError(\"Given a pandas object and the index does \"\n                                     \"not contain dates\")\n            if not freq:\n                try:\n                    freq = datetools._infer_freq(dates)\n                except:\n                    raise ValueError(\"Frequency inference failed. Use `freq` \"\n                            \"keyword.\")\n            dates = Index(dates)\n        self.data.dates = dates\n        if freq:\n            try: #NOTE: Can drop this once we move to pandas >= 0.8.x\n                _freq_to_pandas[freq]\n            except:\n                raise ValueError(\"freq %s not understood\" % freq)\n        self.data.freq = freq\n\n    def _get_exog_names(self):\n        return self.data.xnames\n\n    def _set_exog_names(self, vals):\n        if not isinstance(vals, list):\n            vals = [vals]\n        self.data.xnames = vals\n\n    #overwrite with writable property for (V)AR models\n    exog_names = property(_get_exog_names, _set_exog_names)\n\n    def _get_dates_loc(self, dates, date):\n        if hasattr(dates, 'indexMap'): # 0.7.x\n            date = dates.indexMap[date]\n        else:\n            date = dates.get_loc(date)\n            try: # pandas 0.8.0 returns a boolean array\n                len(date)\n                from numpy import where\n                date = where(date)[0].item()\n            except TypeError: # this is expected behavior\n                pass\n        return date\n\n    def _str_to_date(self, date):\n        \"\"\"\n        Takes a string and returns a datetime object\n        \"\"\"\n        return datetools.date_parser(date)\n\n    def _set_predict_start_date(self, start):\n        dates = self.data.dates\n        if dates is None:\n            return\n        if start > len(dates):\n            raise ValueError(\"Start must be <= len(endog)\")\n        if start == len(dates):\n            self.data.predict_start = datetools._date_from_idx(dates[-1],\n                                                    1, self.data.freq)\n        elif start < len(dates):\n            self.data.predict_start = dates[start]\n        else:\n            raise ValueError(\"Start must be <= len(dates)\")\n\n    def _get_predict_start(self, start):\n        \"\"\"\n        Returns the index of the given start date. Subclasses should define\n        default behavior for start = None. That isn't handled here.\n\n        Start can be a string or an integer if self.data.dates is None.\n        \"\"\"\n        dates = self.data.dates\n        if isinstance(start, str):\n            if dates is None:\n                raise ValueError(\"Got a string for start and dates is None\")\n            dtstart = self._str_to_date(start)\n            self.data.predict_start = dtstart\n            try:\n                start = self._get_dates_loc(dates, dtstart)\n            except KeyError:\n                raise ValueError(\"Start must be in dates. Got %s | %s\" %\n                        (str(start), str(dtstart)))\n\n        self._set_predict_start_date(start)\n        return start\n\n\n    def _get_predict_end(self, end):\n        \"\"\"\n        See _get_predict_start for more information. Subclasses do not\n        need to define anything for this.\n        \"\"\"\n\n        out_of_sample = 0 # will be overwritten if needed\n        if end is None: # use data for ARIMA - endog changes\n            end = len(self.data.endog) - 1\n\n        dates = self.data.dates\n        freq = self.data.freq\n\n        if isinstance(end, str) or (dates is not None\n                                    and isinstance(end, type(dates[0]))):\n            if dates is None:\n                raise ValueError(\"Got a string or date for `end` and `dates` is None\")\n\n            if isinstance(end, str):\n                dtend = self._str_to_date(end)\n            else:\n                dtend = end  # end could be a pandas TimeStamp not a datetime\n\n            self.data.predict_end = dtend\n            try:\n                end = self._get_dates_loc(dates, dtend)\n            except KeyError as err: # end is greater than dates[-1]...probably\n                if dtend > self.data.dates[-1]:\n                    end = len(self.data.endog) - 1\n                    freq = self.data.freq\n                    out_of_sample = datetools._idx_from_dates(dates[-1], dtend,\n                                            freq)\n                else:\n                    if freq is None:\n                        raise ValueError(\"There is no frequency for these \"\n                                         \"dates and date %s is not in dates \"\n                                         \"index. Try giving a date that is in \"\n                                         \"the dates index or use an integer.\"\n                                         % dtend)\n                    else: #pragma: no cover\n                        raise err # should never get here\n            self._make_predict_dates() # attaches self.data.predict_dates\n\n        elif isinstance(end, int) and dates is not None:\n            try:\n                self.data.predict_end = dates[end]\n            except IndexError as err:\n                nobs = len(self.data.endog) - 1 # as an index\n                out_of_sample = end - nobs\n                end = nobs\n                if freq is not None:\n                    self.data.predict_end = datetools._date_from_idx(dates[-1],\n                            out_of_sample, freq)\n                elif out_of_sample <= 0: # have no frequency but are in sample\n                    #TODO: what error to catch here to make sure dates is\n                    #on the index?\n                    try:\n                        self.data.predict_end = self._get_dates_loc(dates,\n                                                end)\n                    except KeyError:\n                        raise\n                else:\n                    self.data.predict_end = end + out_of_sample\n                    self.data.predict_start = self._get_dates_loc(dates,\n                                                self.data.predict_start)\n\n            self._make_predict_dates()\n\n        elif isinstance(end, int):\n            nobs = len(self.data.endog) - 1 # is an index\n            if end > nobs:\n                out_of_sample = end - nobs\n                end = nobs\n\n        elif freq is None: # should have a date with freq = None\n            raise ValueError(\"When freq is None, you must give an integer \"\n                             \"index for end.\")\n\n        else:\n            raise ValueError(\"no rule for interpreting end\")\n\n        return end, out_of_sample\n\n    def _make_predict_dates(self):\n        data = self.data\n        dtstart = data.predict_start\n        dtend = data.predict_end\n        freq = data.freq\n\n        if freq is not None:\n            pandas_freq = _freq_to_pandas[freq]\n            try:\n                from pandas import DatetimeIndex\n                dates = DatetimeIndex(start=dtstart, end=dtend,\n                                        freq=pandas_freq)\n            except ImportError as err:\n                from pandas import DateRange\n                dates = DateRange(dtstart, dtend, offset = pandas_freq).values\n        # handle\n        elif freq is None and (isinstance(dtstart, int) and\n                               isinstance(dtend, int)):\n            from pandas import Index\n            dates = Index(lrange(dtstart, dtend+1))\n        # if freq is None and dtstart and dtend aren't integers, we're\n        # in sample\n        else:\n            dates = self.data.dates\n            start = self._get_dates_loc(dates, dtstart)\n            end = self._get_dates_loc(dates, dtend)\n            dates = dates[start:end+1] # is this index inclusive?\n        self.data.predict_dates = dates\n\nclass TimeSeriesModelResults(base.LikelihoodModelResults):\n    def __init__(self, model, params, normalized_cov_params, scale=1.):\n        self.data = model.data\n        super(TimeSeriesModelResults,\n                self).__init__(model, params, normalized_cov_params, scale)\n\nclass TimeSeriesResultsWrapper(wrap.ResultsWrapper):\n    _attrs = {}\n    _wrap_attrs = wrap.union_dicts(base.LikelihoodResultsWrapper._wrap_attrs,\n                                    _attrs)\n    _methods = {'predict' : 'dates'}\n    _wrap_methods = wrap.union_dicts(base.LikelihoodResultsWrapper._wrap_methods,\n                                     _methods)\nwrap.populate_wrapper(TimeSeriesResultsWrapper,\n                      TimeSeriesModelResults)\n\nif __name__ == \"__main__\":\n    import statsmodels.api as sm\n    import datetime\n    import pandas\n\n    data = sm.datasets.macrodata.load()\n\n    #make a DataFrame\n    #TODO: attach a DataFrame to some of the datasets, for quicker use\n    dates = [str(int(x[0])) +':'+ str(int(x[1])) \\\n             for x in data.data[['year','quarter']]]\n\n    df = pandas.DataFrame(data.data[['realgdp','realinv','realcons']], index=dates)\n    ex_mod = TimeSeriesModel(df)\n    #ts_series = pandas.Series()\n\n\n", "path": "statsmodels/tsa/base/tsa_model.py"}]}