Skip to content

Commit

Permalink
Merge pull request #1354 from ranaroussi/hotfix/rename-basic-info
Browse files Browse the repository at this point in the history
Rename 'basic_info' -> 'fast_info'
  • Loading branch information
ValueRaider committed Jan 26, 2023
2 parents f705678 + ad3f4ca commit b43072c
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 27 deletions.
23 changes: 12 additions & 11 deletions tests/ticker.py
Original file line number Diff line number Diff line change
Expand Up @@ -685,19 +685,18 @@ def tearDown(self):
self.ticker = None

def test_info(self):
data = self.ticker.info
data = self.tickers[0].info
self.assertIsInstance(data, dict, "data has wrong type")
self.assertIn("symbol", data.keys(), "Did not find expected key in info dict")
self.assertEqual("GOOGL", data["symbol"], "Wrong symbol value in info dict")
self.assertEqual("ESLT.TA", data["symbol"], "Wrong symbol value in info dict")

def test_basic_info(self):
def test_fast_info(self):
yf.scrapers.quote.PRUNE_INFO = False

# basic_info_keys = self.ticker.basic_info.keys()
basic_info_keys = set()
fast_info_keys = set()
for ticker in self.tickers:
basic_info_keys.update(set(ticker.basic_info.keys()))
basic_info_keys = sorted(list(basic_info_keys))
fast_info_keys.update(set(ticker.fast_info.keys()))
fast_info_keys = sorted(list(fast_info_keys))

key_rename_map = {}
key_rename_map["last_price"] = ["currentPrice", "regularMarketPrice"]
Expand Down Expand Up @@ -737,7 +736,7 @@ def test_basic_info(self):
custom_tolerances["fifty_day_average"] = 1e-2
custom_tolerances["two_hundred_day_average"] = 1e-2

for k in basic_info_keys:
for k in fast_info_keys:
if k in key_rename_map:
k2 = key_rename_map[k]
else:
Expand All @@ -750,7 +749,7 @@ def test_basic_info(self):
for ticker in self.tickers:
if not m in ticker.info:
print(sorted(list(ticker.info.keys())))
raise Exception("Need to add/fix mapping for basic_info key", k)
raise Exception("Need to add/fix mapping for fast_info key", k)

if k in bad_keys:
# Doesn't match, investigate why
Expand All @@ -762,9 +761,11 @@ def test_basic_info(self):
rtol = 5e-3
# rtol = 1e-4

print(f"Testing key {m} -> {k} ticker={ticker.ticker}")
# if k in approximate_keys:
v1 = ticker.basic_info[k]
v1 = ticker.fast_info[k]
if k == "market_cap" and ticker.fast_info["currency"] in ["GBp", "ILA"]:
# Adjust for currency to match Yahoo:
v1 *= 0.01
v2 = ticker.info[m]
if isinstance(v1, float) or isinstance(v2, int):
self.assertTrue(np.isclose(v1, v2, rtol=rtol), f"{k}: {v1} != {v2}")
Expand Down
31 changes: 18 additions & 13 deletions yfinance/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@
_ROOT_URL_ = 'https://finance.yahoo.com'


class BasicInfo:
class FastInfo:
# Contain small subset of info[] items that can be fetched faster elsewhere.
# Imitates a dict.
def __init__(self, tickerBaseObject):
Expand Down Expand Up @@ -99,7 +99,7 @@ def __getitem__(self, k):
if not isinstance(k, str):
raise KeyError(f"key must be a string")
if not k in self.keys():
raise KeyError(f"'{k}' not valid key. Examine 'BasicInfo.keys()'")
raise KeyError(f"'{k}' not valid key. Examine 'FastInfo.keys()'")
return getattr(self, k)
def __contains__(self, k):
return k in self.keys()
Expand Down Expand Up @@ -178,9 +178,6 @@ def currency(self):
self._currency = md["currency"]
return self._currency

def _currency_is_cents(self):
return self.currency in ["GBp", "ILA"]

@property
def exchange(self):
if self._exchange is not None:
Expand All @@ -202,7 +199,13 @@ def shares(self):
if self._shares is not None:
return self._shares

shares = self._tkr.get_shares_full(start=pd.Timestamp.utcnow().date()-pd.Timedelta(days=548))
try:
shares = self._tkr.get_shares_full(start=pd.Timestamp.utcnow().date()-pd.Timedelta(days=548))
except Exception as e:
if "did not return share count" in str(e):
shares = None
else:
raise
if shares is None:
# Requesting 18 months failed, so fallback to shares which should include last year
shares = self._tkr.get_shares()
Expand Down Expand Up @@ -365,8 +368,6 @@ def market_cap(self):
return self._mcap

self._mcap = self.shares * self.last_price
if self._currency_is_cents():
self._mcap *= 0.01
return self._mcap


Expand Down Expand Up @@ -400,7 +401,7 @@ def __init__(self, ticker, session=None):
self._quote = Quote(self._data)
self._fundamentals = Fundamentals(self._data)

self._basic_info = BasicInfo(self)
self._fast_info = FastInfo(self)

def stats(self, proxy=None):
ticker_url = "{}/{}".format(self._scrape_url, self.ticker)
Expand Down Expand Up @@ -1146,7 +1147,7 @@ def _get_ticker_tz(self, debug_mode, proxy, timeout):
return tz

def _fetch_ticker_tz(self, debug_mode, proxy, timeout):
# Query Yahoo for basic price data just to get returned timezone
# Query Yahoo for fast price data just to get returned timezone

params = {"range": "1d", "interval": "1d"}

Expand Down Expand Up @@ -1220,9 +1221,14 @@ def get_info(self, proxy=None) -> dict:
data = self._quote.info
return data

@property
def fast_info(self):
return self._fast_info

@property
def basic_info(self):
return self._basic_info
print("WARNING: 'Ticker.basic_info' is renamed to 'Ticker.fast_info', hopefully purpose is clearer")
return self.fast_info

def get_sustainability(self, proxy=None, as_dict=False):
self._quote.proxy = proxy
Expand Down Expand Up @@ -1489,8 +1495,7 @@ def get_shares_full(self, start=None, end=None, proxy=None):

shares_data = json_data["timeseries"]["result"]
if not "shares_out" in shares_data[0]:
print(f"{self.ticker}: Yahoo did not return share count in date range {start} -> {end}")
return None
raise Exception(f"{self.ticker}: Yahoo did not return share count in date range {start} -> {end}")
try:
df = _pd.Series(shares_data[0]["shares_out"], index=_pd.to_datetime(shares_data[0]["timestamp"], unit="s"))
except Exception as e:
Expand Down
6 changes: 3 additions & 3 deletions yfinance/scrapers/quote.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,13 +46,13 @@ def __contains__(self, k):

def __getitem__(self, k):
if k in info_retired_keys_price:
print(f"Price data removed from info. Use Ticker.basic_info or history() instead")
print(f"Price data removed from info. Use Ticker.fast_info or history() instead")
return None
elif k in info_retired_keys_exchange:
print(f"Exchange data removed from info. Use Ticker.basic_info or Ticker.get_history_metadata() instead")
print(f"Exchange data removed from info. Use Ticker.fast_info or Ticker.get_history_metadata() instead")
return None
elif k in info_retired_keys_marketCap:
print(f"Market cap removed from info. Use Ticker.basic_info instead")
print(f"Market cap removed from info. Use Ticker.fast_info instead")
return None
elif k in info_retired_keys_symbol:
print(f"Symbol removed from info. You know this already")
Expand Down

0 comments on commit b43072c

Please sign in to comment.