Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 9 additions & 9 deletions yfinance_cache/yfc_cache_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ def ReadCacheDatum(ticker, objectName, return_metadata_too=False):
expiry = d["expiry"] if "expiry" in d else None

if expiry is not None:
dtnow = pd.Timestamp.utcnow().replace(tzinfo=ZoneInfo("UTC"))
dtnow = pd.Timestamp.now('UTC').replace(tzinfo=ZoneInfo("UTC"))
if dtnow >= expiry:
if verbose:
print("Deleting expired datum '{0}/{1}'".format(ticker, objectName))
Expand Down Expand Up @@ -238,7 +238,7 @@ def ReadCachePackedDatum(ticker, objectName, return_metadata_too=False):
expiry = objData["expiry"] if "expiry" in objData else None

if expiry is not None:
dtnow = pd.Timestamp.utcnow().replace(tzinfo=ZoneInfo("UTC"))
dtnow = pd.Timestamp.now('UTC').replace(tzinfo=ZoneInfo("UTC"))
if dtnow >= expiry:
if verbose:
print("Deleting expired packed datum '{0}/{1}'".format(ticker, objectName))
Expand Down Expand Up @@ -275,7 +275,7 @@ def StoreCacheDatum(ticker, objectName, datum, expiry=None, metadata=None):
if expiry is not None:
if isinstance(expiry, yfcd.Interval):
# Convert interval to actual datetime
expiry = pd.Timestamp.utcnow().replace(tzinfo=ZoneInfo("UTC")) + yfcd.intervalToTimedelta[expiry]
expiry = pd.Timestamp.now('UTC').replace(tzinfo=ZoneInfo("UTC")) + yfcd.intervalToTimedelta[expiry]
if not isinstance(expiry, datetime):
raise Exception("'expiry' must be datetime or yfcd.Interval")

Expand Down Expand Up @@ -339,7 +339,7 @@ def StoreCachePackedDatum(ticker, objectName, datum, expiry=None, metadata=None)
if expiry is not None:
if isinstance(expiry, yfcd.Interval):
# Convert interval to actual datetime
expiry = pd.Timestamp.utcnow().replace(tzinfo=ZoneInfo("UTC")) + yfcd.intervalToTimedelta[expiry]
expiry = pd.Timestamp.now('UTC').replace(tzinfo=ZoneInfo("UTC")) + yfcd.intervalToTimedelta[expiry]
if not isinstance(expiry, datetime):
raise Exception("'expiry' must be datetime or yfcd.Interval")
if (metadata is not None) and "Expiry" in metadata.keys():
Expand Down Expand Up @@ -508,11 +508,11 @@ def _load_option(self):
self.options = {}
# Initialise
a = self.__getattr__('max_ages')
a.calendar = '7d'
a.info = '45d'
a.options = '1d'
a.holdings = '91d'
a.analysis = '91d'
a.calendar = '7D'
a.info = '45D'
a.options = '1D'
a.holdings = '91D'
a.analysis = '91D'
c = self.__getattr__('calendar')
c.accept_unexpected_Yahoo_intervals = True

Expand Down
24 changes: 12 additions & 12 deletions yfinance_cache/yfc_financials_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -469,7 +469,7 @@ def _get_fin_table(self, finType, period, refresh=True):
if df is None:
do_fetch = True
elif refresh:
dt_now = pd.Timestamp.utcnow().tz_convert(self.tzName)
dt_now = pd.Timestamp.now('UTC').tz_convert(self.tzName)
if df.empty:
# Nothing to estimate releases on, so just periodically check
try:
Expand Down Expand Up @@ -574,7 +574,7 @@ def _get_fin_table(self, finType, period, refresh=True):
print(msg)
df_new = getattr(self.dat, name)
df_new = df_new.astype('float')
fetch_dt = pd.Timestamp.utcnow().tz_convert(self.tzName)
fetch_dt = pd.Timestamp.now('UTC').tz_convert(self.tzName)
if md is None:
md = {'FetchDates':{}}
for dt in df_new.columns:
Expand Down Expand Up @@ -798,7 +798,7 @@ def get_release_dates(self, period, preferred_fin=yfcd.Financials.IncomeStmt, as

max_age = pd.Timedelta(yfcm._option_manager.max_ages.calendar)
dt_now = pd.Timestamp.now()
d_exchange = pd.Timestamp.utcnow().tz_convert(self.tzName).date()
d_exchange = pd.Timestamp.now('UTC').tz_convert(self.tzName).date()
if releases is None:
if md is None:
do_calc = True
Expand Down Expand Up @@ -2079,7 +2079,7 @@ def get_earnings_dates(self, start, refresh=True, clean=True):
if debug:
print(f"get_earnings_dates(start={start}, refresh={refresh})")

dt_now = pd.Timestamp.utcnow().tz_convert(self.tzName)
dt_now = pd.Timestamp.now('UTC').tz_convert(self.tzName)

last_fetch = None
if self._earnings_dates is None:
Expand Down Expand Up @@ -2163,7 +2163,7 @@ def get_earnings_dates(self, start, refresh=True, clean=True):
if debug:
print("- yf_start_date =", yf_start_date)
if last_fetch is not None:
if (last_fetch + pd.Timedelta('14d')) > dt_now:
if (last_fetch + pd.Timedelta('14D')) > dt_now:
# Avoid spamming Yahoo for data it doesn't have (empty earnings_dates).
if self._earnings_dates is None:
# Already attempted a fetch recently, Yahoo has nothing.
Expand Down Expand Up @@ -2191,17 +2191,17 @@ def get_earnings_dates(self, start, refresh=True, clean=True):
if isinstance(ei, (yfcd.ComparableRelativedelta, relativedelta)):
# Convert to normal Timedelta, don't need 100% precision
if ei.months == 3:
ei = pd.Timedelta('91d')
ei = pd.Timedelta('91D')
elif ei.months == 6:
ei = pd.Timedelta('182d')
ei = pd.Timedelta('182D')
elif ei.months == 12 or ei.years==1:
# ei = pd.Timedelta('365d')
# ei = pd.Timedelta('365D')
# Don't believe it
ei = pd.Timedelta('182d')
ei = pd.Timedelta('182D')
else:
raise Exception(ei, type(ei))

lookahead_dt = dt_now + pd.Timedelta('365d')
lookahead_dt = dt_now + pd.Timedelta('365D')
if debug:
print("- ei =", ei)
print("- lookahead_dt =", lookahead_dt)
Expand All @@ -2215,7 +2215,7 @@ def get_earnings_dates(self, start, refresh=True, clean=True):
df = self._earnings_dates.copy()
f_na = df['Reported EPS'].isna().to_numpy()
f_nna = ~f_na
f_expired = f_na & (df.index < dt_now) & ((dt_now - df['FetchDate']) > pd.Timedelta('7d')).to_numpy()
f_expired = f_na & (df.index < dt_now) & ((dt_now - df['FetchDate']) > pd.Timedelta('7D')).to_numpy()
n = df.shape[0]
if debug:
print("- n =", n)
Expand Down Expand Up @@ -2417,7 +2417,7 @@ def _fetch_earnings_dates(self, limit, refresh=True):
if debug:
print("- Yahoo returned None")
return None
df['FetchDate'] = pd.Timestamp.utcnow().tz_convert(self.tzName)
df['FetchDate'] = pd.Timestamp.now('UTC').tz_convert(self.tzName)

if df.shape[0] < limit:
if debug:
Expand Down
16 changes: 8 additions & 8 deletions yfinance_cache/yfc_prices_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -527,7 +527,7 @@ def get(self, start=None, end=None, period=None,
yfct.SetExchangeTzName(self.exchange, self.tzName)
td_1d = timedelta(days=1)
tz_exchange = ZoneInfo(self.tzName)
dt_now = pd.Timestamp.utcnow().tz_convert(tz_exchange)
dt_now = pd.Timestamp.now('UTC').tz_convert(tz_exchange)
d_now_exchange = dt_now.date()
tomorrow_d = d_now_exchange + td_1d
if self.interday:
Expand Down Expand Up @@ -1337,7 +1337,7 @@ def _fetchAndAddRanges_sparse(self, ranges_to_fetch, prepost, debug, quiet=False

tz_exchange = self.tz
td_1d = timedelta(days=1)
dtnow = pd.Timestamp.utcnow().tz_convert(tz_exchange)
dtnow = pd.Timestamp.now('UTC').tz_convert(tz_exchange)

# Backport events that occurred since last adjustment:
self._applyNewEvents()
Expand Down Expand Up @@ -1464,7 +1464,7 @@ def _verifyCachedPrices(self, rtol=0.0001, vol_rtol=0.004, correct=False, discar
h["Volume"] = (h["Volume"].to_numpy() / h["CSF"].to_numpy()).round().astype('int')

td_1d = pd.Timedelta("1D")
dt_now = pd.Timestamp.utcnow().tz_convert(ZoneInfo("UTC"))
dt_now = pd.Timestamp.now('UTC').tz_convert(ZoneInfo("UTC"))

def _aggregate_yfdf_daily(df):
df2 = df.copy()
Expand Down Expand Up @@ -1884,7 +1884,7 @@ def _fetchYfHistory(self, start, end, prepost, debug, verify_intervals=True, dis

tz_exchange = self.tz
td_1d = timedelta(days=1)
dt_now = pd.Timestamp.utcnow().tz_convert(ZoneInfo("UTC"))
dt_now = pd.Timestamp.now('UTC').tz_convert(ZoneInfo("UTC"))

if self.intraday:
maxLookback = yfcd.yfMaxFetchLookback[self.interval] - timedelta(seconds=10)
Expand Down Expand Up @@ -2064,7 +2064,7 @@ def _fetchYfHistory(self, start, end, prepost, debug, verify_intervals=True, dis
if df.index.duplicated().any():
raise Exception("df contains duplicated dates")

fetch_dt_utc = pd.Timestamp.utcnow().tz_convert(ZoneInfo("UTC"))
fetch_dt_utc = pd.Timestamp.now('UTC').tz_convert(ZoneInfo("UTC"))

if (df is not None) and (df.index.tz is not None) and (not isinstance(df.index.tz, ZoneInfo)):
# Convert to ZoneInfo
Expand Down Expand Up @@ -2767,7 +2767,7 @@ def _reconstruct_intervals_batch(self, df, tag=-1):
if min_lookback is None:
min_dt = None
else:
min_dt = pd.Timestamp.utcnow().tz_convert(ZoneInfo("UTC")) - min_lookback
min_dt = pd.Timestamp.now('UTC').tz_convert(ZoneInfo("UTC")) - min_lookback
if debug:
print(f"- min_dt={min_dt} interval={self.interval} sub_interval={sub_interval}")
if min_dt is not None:
Expand Down Expand Up @@ -4056,7 +4056,7 @@ def _reverseYahooAdjust(self, df):
df["CSF"] = csf
df["CDF"] = cdf

h_lastDivAdjustDt = pd.Timestamp.utcnow().tz_convert(ZoneInfo("UTC"))
h_lastDivAdjustDt = pd.Timestamp.now('UTC').tz_convert(ZoneInfo("UTC"))
h_lastSplitAdjustDt = h_lastDivAdjustDt
df["LastDivAdjustDt"] = h_lastDivAdjustDt
df["LastSplitAdjustDt"] = h_lastSplitAdjustDt
Expand Down Expand Up @@ -4206,7 +4206,7 @@ def _applyNewEvents(self):
# This can happen with recent multiday intervals and that's ok, and will correct manually.
f1_oldest_idx = np.where(f1)[0][-1]
f1_oldest_dt = self.h.index[f1_oldest_idx]
is_f1_oldest_dt_recent = (pd.Timestamp.utcnow() - f1_oldest_dt) < (1.5*self.itd)
is_f1_oldest_dt_recent = (pd.Timestamp.now('UTC') - f1_oldest_dt) < (1.5*self.itd)
if self.interday and self.interval != yfcd.Interval.Days1 and is_f1_oldest_dt_recent:
# Yup, that's what happened
f[f1_oldest_idx:] = False
Expand Down
18 changes: 9 additions & 9 deletions yfinance_cache/yfc_ticker.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ def history(self,
raise Exception(f"Need to add mapping of exchange {exchange} to xcal (ticker={self._ticker})")
else:
raise
dt_now = pd.Timestamp.utcnow()
dt_now = pd.Timestamp.now('UTC')

# Type checks
if max_age is not None:
Expand Down Expand Up @@ -361,7 +361,7 @@ def _getExchangeAndTzAndListingDay(self):
exchange, tz_name, lday = None, None, None
i = None
try:
i = self.get_info('9999d')
i = self.get_info('9999D')
exchange = i['exchange']
if "exchangeTimezoneName" in i:
tz_name = i["exchangeTimezoneName"]
Expand Down Expand Up @@ -519,7 +519,7 @@ def _process_user_dt(self, dt):

def get_attribute(self, name, max_age=None, merge=False, metadata=False):
if max_age is None:
max_age = pd.Timedelta('365d')
max_age = pd.Timedelta('365D')
if not isinstance(max_age, (datetime.timedelta, pd.Timedelta)):
max_age = pd.Timedelta(max_age)
if max_age < pd.Timedelta(0):
Expand Down Expand Up @@ -665,15 +665,15 @@ def fast_info(self):

return self._fast_info

def get_shares(self, start=None, end=None, max_age='30d'):
def get_shares(self, start=None, end=None, max_age='30D'):
debug = False
# debug = True

max_age = pd.Timedelta(max_age)

# Process dates
exchange, tz, lday = self._getExchangeAndTzAndListingDay()
dt_now = pd.Timestamp.utcnow().tz_convert(tz)
dt_now = pd.Timestamp.now('UTC').tz_convert(tz)
if start is not None:
start_dt, start_d = self._process_user_dt(start)
start = start_d
Expand Down Expand Up @@ -704,7 +704,7 @@ def get_shares(self, start=None, end=None, max_age='30d'):
self._shares = self._fetch_shares(start, end)
if self._shares is None:
self._shares = pd.DataFrame()
yfcm.StoreCacheDatum(self._ticker, "shares", self._shares, metadata={'LastFetch':pd.Timestamp.utcnow().tz_convert(tz)})
yfcm.StoreCacheDatum(self._ticker, "shares", self._shares, metadata={'LastFetch':pd.Timestamp.now('UTC').tz_convert(tz)})
if self._shares.empty:
return None
else:
Expand All @@ -728,14 +728,14 @@ def get_shares(self, start=None, end=None, max_age='30d'):

if start < self._shares.index[0].date() and (not yfcm._option_manager.session.offline):
df_pre = self._fetch_shares(start, self._shares.index[0])
yfcm.WriteCacheMetadata(self._ticker, "shares", 'LastFetch', pd.Timestamp.utcnow().tz_convert(tz))
yfcm.WriteCacheMetadata(self._ticker, "shares", 'LastFetch', pd.Timestamp.now('UTC').tz_convert(tz))
if df_pre is not None:
self._shares = pd.concat([df_pre, self._shares])
if (end-td_1d) > self._shares.index[-1].date() and \
(end - self._shares.index[-1].date()) > max_age \
and (not yfcm._option_manager.session.offline):
df_post = self._fetch_shares(self._shares.index[-1] + td_1d, end)
yfcm.WriteCacheMetadata(self._ticker, "shares", 'LastFetch', pd.Timestamp.utcnow().tz_convert(tz))
yfcm.WriteCacheMetadata(self._ticker, "shares", 'LastFetch', pd.Timestamp.now('UTC').tz_convert(tz))
if df_post is not None:
self._shares = pd.concat([self._shares, df_post])

Expand Down Expand Up @@ -794,7 +794,7 @@ def _fetch_shares(self, start, end):
if df.empty:
return None

fetch_dt = pd.Timestamp.utcnow().tz_convert(tz)
fetch_dt = pd.Timestamp.now('UTC').tz_convert(tz)
df = pd.DataFrame(df, columns=['Shares'])

if start_d < df.index[0].date():
Expand Down
16 changes: 8 additions & 8 deletions yfinance_cache/yfc_time.py
Original file line number Diff line number Diff line change
Expand Up @@ -238,8 +238,8 @@ def _customModSchedule(cal):
start = date(pre_range[0], 1, 1)
end = date(pre_range[1], 12, 31)
if exchange == 'CCC':
opens = pd.date_range(start=start, end=end, freq='1d').tz_localize(ZoneInfo(GetExchangeTzName(exchange)))
ends = opens + pd.Timedelta('1d')
opens = pd.date_range(start=start, end=end, freq='1D').tz_localize(ZoneInfo(GetExchangeTzName(exchange)))
ends = opens + pd.Timedelta('1D')
pre_cal = Simple247xcal(opens, ends)
else:
pre_cal = xcal.get_calendar(cal_name, start=start, end=end)
Expand All @@ -252,8 +252,8 @@ def _customModSchedule(cal):
start = date(post_range[0], 1, 1)
end = date(post_range[1], 12, 31)
if exchange == 'CCC':
opens = pd.date_range(start=start, end=end, freq='1d').tz_localize(ZoneInfo(GetExchangeTzName(exchange)))
ends = opens + pd.Timedelta('1d')
opens = pd.date_range(start=start, end=end, freq='1D').tz_localize(ZoneInfo(GetExchangeTzName(exchange)))
ends = opens + pd.Timedelta('1D')
post_cal = Simple247xcal(opens, ends)
else:
post_cal = xcal.get_calendar(cal_name, start=start, end=end)
Expand Down Expand Up @@ -417,7 +417,7 @@ def GetExchangeWeekSchedule(exchange, start, end, ignoreHolidays, ignoreWeekends
end_d = end
else:
end_d = end.astimezone(tz).date() + td_1d
dt_now = pd.Timestamp.utcnow().tz_convert(ZoneInfo("UTC"))
dt_now = pd.Timestamp.now('UTC').tz_convert(ZoneInfo("UTC"))
# td7d = timedelta(days=7)
td7d = pd.DateOffset(days=7)

Expand Down Expand Up @@ -534,7 +534,7 @@ def MapPeriodToDates(exchange, period, interval):

# Map period to start->end range so logic can intelligently fetch missing data
td_1d = timedelta(days=1)
dt_now = pd.Timestamp.utcnow().replace(tzinfo=ZoneInfo("UTC"))
dt_now = pd.Timestamp.now('UTC').replace(tzinfo=ZoneInfo("UTC"))
d_now = dt_now.astimezone(tz_exchange).date()
sched = GetExchangeSchedule(exchange, d_now-(7*td_1d), d_now+td_1d)
yf_lag = yfcd.exchangeToYfLag[exchange]
Expand Down Expand Up @@ -612,7 +612,7 @@ def GetExchangeScheduleIntervals(exchange, interval, start, end, discardTimes=No
yfc_logger.debug("GetExchangeScheduleIntervals()")
yfc_logger.debug("- " + str(locals()))

dt_now = pd.Timestamp.utcnow()
dt_now = pd.Timestamp.now('UTC')
tz = ZoneInfo(GetExchangeTzName(exchange))
td_1d = timedelta(days=1)
if not isinstance(start, datetime):
Expand Down Expand Up @@ -1795,7 +1795,7 @@ def IsPriceDatapointExpired(intervalStart, fetch_dt, repaired, max_age, exchange
if dt_now is not None:
yfcu.TypeCheckDatetime(dt_now, "dt_now")
else:
dt_now = pd.Timestamp.utcnow().tz_convert(ZoneInfo(GetExchangeTzName(exchange)))
dt_now = pd.Timestamp.now('UTC').tz_convert(ZoneInfo(GetExchangeTzName(exchange)))

if yf_lag is not None:
yfcu.TypeCheckTimedelta(yf_lag, "yf_lag")
Expand Down