Skip to content

Commit

Permalink
Raise YahooError when no data is returned.
Browse files Browse the repository at this point in the history
Before this change, the code was raising an exception at getting the
'timestamp' field from the result dict, because this field is not
populated in such use case.
  • Loading branch information
doriath committed Mar 17, 2021
1 parent d2f292f commit 6fe4c5e
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
5 changes: 4 additions & 1 deletion beanprice/sources/yahoo.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@

from beanprice import source


class YahooError(ValueError):
"An error from the Yahoo API."

Expand Down Expand Up @@ -90,6 +89,10 @@ def get_price_series(ticker: str,
tzone = timezone(timedelta(hours=meta['gmtoffset'] / 3600),
meta['exchangeTimezoneName'])

if 'timestamp' not in result:
raise YahooError("Yahoo returned no data for ticker {} for time range {} - {}".format(
ticker, time_begin, time_end))

timestamp_array = result['timestamp']
close_array = result['indicators']['quote'][0]['close']
series = [(datetime.fromtimestamp(timestamp, tz=tzone), Decimal(price))
Expand Down
35 changes: 35 additions & 0 deletions beanprice/sources/yahoo_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,41 @@ def test_parse_response_error_not_none(self):
with self.assertRaises(yahoo.YahooError):
yahoo.parse_response(response)

def test_parse_response_no_timestamp(self):
response = MockResponse(textwrap.dedent("""
{"chart":
{"error": null,
"result": [{"indicators": {"adjclose": [{}],
"quote": [{}]},
"meta": {"chartPreviousClose": 29.25,
"currency": "CAD",
"currentTradingPeriod": {"post": {"end": 1522702800,
"gmtoffset": -14400,
"start": 1522699200,
"timezone": "EDT"},
"pre": {"end": 1522675800,
"gmtoffset": -14400,
"start": 1522670400,
"timezone": "EDT"},
"regular": {"end": 1522699200,
"gmtoffset": -14400,
"start": 1522675800,
"timezone": "EDT"}},
"dataGranularity": "1d",
"exchangeName": "TOR",
"exchangeTimezoneName": "America/Toronto",
"firstTradeDate": 1018872000,
"gmtoffset": -14400,
"instrumentType": "ETF",
"symbol": "XSP.TO",
"timezone": "EDT",
"validRanges": ["1d", "5d", "1mo", "3mo", "6mo", "1y",
"2y", "5y", "10y", "ytd", "max"]}}]}}"""))
with self.assertRaises(yahoo.YahooError):
with mock.patch('requests.get', return_value=response):
srcprice = yahoo.Source().get_historical_price(
'XSP.TO', datetime.datetime(2017, 11, 1, 16, 0, 0, tzinfo=tz.tzutc()))


if __name__ == '__main__':
unittest.main()

0 comments on commit 6fe4c5e

Please sign in to comment.