Add Ticker.market_cap helper ; Tidy info[] blacklist

pull/1317/head
ValueRaider 2023-01-16 11:23:35 +00:00
parent 97671b78dd
commit 677bbfed8b
4 changed files with 40 additions and 14 deletions

View File

@ -86,6 +86,9 @@ msft.capital_gains
msft.shares
msft.get_shares_full()
# calculate market cap
msft.market_cap
# show financials:
# - income statement
msft.income_stmt

View File

@ -1172,6 +1172,24 @@ class TickerBase:
df = df.sort_index()
return df
def calc_market_cap(self, proxy=None):
shares = self.get_shares_full(start=pd.Timestamp.utcnow().date()-pd.Timedelta(days=548), proxy=proxy)
if shares is None:
# Requesting 18 months failed, so fallback to shares which should include last year
shares = self.get_shares(proxy=proxy)
if shares is None:
raise Exception(f"{self.ticker}: Cannot retrieve share count for calculating market cap")
if isinstance(shares, pd.DataFrame):
shares = shares[shares.columns[0]]
shares = shares.iloc[-1]
# price = self.history(period="1wk")["Close"].iloc[-1]
# Use metadata, in case history() returns empty because stock hasn't traded for long time
df = self.history(period="1d")
md = self.get_history_metadata()
price = md["regularMarketPrice"]
mcap = price * shares
return mcap
def get_isin(self, proxy=None) -> Optional[str]:
# *** experimental ***
if self._isin is not None:

View File

@ -7,33 +7,38 @@ from yfinance import utils
from yfinance.data import TickerData
info_retired_keys_price = {"currentPrice", "dayHigh", "dayLow", "open", "previousClose"}
info_retired_keys_price.update({"regularMarket"+s for s in ["DayHigh", "DayLow", "Open", "PreviousClose", "Price"]})
info_retired_keys_exchange = {"currency", "exchange", "exchangeTimezoneName", "exchangeTimezoneShortName"}
info_retired_keys_marketCap = {"marketCap"}
info_retired_keys_symbol = {"symbol"}
info_retired_keys = info_retired_keys_price | info_retired_keys_exchange | info_retired_keys_marketCap | info_retired_keys_symbol
from collections.abc import MutableMapping
class InfoDictWrapper(MutableMapping):
""" Simple wrapper around info dict, to print messages for specific keys
instructing how to retrieve with new methods"""
def __init__(self, info):
self.info = info
self.redundant_keys_price = ["currentPrice", "dayHigh", "dayLow", "open", "previousClose"]
self.redundant_keys_price += ["regularMarket"+s for s in ["DayHigh", "DayLow", "Open", "PreviousClose", "Price"]]
self.redundant_keys_exchange = ["currency", "exchange", "exchangeTimezoneName", "exchangeTimezoneShortName"]
self.redundant_keys_marketCap = ["marketCap"]
def __contains__(self, k):
return k in self.info.keys()
def __getitem__(self, k):
if k in self.redundant_keys_price:
if k in info_retired_keys_price:
print(f"Price data removed from info. Use Ticker.history(period='1wk') instead")
return None
elif k in self.redundant_keys_exchange:
elif k in info_retired_keys_exchange:
print(f"Exchange data removed from info. Use Ticker.get_history_metadata() instead")
return None
elif k in self.redundant_keys_marketCap:
elif k in info_retired_keys_marketCap:
print(f"Market cap removed from info. Calculate using new Ticker.get_shares_full() * price")
return None
elif k in info_retired_keys_symbol:
print(f"Symbol removed from info. You know this already")
return None
return self.info[self._keytransform(k)]
def __setitem__(self, k, value):
@ -178,11 +183,7 @@ class Quote:
# Delete redundant info[] keys, because values can be accessed faster
# elsewhere - e.g. price keys. Hope is reduces Yahoo spam effect.
redundant_keys = ["currentPrice", "dayHigh", "dayLow", "open", "previousClose"]
redundant_keys += ["regularMarket"+s for s in ["DayHigh", "DayLow", "Open", "PreviousClose", "Price"]]
redundant_keys += ["currency", "exchange", "exchangeTimezoneName", "exchangeTimezoneShortName"]
redundant_keys += ["marketCap"]
for k in redundant_keys:
for k in info_retired_keys:
if k in self._info:
del self._info[k]
# InfoDictWrapper will explain how to access above data elsewhere

View File

@ -133,6 +133,10 @@ class Ticker(TickerBase):
def shares(self) -> _pd.DataFrame :
return self.get_shares()
@property
def market_cap(self) -> float:
return self.calc_market_cap()
@property
def info(self) -> dict:
return self.get_info()