Skip to content

Commit

Permalink
Merge pull request #1790 from bot-unit/feature/calendar
Browse files Browse the repository at this point in the history
feature calendar events
  • Loading branch information
ValueRaider authored Dec 16, 2023
2 parents a679060 + 24f53e9 commit 281cc64
Show file tree
Hide file tree
Showing 4 changed files with 48 additions and 16 deletions.
24 changes: 17 additions & 7 deletions tests/ticker.py
Original file line number Diff line number Diff line change
Expand Up @@ -711,13 +711,23 @@ def test_recommendations_history(self): # alias for upgrades_downgrades
# data_cached = self.ticker.revenue_forecasts
# self.assertIs(data, data_cached, "data not cached")

# def test_calendar(self):
# data = self.ticker.calendar
# self.assertIsInstance(data, pd.DataFrame, "data has wrong type")
# self.assertFalse(data.empty, "data is empty")

# data_cached = self.ticker.calendar
# self.assertIs(data, data_cached, "data not cached")
def test_calendar(self):
data = self.ticker.calendar
self.assertIsInstance(data, dict, "data has wrong type")
self.assertTrue(len(data) > 0, "data is empty")
self.assertIn("Earnings Date", data.keys(), "data missing expected key")
self.assertIn("Earnings Average", data.keys(), "data missing expected key")
self.assertIn("Earnings Low", data.keys(), "data missing expected key")
self.assertIn("Earnings High", data.keys(), "data missing expected key")
self.assertIn("Revenue Average", data.keys(), "data missing expected key")
self.assertIn("Revenue Low", data.keys(), "data missing expected key")
self.assertIn("Revenue High", data.keys(), "data missing expected key")
# dividend date is not available for tested ticker GOOGL
if self.ticker.ticker != "GOOGL":
self.assertIn("Dividend Date", data.keys(), "data missing expected key")
# ex-dividend date is not always available
data_cached = self.ticker.calendar
self.assertIs(data, data_cached, "data not cached")

# def test_shares(self):
# data = self.ticker.shares
Expand Down
7 changes: 2 additions & 5 deletions yfinance/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -1733,12 +1733,9 @@ def get_upgrades_downgrades(self, proxy=None, as_dict=False):
return data.to_dict()
return data

def get_calendar(self, proxy=None, as_dict=False):
def get_calendar(self, proxy=None) -> dict:
self._quote.proxy = proxy or self.proxy
data = self._quote.calendar
if as_dict:
return data.to_dict()
return data
return self._quote.calendar

def get_major_holders(self, proxy=None, as_dict=False):
self._holders.proxy = proxy or self.proxy
Expand Down
28 changes: 25 additions & 3 deletions yfinance/scrapers/quote.py
Original file line number Diff line number Diff line change
Expand Up @@ -610,9 +610,9 @@ def upgrades_downgrades(self) -> pd.DataFrame:
return self._upgrades_downgrades

@property
def calendar(self) -> pd.DataFrame:
def calendar(self) -> dict:
if self._calendar is None:
raise YFNotImplementedError('calendar')
self._fetch_calendar()
return self._calendar

@staticmethod
Expand All @@ -626,7 +626,7 @@ def _fetch(self, proxy, modules: list):
modules = ','.join([m for m in modules if m in quote_summary_valid_modules])
if len(modules) == 0:
raise YFinanceException("No valid modules provided, see available modules using `valid_modules`")
params_dict = {"modules": modules, "corsDomain": "finance.yahoo.com", "symbol": self._symbol}
params_dict = {"modules": modules, "corsDomain": "finance.yahoo.com", "formatted": "false", "symbol": self._symbol}
result = self._data.get_raw_json(_QUOTE_SUMMARY_URL_ + f"/{self._symbol}", user_agent_headers=self._data.user_agent_headers, params=params_dict, proxy=proxy)
return result

Expand Down Expand Up @@ -727,3 +727,25 @@ def _fetch_complementary(self, proxy):
else:
self.info[k] = None

def _fetch_calendar(self):
# secFilings return too old data, so not requesting it for now
result = self._fetch(self.proxy, modules=['calendarEvents'])
try:
self._calendar = dict()
_events = result["quoteSummary"]["result"][0]["calendarEvents"]
if 'dividendDate' in _events:
self._calendar['Dividend Date'] = datetime.datetime.fromtimestamp(_events['dividendDate']).date()
if 'exDividendDate' in _events:
self._calendar['Ex-Dividend Date'] = datetime.datetime.fromtimestamp(_events['exDividendDate']).date()
# splits = _events.get('splitDate') # need to check later, i will add code for this if found data
earnings = _events.get('earnings')
if earnings is not None:
self._calendar['Earnings Date'] = [datetime.datetime.fromtimestamp(d).date() for d in earnings.get('earningsDate', [])]
self._calendar['Earnings High'] = earnings.get('earningsHigh', None)
self._calendar['Earnings Low'] = earnings.get('earningsLow', None)
self._calendar['Earnings Average'] = earnings.get('earningsAverage', None)
self._calendar['Revenue High'] = earnings.get('revenueHigh', None)
self._calendar['Revenue Low'] = earnings.get('revenueLow', None)
self._calendar['Revenue Average'] = earnings.get('revenueAverage', None)
except (KeyError, IndexError):
raise YFinanceDataException(f"Failed to parse json response from Yahoo Finance: {result}")
5 changes: 4 additions & 1 deletion yfinance/ticker.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,10 @@ def fast_info(self):
return self.get_fast_info()

@property
def calendar(self) -> _pd.DataFrame:
def calendar(self) -> dict:
"""
Returns a dictionary of events, earnings, and dividends for the ticker
"""
return self.get_calendar()

@property
Expand Down

0 comments on commit 281cc64

Please sign in to comment.