Skip to content

Commit 6c70b86

Browse files
authored
Merge pull request #1423 from flaviovs/no-print
No print
2 parents bd696fb + d13aafa commit 6c70b86

File tree

8 files changed

+98
-86
lines changed

8 files changed

+98
-86
lines changed

test_yfinance.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,9 @@
1515

1616
import yfinance as yf
1717
import unittest
18+
import logging
19+
20+
logging.basicConfig(level=logging.DEBUG)
1821

1922
symbols = ['MSFT', 'IWO', 'VFINX', '^GSPC', 'BTC-USD']
2023
tickers = [yf.Ticker(symbol) for symbol in symbols]

yfinance/base.py

Lines changed: 61 additions & 67 deletions
Large diffs are not rendered by default.

yfinance/data.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import functools
22
from functools import lru_cache
33

4+
import logging
45
import hashlib
56
from base64 import b64decode
67
usePycryptodome = False # slightly faster
@@ -25,6 +26,8 @@
2526

2627
cache_maxsize = 64
2728

29+
logger = logging.getLogger(__name__)
30+
2831

2932
def lru_cache_freezeargs(func):
3033
"""
@@ -294,7 +297,7 @@ def get_json_data_stores(self, sub_page: str = None, proxy=None) -> dict:
294297
msg = "No decryption keys could be extracted from JS file."
295298
if "requests_cache" in str(type(response)):
296299
msg += " Try flushing your 'requests_cache', probably parsing old JS."
297-
print("WARNING: " + msg + " Falling back to backup decrypt methods.")
300+
logger.warning("%s Falling back to backup decrypt methods.", msg)
298301
if len(keys) == 0:
299302
keys = []
300303
try:

yfinance/multi.py

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -21,13 +21,15 @@
2121

2222
from __future__ import print_function
2323

24+
import logging
2425
import time as _time
2526
import multitasking as _multitasking
2627
import pandas as _pd
2728

2829
from . import Ticker, utils
2930
from . import shared
3031

32+
logger = logging.getLogger(__name__)
3133

3234
def download(tickers, start=None, end=None, actions=False, threads=True, ignore_tz=None,
3335
group_by='column', auto_adjust=False, back_adjust=False, repair=False, keepna=False,
@@ -144,12 +146,16 @@ def download(tickers, start=None, end=None, actions=False, threads=True, ignore_
144146
if progress:
145147
shared._PROGRESS_BAR.completed()
146148

147-
if shared._ERRORS and show_errors:
148-
print('\n%.f Failed download%s:' % (
149-
len(shared._ERRORS), 's' if len(shared._ERRORS) > 1 else ''))
150-
# print(shared._ERRORS)
151-
print("\n".join(['- %s: %s' %
152-
v for v in list(shared._ERRORS.items())]))
149+
if shared._ERRORS:
150+
if show_errors:
151+
print('\n%.f Failed download%s:' % (
152+
len(shared._ERRORS), 's' if len(shared._ERRORS) > 1 else ''))
153+
# print(shared._ERRORS)
154+
print("\n".join(['- %s: %s' %
155+
v for v in list(shared._ERRORS.items())]))
156+
else:
157+
logger.error('%d failed downloads: %s',
158+
len(shared._ERRORS), shared._ERRORS)
153159

154160
if ignore_tz:
155161
for tkr in shared._DFS.keys():

yfinance/scrapers/analysis.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ def _scrape(self, proxy):
5858
analysis_data = analysis_data['QuoteSummaryStore']
5959
except KeyError as e:
6060
err_msg = "No analysis data found, symbol may be delisted"
61-
print('- %s: %s' % (self._data.ticker, err_msg))
61+
logger.error('%s: %s', self._data.ticker, err_msg)
6262
return
6363

6464
if isinstance(analysis_data.get('earningsTrend'), dict):

yfinance/scrapers/fundamentals.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import datetime
2+
import logging
23
import json
34

45
import pandas as pd
@@ -8,6 +9,7 @@
89
from yfinance.data import TickerData
910
from yfinance.exceptions import YFinanceDataException, YFinanceException
1011

12+
logger = logging.getLogger(__name__)
1113

1214
class Fundamentals:
1315

@@ -50,7 +52,7 @@ def _scrape_basics(self, proxy):
5052
self._fin_data_quote = self._financials_data['QuoteSummaryStore']
5153
except KeyError:
5254
err_msg = "No financials data found, symbol may be delisted"
53-
print('- %s: %s' % (self._data.ticker, err_msg))
55+
logger.error('%s: %s', self._data.ticker, err_msg)
5456
return None
5557

5658
def _scrape_earnings(self, proxy):
@@ -144,7 +146,7 @@ def _fetch_time_series(self, name, timescale, proxy=None):
144146
if statement is not None:
145147
return statement
146148
except YFinanceException as e:
147-
print(f"- {self._data.ticker}: Failed to create {name} financials table for reason: {repr(e)}")
149+
logger.error("%s: Failed to create %s financials table for reason: %r", self._data.ticker, name, e)
148150
return pd.DataFrame()
149151

150152
def _create_financials_table(self, name, timescale, proxy):
@@ -267,7 +269,7 @@ def _scrape(self, name, timescale, proxy=None):
267269
if statement is not None:
268270
return statement
269271
except YFinanceException as e:
270-
print(f"- {self._data.ticker}: Failed to create financials table for {name} reason: {repr(e)}")
272+
logger.error("%s: Failed to create financials table for %s reason: %r", self._data.ticker, name, e)
271273
return pd.DataFrame()
272274

273275
def _create_financials_table_old(self, name, timescale, proxy):

yfinance/scrapers/quote.py

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,14 @@
11
import datetime
2+
import logging
23
import json
4+
import warnings
35

46
import pandas as pd
57

68
from yfinance import utils
79
from yfinance.data import TickerData
810

11+
logger = logging.getLogger(__name__)
912

1013
info_retired_keys_price = {"currentPrice", "dayHigh", "dayLow", "open", "previousClose", "volume", "volume24Hr"}
1114
info_retired_keys_price.update({"regularMarket"+s for s in ["DayHigh", "DayLow", "Open", "PreviousClose", "Price", "Volume"]})
@@ -44,16 +47,16 @@ def __contains__(self, k):
4447

4548
def __getitem__(self, k):
4649
if k in info_retired_keys_price:
47-
print(f"Price data removed from info (key='{k}'). Use Ticker.fast_info or history() instead")
50+
warnings.warn(f"Price data removed from info (key='{k}'). Use Ticker.fast_info or history() instead", DeprecationWarning)
4851
return None
4952
elif k in info_retired_keys_exchange:
50-
print(f"Exchange data removed from info (key='{k}'). Use Ticker.fast_info or Ticker.get_history_metadata() instead")
53+
warnings.warn(f"Exchange data removed from info (key='{k}'). Use Ticker.fast_info or Ticker.get_history_metadata() instead", DeprecationWarning)
5154
return None
5255
elif k in info_retired_keys_marketCap:
53-
print(f"Market cap removed from info (key='{k}'). Use Ticker.fast_info instead")
56+
warnings.warn(f"Market cap removed from info (key='{k}'). Use Ticker.fast_info instead", DeprecationWarning)
5457
return None
5558
elif k in info_retired_keys_symbol:
56-
print(f"Symbol removed from info (key='{k}'). You know this already")
59+
warnings.warn(f"Symbol removed from info (key='{k}'). You know this already", DeprecationWarning)
5760
return None
5861
return self.info[self._keytransform(k)]
5962

@@ -126,7 +129,7 @@ def _scrape(self, proxy):
126129
quote_summary_store = json_data['QuoteSummaryStore']
127130
except KeyError:
128131
err_msg = "No summary info found, symbol may be delisted"
129-
print('- %s: %s' % (self._data.ticker, err_msg))
132+
logger.error('%s: %s', self._data.ticker, err_msg)
130133
return None
131134

132135
# sustainability

yfinance/utils.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -936,9 +936,10 @@ def get_tz_cache():
936936
try:
937937
_tz_cache = _TzCache()
938938
except _TzCacheException as err:
939-
print("Failed to create TzCache, reason: {}".format(err))
940-
print("TzCache will not be used.")
941-
print("Tip: You can direct cache to use a different location with 'set_tz_cache_location(mylocation)'")
939+
logger.error("Failed to create TzCache, reason: %s. "
940+
"TzCache will not be used. "
941+
"Tip: You can direct cache to use a different location with 'set_tz_cache_location(mylocation)'",
942+
err)
942943
_tz_cache = _TzCacheDummy()
943944

944945
return _tz_cache

0 commit comments

Comments
 (0)