def _test_get_latest_price(self): response = MockResponse( textwrap.dedent(""" {"quoteResponse": {"error": null, "result": [{"esgPopulated": false, "exchange": "TOR", "exchangeDataDelayedBy": 15, "exchangeTimezoneName": "America/Toronto", "exchangeTimezoneShortName": "EDT", "fullExchangeName": "Toronto", "gmtOffSetMilliseconds": -14400000, "language": "en-US", "market": "ca_market", "marketState": "CLOSED", "quoteType": "ETF", "regularMarketPrice": 29.99, "regularMarketTime": 1522353589, "sourceInterval": 15, "symbol": "XSP.TO", "tradeable": false}]}} """)) with mock.patch('requests.get', return_value=response): srcprice = yahoo.Source().get_latest_price('XSP.TO') self.assertTrue(isinstance(srcprice.price, Decimal)) self.assertEqual(Decimal('29.99'), srcprice.price) timezone = datetime.timezone(datetime.timedelta(hours=-4), 'America/Toronto') self.assertEqual( datetime.datetime(2018, 3, 29, 15, 59, 49, tzinfo=timezone), srcprice.time) self.assertEqual('CAD', srcprice.quote_currency)
def main(): """Top-level function.""" parser = argparse.ArgumentParser(description=__doc__.strip()) parser.add_argument('price_ledger', help="Ledger file containing a list of prices to fetch") parser.add_argument('output', help="Output directory to write all output files to.") parser.add_argument('-v', '--verbose', action='store_true') args = parser.parse_args() if args.verbose: logging.basicConfig(level=logging.DEBUG, format='%(levelname)-8s: %(message)s') os.makedirs(args.output, exist_ok=True) # Load the example file. logging.info("Reading ledger: %s", args.price_ledger) entries, _, _ = loader.load_file(args.price_ledger) source = yahoo.Source() new_entries = [] for price_entry in entries: assert isinstance(price_entry, data.Price) time = datetime.datetime.combine(price_entry.date, datetime.time(), tzinfo=tz.tzutc()) try: srcprice = source.get_historical_price(price_entry.currency, time) new_entry = price_entry._replace( amount=price_entry.amount._replace(number=srcprice.price)) new_entries.append(new_entry) except yahoo.YahooError as exc: print("ERROR: {}".format(exc)) printer.print_entries(new_entries)
def main(): """Top-level function.""" today = datetime.date.today() parser = argparse.ArgumentParser(description=__doc__.strip()) parser.add_argument('instrument', help="Yahoo!Finance code for financial instrument.") parser.add_argument( 'start', action='store', type=lambda x: dateutil.parser.parse(x).date(), default=today.replace(year=today.year - 1), help="Start date of interval. Default is one year ago.") parser.add_argument('end', action='store', type=lambda x: dateutil.parser.parse(x).date(), default=today, help="End date of interval. Default is today ago.") args = parser.parse_args() # Get the data. source = yahoo.Source() sprices = source.get_daily_prices( args.instrument, datetime.datetime.combine(args.start, datetime.time()), datetime.datetime.combine(args.end, datetime.time())) if sprices is None: raise RuntimeError("Could not fetch from {}".format(source)) # Attempt to infer the right quantization and quantize if succesfull. quant = number.infer_quantization_from_numbers([s.price for s in sprices]) if quant: sprices = [ sprice._replace(price=sprice.price.quantize(quant)) for sprice in sprices ] # Convert to Price entries and output. price_entries = [] for sprice in sprices: price_entries.append( data.Price({}, sprice.time.date(), args.instrument, amount.Amount(sprice.price, sprice.quote_currency))) printer.print_entries(price_entries)
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()))
def _test_get_historical_price(self): response = MockResponse( textwrap.dedent(""" {"chart": {"error": null, "result": [{"indicators": {"adjclose": [{"adjclose": [29.236251831054688, 29.16683006286621, 29.196582794189453, 29.226333618164062]}], "quote": [{"close": [29.479999542236328, 29.40999984741211, 29.440000534057617, 29.469999313354492], "high": [29.510000228881836, 29.489999771118164, 29.469999313354492, 29.579999923706055], "low": [29.34000015258789, 29.350000381469727, 29.399999618530273, 29.43000030517578], "open": [29.360000610351562, 29.43000030517578, 29.43000030517578, 29.530000686645508], "volume": [160800, 118700, 98500, 227800]}]}, "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"]}, "timestamp": [1509111000, 1509370200, 1509456600, 1509543000]}]}}""")) 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())) self.assertTrue(isinstance(srcprice.price, Decimal)) self.assertEqual(Decimal('29.469999313354492'), srcprice.price) timezone = datetime.timezone(datetime.timedelta(hours=-4), 'America/Toronto') self.assertEqual( datetime.datetime(2017, 11, 1, 9, 30, tzinfo=timezone), srcprice.time) self.assertEqual('CAD', srcprice.quote_currency)