Search code examples
pythongoogle-finance-api

How can I treat this ampersand as text?


from googlefinance import getQuotes

print(getQuotes("NSE:M\&MFIN"),)

The ampersand is being treated as code but I want to treat it as text; I get a bad request exception:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/.../site-packages/googlefinance/__init__.py", line 70, in getQuotes
    content = json.loads(request(symbols))
  File "/.../site-packages/googlefinance/__init__.py", line 33, in request
    resp = urlopen(req)
  File "/.../urllib/request.py", line 223, in urlopen
    return opener.open(url, data, timeout)
  File "/.../urllib/request.py", line 532, in open
    response = meth(req, response)
  File "/.../urllib/request.py", line 642, in http_response
    'http', request, response, code, msg, hdrs)
  File "/.../urllib/request.py", line 570, in error
    return self._call_chain(*args)
  File "/.../urllib/request.py", line 504, in _call_chain
    result = func(*args)
  File "/.../urllib/request.py", line 650, in http_error_default
    raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 400: Bad Request

I tried to escape it (using a \) but this did not work either.

How can I treat this ampersand as text?


Solution

  • The library is rather naive in that it just appends the symbols to a URL without proper encoding, see the source code:

    def buildUrl(symbols):
        symbol_list = ','.join([symbol for symbol in symbols])
        # a deprecated but still active & correct api
        return 'http://finance.google.com/finance/info?client=ig&q=' \
            + symbol_list
    

    You can work around this by manually quoting up front, using the urllib.parse.quote() function:

    from urllib.parse import quote
    
    print(getQuotes(quote("NSE:M&MFIN")))
    

    Demo:

    >>> from googlefinance import getQuotes
    >>> from urllib.parse import quote
    >>> print(getQuotes(quote("NSE:M&MFIN")))
    [{'ID': '11784956', 'StockSymbol': 'M&MFIN', 'Index': 'NSE', 'LastTradePrice': '416.55', 'LastTradeWithCurrency': '&#8377;416.55', 'LastTradeTime': '3:30PM GMT+5:30', 'LastTradeDateTime': '2017-08-18T15:30:00Z', 'LastTradeDateTimeLong': 'Aug 18, 3:30PM GMT+5:30'}]