|
| 1 | +""" |
| 2 | +script to check converting covidcast api calls with Epidata.covidcast Epidata.covidcast_meta |
| 3 | +""" |
| 4 | +from typing import Union, Iterable |
| 5 | +from datetime import datetime, timedelta, date |
| 6 | +import pandas as pd |
| 7 | +import covidcast |
| 8 | +from delphi_epidata import Epidata |
| 9 | +from pandas.testing import assert_frame_equal |
| 10 | +import os |
| 11 | +from epiweeks import Week |
| 12 | + |
| 13 | +API_KEY = os.environ.get('DELPHI_API_KEY') |
| 14 | +covidcast.use_api_key(API_KEY) |
| 15 | + |
| 16 | +Epidata.debug = True |
| 17 | +Epidata.auth = ("epidata", API_KEY) |
| 18 | + |
| 19 | +def _parse_datetimes(date_int: int, time_type: str, date_format: str = "%Y%m%d") -> Union[pd.Timestamp, None]: |
| 20 | + """Convert a date or epiweeks string into timestamp objects. |
| 21 | +
|
| 22 | + Datetimes (length 8) are converted to their corresponding date, while epiweeks (length 6) |
| 23 | + are converted to the date of the start of the week. Returns nan otherwise |
| 24 | +
|
| 25 | + Epiweeks use the CDC format. |
| 26 | +
|
| 27 | + date_int: Int representation of date. |
| 28 | + time_type: The temporal resolution to request this data. Most signals |
| 29 | + are available at the "day" resolution (the default); some are only |
| 30 | + available at the "week" resolution, representing an MMWR week ("epiweek"). |
| 31 | + date_format: String of the date format to parse. |
| 32 | + :returns: Timestamp. |
| 33 | + """ |
| 34 | + date_str = str(date_int) |
| 35 | + if time_type == "day": |
| 36 | + return pd.to_datetime(date_str, format=date_format) |
| 37 | + if time_type == "week": |
| 38 | + epiwk = Week(int(date_str[:4]), int(date_str[-2:])) |
| 39 | + return pd.to_datetime(epiwk.startdate()) |
| 40 | + return None |
| 41 | + |
| 42 | + |
| 43 | +def ported_metadata() -> Union[pd.DataFrame, None]: |
| 44 | + """ |
| 45 | + Make covidcast metadata api call. |
| 46 | +
|
| 47 | + Returns |
| 48 | + ------- |
| 49 | + pd.DataFrame of covidcast metadata. |
| 50 | + """ |
| 51 | + response = Epidata.covidcast_meta() |
| 52 | + |
| 53 | + if response["result"] != 1: |
| 54 | + # Something failed in the API and we did not get real metadata |
| 55 | + raise RuntimeError("Error when fetching metadata from the API", response["message"]) |
| 56 | + |
| 57 | + df = pd.DataFrame.from_dict(response["epidata"]) |
| 58 | + df["min_time"] = df.apply(lambda x: _parse_datetimes(x.min_time, x.time_type), axis=1) |
| 59 | + df["max_time"] = df.apply(lambda x: _parse_datetimes(x.max_time, x.time_type), axis=1) |
| 60 | + df["last_update"] = pd.to_datetime(df["last_update"], unit="s") |
| 61 | + return df |
| 62 | + |
| 63 | + |
| 64 | +def ported_signal( |
| 65 | + data_source: str, |
| 66 | + signal: str, # pylint: disable=W0621 |
| 67 | + start_day: date = None, |
| 68 | + end_day: date = None, |
| 69 | + geo_type: str = "county", |
| 70 | + geo_values: Union[str, Iterable[str]] = "*", |
| 71 | + as_of: date = None, |
| 72 | + lag: int = None, |
| 73 | + time_type: str = "day", |
| 74 | +) -> Union[pd.DataFrame, None]: |
| 75 | + """ |
| 76 | + Makes covidcast signal api call. |
| 77 | +
|
| 78 | + data_source: String identifying the data source to query, such as |
| 79 | + ``"fb-survey"``. |
| 80 | + signal: String identifying the signal from that source to query, |
| 81 | + such as ``"smoothed_cli"``. |
| 82 | + start_day: Query data beginning on this date. Provided as a |
| 83 | + ``datetime.date`` object. If ``start_day`` is ``None``, defaults to the |
| 84 | + first day data is available for this signal. If ``time_type == "week"``, then |
| 85 | + this is rounded to the epiweek containing the day (i.e. the previous Sunday). |
| 86 | + end_day: Query data up to this date, inclusive. Provided as a |
| 87 | + ``datetime.date`` object. If ``end_day`` is ``None``, defaults to the most |
| 88 | + recent day data is available for this signal. If ``time_type == "week"``, then |
| 89 | + this is rounded to the epiweek containing the day (i.e. the previous Sunday). |
| 90 | + geo_type: The geography type for which to request this data, such as |
| 91 | + ``"county"`` or ``"state"``. Available types are described in the |
| 92 | + COVIDcast signal documentation. Defaults to ``"county"``. |
| 93 | + geo_values: The geographies to fetch data for. The default, ``"*"``, |
| 94 | + fetches all geographies. To fetch one geography, specify its ID as a |
| 95 | + string; multiple geographies can be provided as an iterable (list, tuple, |
| 96 | + ...) of strings. |
| 97 | + as_of: Fetch only data that was available on or before this date, |
| 98 | + provided as a ``datetime.date`` object. If ``None``, the default, return |
| 99 | + the most recent available data. If ``time_type == "week"``, then |
| 100 | + this is rounded to the epiweek containing the day (i.e. the previous Sunday). |
| 101 | + lag: Integer. If, for example, ``lag=3``, fetch only data that was |
| 102 | + published or updated exactly 3 days after the date. For example, a row |
| 103 | + with ``time_value`` of June 3 will only be included in the results if its |
| 104 | + data was issued or updated on June 6. If ``None``, the default, return the |
| 105 | + most recently issued data regardless of its lag. |
| 106 | + time_type: The temporal resolution to request this data. Most signals |
| 107 | + are available at the "day" resolution (the default); some are only |
| 108 | + available at the "week" resolution, representing an MMWR week ("epiweek"). |
| 109 | + :returns: A Pandas data frame with matching data, or ``None`` if no data is |
| 110 | + returned. Each row is one observation on one day in one geographic location. |
| 111 | + Contains the following columns: |
| 112 | + """ |
| 113 | + if start_day > end_day: |
| 114 | + raise ValueError( |
| 115 | + "end_day must be on or after start_day, but " f"start_day = '{start_day}', end_day = '{end_day}'" |
| 116 | + ) |
| 117 | + |
| 118 | + response = Epidata.covidcast( |
| 119 | + data_source, |
| 120 | + signal, |
| 121 | + time_type=time_type, |
| 122 | + geo_type=geo_type, |
| 123 | + time_values=Epidata.range(start_day.strftime("%Y%m%d"), end_day.strftime("%Y%m%d")), |
| 124 | + geo_value=geo_values, |
| 125 | + as_of=as_of, |
| 126 | + lag=lag, |
| 127 | + ) |
| 128 | + if response["result"] != 1: |
| 129 | + # Something failed in the API and we did not get real metadata |
| 130 | + raise RuntimeError("Error when fetching signal data from the API", response["message"]) |
| 131 | + |
| 132 | + api_df = pd.DataFrame.from_dict(response["epidata"]) |
| 133 | + api_df["issue"] = pd.to_datetime(api_df["issue"], format="%Y%m%d") |
| 134 | + api_df["time_value"] = pd.to_datetime(api_df["time_value"], format="%Y%m%d") |
| 135 | + api_df.drop("direction", axis=1, inplace=True) |
| 136 | + api_df["data_source"] = data_source |
| 137 | + api_df["signal"] = signal |
| 138 | + |
| 139 | + return api_df |
| 140 | + |
| 141 | +def check_metadata(): |
| 142 | + expected_df = covidcast.metadata() |
| 143 | + df = ported_metadata().metadata() |
| 144 | + assert_frame_equal(expected_df, df) |
| 145 | + |
| 146 | +def check_signal(): |
| 147 | + meta_df = covidcast.metadata() |
| 148 | + startdate = datetime(year=2022, month=2, day=1) |
| 149 | + data_filter = (meta_df["max_time"] >= startdate) |
| 150 | + signal_df = meta_df[data_filter].groupby("data_source")["signal"].agg(['unique']) |
| 151 | + enddate = startdate + timedelta(days=3) |
| 152 | + |
| 153 | + for data_source, row in signal_df.iterrows(): |
| 154 | + signals = list(row[0]) |
| 155 | + for signal in signals: |
| 156 | + expected_df = covidcast.signal(data_source, signal, start_day=startdate, end_day=enddate, geo_type="state") |
| 157 | + if expected_df is None: |
| 158 | + print("%s %s %s %s not existing", data_source, signal, startdate, enddate) |
| 159 | + |
| 160 | + df = ported_signal(data_source, signal, start_day=startdate, end_day=enddate, geo_type="state") |
| 161 | + |
| 162 | + check = df.merge(expected_df, indicator=True) |
| 163 | + assert (check["_merge"] == "both").all() |
| 164 | + assert check["_left_only"].empty |
| 165 | + assert check["_right_only"].empty |
| 166 | + |
| 167 | +if __name__ == "__main__": |
| 168 | + # check_metadata() |
| 169 | + check_signal() |
0 commit comments