2020-05-05 复习yfinance

自从Yahoo! finance(雅虎财经)部门停止更新了他们的历史数据API,许多依赖它的程序停止工作。yfinance旨在通过提供一种可靠的、线程化的、Python化的方式从下载历史股票交易市场数据来解决这个问题。

这个库最初被命名为fix-yahoo-finance,但后来作者将其重命名为yfinance,因为作者不再认为它只是一个“修复fix”工具。出于竞争力落后的原因,fix-yahoo-finance现在导入并使用yfinance,但您应该直接安装并使用yfinance

Ticker模块

Ticker 模块可以让使用者用一种更Pythonic的方式获取股市交易数据:

#导入`yfinance`库
import yfinance as yf
#定义msft导入微软的股票信息
msft = yf.Ticker("MSFT")

# 获取股票信息
msft.info

# 获取历史交易信息
hist = msft.history(period="max")

# 显示操作(分红、拆分)(dividends, splits)
msft.actions

# show dividends
msft.dividends

# show splits
msft.splits

# show financials
msft.financials
msft.quarterly_financials

# show major holders展示主要持有人
stock.major_holders

# show institutional holders展示机构持有人
stock.institutional_holders

# show balance heet显示资产负债表
msft.balance_sheet
msft.quarterly_balance_sheet

# show cashflow 现金流量表
msft.cashflow
msft.quarterly_cashflow
 
# show earnings收益
msft.earnings
msft.quarterly_earnings

# show sustainability 可持续性
msft.sustainability

# show analysts recommendations 向分析师展示建议
msft.recommendations

# show next event (earnings, etc)
msft.calendar

# show ISIN code - *experimental*
# ISIN = International Securities Identification Number
msft.isin

# show options expirations 显示期权到期
msft.options

# get option chain for specific expiration 获取特定到期的期权链
opt = msft.option_chain('YYYY-MM-DD')
# data available via: opt.calls, opt.puts数据可通过以下方式获得:opt.calls,opt.puts

如果要使用代理服务器下载数据,请使用:

import yfinance as yf

msft = yf.Ticker("MSFT")

msft.history(..., proxy="PROXY_SERVER")
msft.get_actions(proxy="PROXY_SERVER")
msft.get_dividends(proxy="PROXY_SERVER")
msft.get_splits(proxy="PROXY_SERVER")
msft.get_balance_sheet(proxy="PROXY_SERVER")
msft.get_cashflow(proxy="PROXY_SERVER")
msgt.option_chain(..., proxy="PROXY_SERVER")
...

要初始化多个股票代码对象,请使用:

import yfinance as yf

tickers = yf.Tickers('msft aapl goog')
# ^ returns a named tuple of Ticker objects

# access each ticker using (example)
tickers.msft.info
tickers.aapl.history(period="1mo")
tickers.goog.actions

获取多个股票的数据:

import yfinance as yf
data = yf.download("SPY AAPL", start="2017-01-01", end="2017-04-30")

作者还添加了一些便捷参数来使工作更轻松 :)

data = yf.download(  # or pdr.get_data_yahoo(...
        # tickers list or string as well
        tickers = "SPY AAPL MSFT",

        # use "period" instead of start/end
        # valid periods: 1d,5d,1mo,3mo,6mo,1y,2y,5y,10y,ytd,max
        # (optional, default is '1mo')
        period = "ytd",

        # fetch data by interval (including intraday if period < 60 days)
        # valid intervals: 1m,2m,5m,15m,30m,60m,90m,1h,1d,5d,1wk,1mo,3mo
        # (optional, default is '1d')
        interval = "1m",

        # group by ticker (to access via data['SPY'])
        # (optional, default is 'column')
        group_by = 'ticker',

        # adjust all OHLC automatically
        # (optional, default is False)
        auto_adjust = True,

        # download pre/post regular market hours data
        # (optional, default is False)
        prepost = True,

        # use threads for mass downloading? (True/False/Integer)
        # (optional, default is True)
        threads = True,

        # proxy URL scheme use use when downloading?
        # (optional, default is None)
        proxy = None
    )

pandas_datareader覆盖

如果您的代码使用pandas_datareader,并且您想更快地下载数据,则可以“劫持” pandas_datareader.data.get_data_yahoo()方法以使用yfinance,同时确保返回的数据与pandas_datareaderget_data_yahoo()格式相同。

from pandas_datareader import data as pdr

import yfinance as yf
yf.pdr_override() # <== that's all it takes :-)

# download dataframe
data = pdr.get_data_yahoo("SPY", start="2017-01-01", end="2017-04-30")

安装

Install yfinance using pip:

$ pip install yfinance --upgrade --no-cache-dir

Install yfinance using conda:

$ conda install -c ranaroussi yfinance

依赖环境

可先依赖项 (if you want to use pandas_datareader)

法律资料

yfinance is distributed under the Apache Software License. See the LICENSE.txt file in the release for details.

今天练习通过ipython实现,记录如下:

先激活python的小环境:

  501  cd /Users/chelsea/pandas-tutorial-master
  502  conda deactivate
  503  history
  504  source venv/bin/activate
  505  ls
  506  cd pythonsp500-plotly-dash-master/
  507  ls
  508  pip install -r requirements.txt
  509  ipython

打开ipython笔记本:记录里面有些报错解决了,有些没能解决,因为这个笔记本和jupternotebook不同,不能保存为一个文件,所以就通过笔记记录,后面再遇到了问题可以回溯。

(venv) Cheng-MacBook-Pro:pythonsp500-plotly-dash-master chelsea$ ipython
/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/IPython/core/interactiveshell.py:935: UserWarning: Attempting to work in a virtualenv. If you encounter problems, please install IPython inside the virtualenv.
  warn("Attempting to work in a virtualenv. If you encounter problems, please "
Python 3.8.1 (v3.8.1:1b293b6006, Dec 18 2019, 14:08:53)
Type 'copyright', 'credits' or 'license' for more information
IPython 7.13.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: import yfinance as yf

In [2]: msft = yf.Ticker("MSFT")

In [3]: msft.info
---------------------------------------------------------------------------
SSLCertVerificationError                  Traceback (most recent call last)
/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/urllib/request.py in do_open(self, http_class, req, **http_conn_args)
   1318             try:
-> 1319                 h.request(req.get_method(), req.selector, req.data, headers,
   1320                           encode_chunked=req.has_header('Transfer-encoding'))

/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/http/client.py in request(self, method, url, body, headers, encode_chunked)
   1229         """Send a complete request to the server."""
-> 1230         self._send_request(method, url, body, headers, encode_chunked)
   1231

/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/http/client.py in _send_request(self, method, url, body, headers, encode_chunked)
   1275             body = _encode(body, 'body')
-> 1276         self.endheaders(body, encode_chunked=encode_chunked)
   1277

/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/http/client.py in endheaders(self, message_body, encode_chunked)
   1224             raise CannotSendHeader()
-> 1225         self._send_output(message_body, encode_chunked=encode_chunked)
   1226

/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/http/client.py in _send_output(self, message_body, encode_chunked)
   1003         del self._buffer[:]
-> 1004         self.send(msg)
   1005

/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/http/client.py in send(self, data)
    943             if self.auto_open:
--> 944                 self.connect()
    945             else:

/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/http/client.py in connect(self)
   1398
-> 1399             self.sock = self._context.wrap_socket(self.sock,
   1400                                                   server_hostname=server_hostname)

/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/ssl.py in wrap_socket(self, sock, server_side, do_handshake_on_connect, suppress_ragged_eofs, server_hostname, session)
    499         # ctx._wrap_socket()
--> 500         return self.sslsocket_class._create(
    501             sock=sock,

/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/ssl.py in _create(cls, sock, server_side, do_handshake_on_connect, suppress_ragged_eofs, server_hostname, context, session)
   1039                         raise ValueError("do_handshake_on_connect should not be specified for non-blocking sockets")
-> 1040                     self.do_handshake()
   1041             except (OSError, ValueError):

/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/ssl.py in do_handshake(self, block)
   1308                 self.settimeout(None)
-> 1309             self._sslobj.do_handshake()
   1310         finally:

SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1108)

During handling of the above exception, another exception occurred:

URLError                                  Traceback (most recent call last)
<ipython-input-3-c52d32a3ec1f> in <module>
----> 1 msft.info

/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/yfinance/ticker.py in info(self)
    136     @property
    137     def info(self):
--> 138         return self.get_info()
    139
    140     @property

/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/yfinance/base.py in get_info(self, proxy, as_dict, *args, **kwargs)
    413
    414     def get_info(self, proxy=None, as_dict=False, *args, **kwargs):
--> 415         self._get_fundamentals(proxy)
    416         data = self._info
    417         if as_dict:

/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/yfinance/base.py in _get_fundamentals(self, kind, proxy)
    282         # holders
    283         url = "{}/{}/holders".format(self._scrape_url, self.ticker)
--> 284         holders = _pd.read_html(url)
    285         self._major_holders = holders[0]
    286         self._institutional_holders = holders[1]

~/pandas-tutorial-master/venv/lib/python3.8/site-packages/pandas/io/html.py in read_html(io, match, flavor, header, index_col, skiprows, attrs, parse_dates, thousands, encoding, decimal, converters, na_values, keep_default_na, displayed_only)
   1083         )
   1084     validate_header_arg(header)
-> 1085     return _parse(
   1086         flavor=flavor,
   1087         io=io,

~/pandas-tutorial-master/venv/lib/python3.8/site-packages/pandas/io/html.py in _parse(flavor, io, match, attrs, encoding, displayed_only, **kwargs)
    893
    894         try:
--> 895             tables = p.parse_tables()
    896         except ValueError as caught:
    897             # if `io` is an io-like object, check if it's seekable

~/pandas-tutorial-master/venv/lib/python3.8/site-packages/pandas/io/html.py in parse_tables(self)
    211         list of parsed (header, body, footer) tuples from tables.
    212         """
--> 213         tables = self._parse_tables(self._build_doc(), self.match, self.attrs)
    214         return (self._parse_thead_tbody_tfoot(table) for table in tables)
    215

~/pandas-tutorial-master/venv/lib/python3.8/site-packages/pandas/io/html.py in _build_doc(self)
    731                     pass
    732             else:
--> 733                 raise e
    734         else:
    735             if not hasattr(r, "text_content"):

~/pandas-tutorial-master/venv/lib/python3.8/site-packages/pandas/io/html.py in _build_doc(self)
    712         try:
    713             if is_url(self.io):
--> 714                 with urlopen(self.io) as f:
    715                     r = parse(f, parser=parser)
    716             else:

~/pandas-tutorial-master/venv/lib/python3.8/site-packages/pandas/io/common.py in urlopen(*args, **kwargs)
    139     import urllib.request
    140
--> 141     return urllib.request.urlopen(*args, **kwargs)
    142
    143

/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/urllib/request.py in urlopen(url, data, timeout, cafile, capath, cadefault, context)
    220     else:
    221         opener = _opener
--> 222     return opener.open(url, data, timeout)
    223
    224 def install_opener(opener):

/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/urllib/request.py in open(self, fullurl, data, timeout)
    523
    524         sys.audit('urllib.Request', req.full_url, req.data, req.headers, req.get_method())
--> 525         response = self._open(req, data)
    526
    527         # post-process response

/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/urllib/request.py in _open(self, req, data)
    540
    541         protocol = req.type
--> 542         result = self._call_chain(self.handle_open, protocol, protocol +
    543                                   '_open', req)
    544         if result:

/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/urllib/request.py in _call_chain(self, chain, kind, meth_name, *args)
    500         for handler in handlers:
    501             func = getattr(handler, meth_name)
--> 502             result = func(*args)
    503             if result is not None:
    504                 return result

/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/urllib/request.py in https_open(self, req)
   1360
   1361         def https_open(self, req):
-> 1362             return self.do_open(http.client.HTTPSConnection, req,
   1363                 context=self._context, check_hostname=self._check_hostname)
   1364

/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/urllib/request.py in do_open(self, http_class, req, **http_conn_args)
   1320                           encode_chunked=req.has_header('Transfer-encoding'))
   1321             except OSError as err: # timeout error
-> 1322                 raise URLError(err)
   1323             r = h.getresponse()
   1324         except:

URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1108)>

In [4]: import ssl

In [5]: ssl._create_default_https_context = ssl._create_unverified_context

In [6]: msft = yf.Ticker("MSFT")

In [7]: msft.info
Out[7]:
{'zip': '98052',
 'sector': 'Technology',
 'fullTimeEmployees': 144000,
 'longBusinessSummary': 'Microsoft Corporation develops, licenses, and supports software, services, devices, and solutions worldwide. Its Productivity and Business Processes segment offers Office, Exchange, SharePoint, Microsoft Teams, Office 365 Security and Compliance, and Skype for Business, as well as related Client Access Licenses (CAL); and Skype, Outlook.com, and OneDrive. It also provides LinkedIn that includes Talent and marketing solutions, and subscriptions; and Dynamics 365, a set of cloud-based and on-premises business solutions for small and medium businesses, large organizations, and divisions of enterprises. Its Intelligent Cloud segment licenses SQL and Windows Servers, Visual Studio, System Center, and related CALs; GitHub that provides a collaboration platform and code hosting service for developers; and Azure, a cloud platform. It also provides support services and Microsoft consulting services to assist customers in developing, deploying, and managing Microsoft server and desktop solutions; and training and certification to developers and IT professionals on various Microsoft products. Its More Personal Computing segment offers Windows OEM licensing and other non-volume licensing of the Windows operating system; Windows Commercial, such as volume licensing of the Windows operating system, Windows cloud services, and other Windows commercial offerings; patent licensing; Windows Internet of Things; and MSN advertising. It also provides Microsoft Surface, PC accessories, and other intelligent devices; Gaming, including Xbox hardware, and Xbox software and services; video games and third-party video game royalties; and Search, including Bing and Microsoft advertising. It sells its products through distributors and resellers; and directly through digital marketplaces, online stores, and retail stores. It has strategic partnerships with Humana Inc., Nokia, Telkomsel, Swiss Re, and Kubota Corporation. The company was founded in 1975 and is headquartered in Redmond, Washington.',
 'city': 'Redmond',
 'phone': '425-882-8080',
 'state': 'WA',
 'country': 'United States',
 'companyOfficers': [],
 'website': 'http://www.microsoft.com',
 'maxAge': 1,
 'address1': 'One Microsoft Way',
 'fax': '425-706-7329',
 'industry': 'Software—Infrastructure',
 'previousClose': 174.57,
 'regularMarketOpen': 174.49,
 'twoHundredDayAverage': 159.58736,
 'trailingAnnualDividendYield': 0.011399439,
 'payoutRatio': 0.3233,
 'volume24Hr': None,
 'regularMarketDayHigh': 178.98,
 'navPrice': None,
 'averageDailyVolume10Day': 40409383,
 'totalAssets': None,
 'regularMarketPreviousClose': 174.57,
 'fiftyDayAverage': 161.73372,
 'trailingAnnualDividendRate': 1.99,
 'open': 174.49,
 'toCurrency': None,
 'averageVolume10days': 40409383,
 'expireDate': None,
 'yield': None,
 'algorithm': None,
 'dividendRate': 2.04,
 'exDividendDate': 1589932800,
 'beta': 0.952031,
 'circulatingSupply': None,
 'startDate': None,
 'regularMarketDayLow': 173.8,
 'priceHint': 2,
 'currency': 'USD',
 'trailingPE': 29.796734,
 'regularMarketVolume': 30372862,
 'lastMarket': None,
 'maxSupply': None,
 'openInterest': None,
 'marketCap': 1356222300160,
 'volumeAllCurrencies': None,
 'strikePrice': None,
 'averageVolume': 56262191,
 'priceToSalesTrailing12Months': 9.77817,
 'dayLow': 173.8,
 'ask': 180.2,
 'ytdReturn': None,
 'askSize': 3000,
 'volume': 30372862,
 'fiftyTwoWeekHigh': 190.7,
 'forwardPE': 28.798712,
 'fromCurrency': None,
 'fiveYearAvgDividendYield': 1.95,
 'fiftyTwoWeekLow': 119.01,
 'bid': 180.48,
 'tradeable': False,
 'dividendYield': 0.0117,
 'bidSize': 2200,
 'dayHigh': 178.98,
 'exchange': 'NMS',
 'shortName': 'Microsoft Corporation',
 'longName': 'Microsoft Corporation',
 'exchangeTimezoneName': 'America/New_York',
 'exchangeTimezoneShortName': 'EDT',
 'isEsgPopulated': False,
 'gmtOffSetMilliseconds': '-14400000',
 'quoteType': 'EQUITY',
 'symbol': 'MSFT',
 'messageBoardId': 'finmb_21835',
 'market': 'us_market',
 'annualHoldingsTurnover': None,
 'enterpriseToRevenue': 9.392,
 'beta3Year': None,
 'profitMargins': 0.33356997,
 'enterpriseToEbitda': 20.324,
 '52WeekChange': 0.4247929,
 'morningStarRiskRating': None,
 'forwardEps': 6.21,
 'revenueQuarterlyGrowth': None,
 'sharesOutstanding': 7583439872,
 'fundInceptionDate': None,
 'annualReportExpenseRatio': None,
 'bookValue': 15.086,
 'sharesShort': 53310482,
 'sharesPercentSharesOut': 0.0069999998,
 'fundFamily': None,
 'lastFiscalYearEnd': 1561852800,
 'heldPercentInstitutions': 0.74192,
 'netIncomeToCommon': 46265999360,
 'trailingEps': 6.002,
 'lastDividendValue': None,
 'SandP52WeekChange': -0.014323652,
 'priceToBook': 11.854699,
 'heldPercentInsiders': 0.014249999,
 'nextFiscalYearEnd': 1625011200,
 'mostRecentQuarter': 1585612800,
 'shortRatio': 0.82,
 'sharesShortPreviousMonthDate': 1584057600,
 'floatShares': 7472418682,
 'enterpriseValue': 1302605463552,
 'threeYearAverageReturn': None,
 'lastSplitDate': 1045526400,
 'lastSplitFactor': '2:1',
 'legalType': None,
 'morningStarOverallRating': None,
 'earningsQuarterlyGrowth': 0.221,
 'dateShortInterest': 1586908800,
 'pegRatio': 2.02,
 'lastCapGain': None,
 'shortPercentOfFloat': 0.0070999996,
 'sharesShortPriorMonth': 55155176,
 'category': None,
 'fiveYearAverageReturn': None,
 'regularMarketPrice': 174.49,
 'logo_url': 'https://logo.clearbit.com/microsoft.com'}

In [8]: msft.history(period="1y")
Out[8]:
              Open    High     Low   Close    Volume  Dividends  Stock Splits
Date
2019-05-06  124.74  126.88  124.46  126.48  24239800        0.0             0
2019-05-07  124.81  125.52  122.60  123.88  36017700        0.0             0
2019-05-08  123.80  124.72  123.12  123.87  28419000        0.0             0
2019-05-09  122.67  124.15  121.96  123.86  27235800        0.0             0
2019-05-10  123.28  126.26  122.20  125.47  30915100        0.0             0
...            ...     ...     ...     ...       ...        ...           ...
2020-04-28  175.59  175.67  169.39  169.81  34392700        0.0             0
2020-04-29  173.22  177.68  171.88  177.43  51286600        0.0             0
2020-04-30  180.00  180.40  176.23  179.21  53875900        0.0             0
2020-05-01  175.80  178.64  174.01  174.57  39370500        0.0             0
2020-05-04  174.49  179.00  173.80  178.84  30336200        0.0             0

[252 rows x 7 columns]

In [9]: msft.actions
Out[9]:
            Dividends  Stock Splits
Date
2019-05-15       0.46           0.0
2019-08-14       0.46           0.0
2019-11-20       0.51           0.0
2020-02-19       0.51           0.0

In [10]: msft.financials
Out[10]:
Empty DataFrame
Columns: [Open, High, Low, Close, Adj Close, Volume]
Index: []

In [11]: msft.quarterly_financials
Out[11]:
Empty DataFrame
Columns: [Open, High, Low, Close, Adj Close, Volume]
Index: []

In [12]: stock.major_holders
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-12-4b45999f2678> in <module>
----> 1 stock.major_holders

NameError: name 'stock' is not defined

In [13]: msft.major_holders
Out[13]:
        0                                      1
0   1.42%        % of Shares Held by All Insider
1  74.19%       % of Shares Held by Institutions
2  75.27%        % of Float Held by Institutions
3    4611  Number of Institutions Holding Shares

In [14]: msft.institutional_holders
Out[14]:
                              Holder     Shares  ...   % Out        Value
0         Vanguard Group, Inc. (The)  623667281  ...  0.0820  98352330213
1                     Blackrock Inc.  515197221  ...  0.0677  81246601751
2           State Street Corporation  315672520  ...  0.0415  49781556404
3                           FMR, LLC  239124143  ...  0.0314  37709877351
4            Capital World Investors  180557630  ...  0.0237  28473938251
5      Price (T.Rowe) Associates Inc  175036277  ...  0.0230  27603220882
6      Geode Capital Management, LLC  113401519  ...  0.0149  17883419546
7    Capital International Investors   99996798  ...  0.0131  15769495044
8         Northern Trust Corporation   93192050  ...  0.0123  14696386285
9  Capital Research Global Investors   92776236  ...  0.0122  14630812417

[10 rows x 5 columns]

In [15]: msft.balance_sheet
Out[15]:
Empty DataFrame
Columns: [Open, High, Low, Close, Adj Close, Volume]
Index: []

In [16]: msft.balancesheet
Out[16]:
Empty DataFrame
Columns: [Open, High, Low, Close, Adj Close, Volume]
Index: []

In [17]: msft.quarterly_balance_sheet
Out[17]:
Empty DataFrame
Columns: [Open, High, Low, Close, Adj Close, Volume]
Index: []

In [18]: msft.sustainability
Out[18]:
                                     Value
2020-3
palmOil                              False
controversialWeapons                 False
gambling                             False
socialScore                           9.87
nuclear                              False
furLeather                           False
alcoholic                            False
gmo                                  False
catholic                             False
socialPercentile                         0
peerCount                              100
governanceScore                       5.24
environmentPercentile                    0
animalTesting                        False
tobacco                              False
totalEsg                             15.55
highestControversy                       3
esgPerformance                  UNDER_PERF
coal                                 False
pesticides                           False
adult                                False
percentile                            7.96
peerGroup              Software & Services
smallArms                            False
environmentScore                      0.44
governancePercentile                     0
militaryContract                     False

In [19]: msft.recommendations
Out[19]:
                      Firm       To Grade From Grade Action
Date
2012-03-16  Argus Research            Buy                up
2012-03-19  Hilliard Lyons  Long-Term Buy              main
2012-03-22  Morgan Stanley     Overweight              main
2012-04-03             UBS            Buy              main
2012-04-20   Goldman Sachs        Neutral              main
...                    ...            ...        ...    ...
2020-04-30  Morgan Stanley     Overweight              main
2020-04-30       Citigroup        Neutral              main
2020-04-30     BMO Capital     Outperform              main
2020-04-30   Credit Suisse     Outperform              main
2020-04-30          Mizuho            Buy              main

[281 rows x 4 columns]

In [20]: msft.calendar
Out[20]:
                                    0                    1
Earnings Date     2020-07-16 00:00:00  2020-07-20 00:00:00
Earnings Average                 1.39                 1.39
Earnings Low                     1.35                 1.35
Earnings High                    1.51                 1.51
Revenue Average           36509700000          36509700000
Revenue Low               36053000000          36053000000
Revenue High              37210000000          37210000000

In [21]: msft.isin
---------------------------------------------------------------------------
TimeoutError                              Traceback (most recent call last)
/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/urllib3/connection.py in _new_conn(self)
    155         try:
--> 156             conn = connection.create_connection(
    157                 (self._dns_host, self.port), self.timeout, **extra_kw

/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/urllib3/util/connection.py in create_connection(address, timeout, source_address, socket_options)
     83     if err is not None:
---> 84         raise err
     85

/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/urllib3/util/connection.py in create_connection(address, timeout, source_address, socket_options)
     73                 sock.bind(source_address)
---> 74             sock.connect(sa)
     75             return sock

TimeoutError: [Errno 60] Operation timed out

During handling of the above exception, another exception occurred:

NewConnectionError                        Traceback (most recent call last)
/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/urllib3/connectionpool.py in urlopen(self, method, url, body, headers, retries, redirect, assert_same_host, timeout, pool_timeout, release_conn, chunked, body_pos, **response_kw)
    664             # Make the request on the httplib connection object.
--> 665             httplib_response = self._make_request(
    666                 conn,

/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/urllib3/connectionpool.py in _make_request(self, conn, method, url, timeout, chunked, **httplib_request_kw)
    375         try:
--> 376             self._validate_conn(conn)
    377         except (SocketTimeout, BaseSSLError) as e:

/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/urllib3/connectionpool.py in _validate_conn(self, conn)
    993         if not getattr(conn, "sock", None):  # AppEngine might not have  `.sock`
--> 994             conn.connect()
    995

/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/urllib3/connection.py in connect(self)
    299         # Add certificate verification
--> 300         conn = self._new_conn()
    301         hostname = self.host

/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/urllib3/connection.py in _new_conn(self)
    167         except SocketError as e:
--> 168             raise NewConnectionError(
    169                 self, "Failed to establish a new connection: %s" % e

NewConnectionError: <urllib3.connection.VerifiedHTTPSConnection object at 0x115f47af0>: Failed to establish a new connection: [Errno 60] Operation timed out

During handling of the above exception, another exception occurred:

MaxRetryError                             Traceback (most recent call last)
/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/requests/adapters.py in send(self, request, stream, timeout, verify, cert, proxies)
    438             if not chunked:
--> 439                 resp = conn.urlopen(
    440                     method=request.method,

/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/urllib3/connectionpool.py in urlopen(self, method, url, body, headers, retries, redirect, assert_same_host, timeout, pool_timeout, release_conn, chunked, body_pos, **response_kw)
    718
--> 719             retries = retries.increment(
    720                 method, url, error=e, _pool=self, _stacktrace=sys.exc_info()[2]

/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/urllib3/util/retry.py in increment(self, method, url, response, error, _pool, _stacktrace)
    435         if new_retry.is_exhausted():
--> 436             raise MaxRetryError(_pool, url, error or ResponseError(cause))
    437

MaxRetryError: HTTPSConnectionPool(host='markets.businessinsider.com', port=443): Max retries exceeded with url: /ajax/SearchController_Suggest?max_results=25&query=Microsoft%20Corporation (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x115f47af0>: Failed to establish a new connection: [Errno 60] Operation timed out'))

During handling of the above exception, another exception occurred:

ConnectionError                           Traceback (most recent call last)
<ipython-input-21-34fdac0987fe> in <module>
----> 1 msft.isin

/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/yfinance/ticker.py in isin(self)
    108     @property
    109     def isin(self):
--> 110         return self.get_isin()
    111
    112     @property

/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/yfinance/base.py in get_isin(self, proxy)
    500               'SearchController_Suggest?max_results=25&query=%s' \
    501             % urlencode(q)
--> 502         data = _requests.get(url=url, proxies=proxy).text
    503
    504         search_str = '"{}|'.format(ticker)

/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/requests/api.py in get(url, params, **kwargs)
     74
     75     kwargs.setdefault('allow_redirects', True)
---> 76     return request('get', url, params=params, **kwargs)
     77
     78

/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/requests/api.py in request(method, url, **kwargs)
     59     # cases, and look like a memory leak in others.
     60     with sessions.Session() as session:
---> 61         return session.request(method=method, url=url, **kwargs)
     62
     63

/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/requests/sessions.py in request(self, method, url, params, data, headers, cookies, files, auth, timeout, allow_redirects, proxies, hooks, stream, verify, cert, json)
    528         }
    529         send_kwargs.update(settings)
--> 530         resp = self.send(prep, **send_kwargs)
    531
    532         return resp

/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/requests/sessions.py in send(self, request, **kwargs)
    641
    642         # Send the request
--> 643         r = adapter.send(request, **kwargs)
    644
    645         # Total elapsed time of the request (approximately)

/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/requests/adapters.py in send(self, request, stream, timeout, verify, cert, proxies)
    514                 raise SSLError(e, request=request)
    515
--> 516             raise ConnectionError(e, request=request)
    517
    518         except ClosedPoolError as e:

ConnectionError: HTTPSConnectionPool(host='markets.businessinsider.com', port=443): Max retries exceeded with url: /ajax/SearchController_Suggest?max_results=25&query=Microsoft%20Corporation (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x115f47af0>: Failed to establish a new connection: [Errno 60] Operation timed out'))

In [22]: msft.options
Out[22]:
('2020-05-08',
 '2020-05-15',
 '2020-05-22',
 '2020-05-29',
 '2020-06-05',
 '2020-06-12',
 '2020-06-19',
 '2020-07-17',
 '2020-09-18',
 '2020-10-16',
 '2020-12-18',
 '2021-01-15',
 '2021-03-19',
 '2021-06-18',
 '2021-09-17',
 '2022-01-21',
 '2022-03-18',
 '2022-06-17',
 '2022-09-16')

In [23]: import yfinance as yf

In [24]: msft = yf.Ticker("MSFT")

In [25]: msft.get_actions(proxy="PROXY_SERVER")
---------------------------------------------------------------------------
gaierror                                  Traceback (most recent call last)
/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/urllib3/connection.py in _new_conn(self)
    155         try:
--> 156             conn = connection.create_connection(
    157                 (self._dns_host, self.port), self.timeout, **extra_kw

/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/urllib3/util/connection.py in create_connection(address, timeout, source_address, socket_options)
     60
---> 61     for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM):
     62         af, socktype, proto, canonname, sa = res

/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/socket.py in getaddrinfo(host, port, family, type, proto, flags)
    917     addrlist = []
--> 918     for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
    919         af, socktype, proto, canonname, sa = res

gaierror: [Errno 8] nodename nor servname provided, or not known

During handling of the above exception, another exception occurred:

NewConnectionError                        Traceback (most recent call last)
/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/urllib3/connectionpool.py in urlopen(self, method, url, body, headers, retries, redirect, assert_same_host, timeout, pool_timeout, release_conn, chunked, body_pos, **response_kw)
    661             if is_new_proxy_conn:
--> 662                 self._prepare_proxy(conn)
    663

/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/urllib3/connectionpool.py in _prepare_proxy(self, conn)
    947         conn.set_tunnel(self._proxy_host, self.port, self.proxy_headers)
--> 948         conn.connect()
    949

/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/urllib3/connection.py in connect(self)
    299         # Add certificate verification
--> 300         conn = self._new_conn()
    301         hostname = self.host

/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/urllib3/connection.py in _new_conn(self)
    167         except SocketError as e:
--> 168             raise NewConnectionError(
    169                 self, "Failed to establish a new connection: %s" % e

NewConnectionError: <urllib3.connection.VerifiedHTTPSConnection object at 0x117227e50>: Failed to establish a new connection: [Errno 8] nodename nor servname provided, or not known

During handling of the above exception, another exception occurred:

MaxRetryError                             Traceback (most recent call last)
/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/requests/adapters.py in send(self, request, stream, timeout, verify, cert, proxies)
    438             if not chunked:
--> 439                 resp = conn.urlopen(
    440                     method=request.method,

/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/urllib3/connectionpool.py in urlopen(self, method, url, body, headers, retries, redirect, assert_same_host, timeout, pool_timeout, release_conn, chunked, body_pos, **response_kw)
    718
--> 719             retries = retries.increment(
    720                 method, url, error=e, _pool=self, _stacktrace=sys.exc_info()[2]

/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/urllib3/util/retry.py in increment(self, method, url, response, error, _pool, _stacktrace)
    435         if new_retry.is_exhausted():
--> 436             raise MaxRetryError(_pool, url, error or ResponseError(cause))
    437

MaxRetryError: HTTPSConnectionPool(host='query1.finance.yahoo.com', port=443): Max retries exceeded with url: /v8/finance/chart/MSFT?period1=-2208988800&period2=1588671618&interval=1d&includePrePost=False&events=div%2Csplits (Caused by ProxyError('Cannot connect to proxy.', NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x117227e50>: Failed to establish a new connection: [Errno 8] nodename nor servname provided, or not known')))

During handling of the above exception, another exception occurred:

ProxyError                                Traceback (most recent call last)
<ipython-input-25-90f4b27c292f> in <module>
----> 1 msft.get_actions(proxy="PROXY_SERVER")

/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/yfinance/base.py in get_actions(self, proxy)
    471     def get_actions(self, proxy=None):
    472         if self._history is None:
--> 473             self.history(period="max", proxy=proxy)
    474         actions = self._history[["Dividends", "Stock Splits"]]
    475         return actions[actions != 0].dropna(how='all').fillna(0)

/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/yfinance/base.py in history(self, period, interval, start, end, prepost, actions, auto_adjust, back_adjust, proxy, rounding, tz, **kwargs)
    148         # Getting data from json
    149         url = "{}/v8/finance/chart/{}".format(self._base_url, self.ticker)
--> 150         data = _requests.get(url=url, params=params, proxies=proxy)
    151         if "Will be right back" in data.text:
    152             raise RuntimeError("*** YAHOO! FINANCE IS CURRENTLY DOWN! ***\n"

/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/requests/api.py in get(url, params, **kwargs)
     74
     75     kwargs.setdefault('allow_redirects', True)
---> 76     return request('get', url, params=params, **kwargs)
     77
     78

/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/requests/api.py in request(method, url, **kwargs)
     59     # cases, and look like a memory leak in others.
     60     with sessions.Session() as session:
---> 61         return session.request(method=method, url=url, **kwargs)
     62
     63

/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/requests/sessions.py in request(self, method, url, params, data, headers, cookies, files, auth, timeout, allow_redirects, proxies, hooks, stream, verify, cert, json)
    528         }
    529         send_kwargs.update(settings)
--> 530         resp = self.send(prep, **send_kwargs)
    531
    532         return resp

/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/requests/sessions.py in send(self, request, **kwargs)
    641
    642         # Send the request
--> 643         r = adapter.send(request, **kwargs)
    644
    645         # Total elapsed time of the request (approximately)

/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/requests/adapters.py in send(self, request, stream, timeout, verify, cert, proxies)
    508
    509             if isinstance(e.reason, _ProxyError):
--> 510                 raise ProxyError(e, request=request)
    511
    512             if isinstance(e.reason, _SSLError):

ProxyError: HTTPSConnectionPool(host='query1.finance.yahoo.com', port=443): Max retries exceeded with url: /v8/finance/chart/MSFT?period1=-2208988800&period2=1588671618&interval=1d&includePrePost=False&events=div%2Csplits (Caused by ProxyError('Cannot connect to proxy.', NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x117227e50>: Failed to establish a new connection: [Errno 8] nodename nor servname provided, or not known')))

In [26]: import yfinance as yf

In [27]: tickers = yf.Tickers('msft aapl goog')

In [28]: tickers.msft.info
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-28-de8923a12a37> in <module>
----> 1 tickers.msft.info

AttributeError: 'Tickers' object has no attribute 'msft'

In [29]: import ssl

In [30]: ssl._create_default_https_context = ssl._create_unverified_context

In [31]: tickers = yf.Tickers('msft aapl goog')

In [32]: tickers.msft.info
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-32-de8923a12a37> in <module>
----> 1 tickers.msft.info

AttributeError: 'Tickers' object has no attribute 'msft'

In [33]: ?yf.Tickers
Init signature: yf.Tickers(tickers)
Docstring:      <no docstring>
File:           /Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/yfinance/tickers.py
Type:           type
Subclasses:

In [34]: import yfinance as yf

In [35]: data = yf.download("SPR AAPL", start ="2019-01-01", end="2020-05-04")
[*********************100%***********************]  2 of 2 completed

In [36]: data.head
Out[36]:
<bound method NDFrame.head of              Adj Close                  Close  ...       Open    Volume
                  AAPL        SPR        AAPL  ...        SPR      AAPL      SPR
Date                                           ...
2018-12-31  155.037109  71.644485  157.740005  ...  71.089996  35003500   611600
2019-01-02  155.214005  71.972443  157.919998  ...  71.220001  37039700   552300
2019-01-03  139.753540  69.656845  142.190002  ...  71.879997  91312200   410100
2019-01-04  145.719513  72.042007  148.259995  ...  71.209999  58607100   694700
2019-01-07  145.395203  72.807243  147.929993  ...  72.830002  54777800   925800
...                ...        ...         ...  ...        ...       ...      ...
2020-04-27  283.170013  19.139999  283.170013  ...  18.230000  29271900  3400300
2020-04-28  278.579987  20.500000  278.579987  ...  20.170000  28001200  3790000
2020-04-29  287.730011  23.600000  287.730011  ...  22.049999  34320200  7480700
2020-04-30  293.799988  22.160000  293.799988  ...  23.000000  45766000  5097500
2020-05-01  289.070007  20.469999  289.070007  ...  21.500000  60154200  3561300

[337 rows x 12 columns]>

In [37]: data = yf.download("SPR AAPL MSFT",period="ytd",interval="3mo",group_by
    ...: ='ticker',auto_adjust= True, prepost= True, threads = 6, proxy =None)
[*********************100%***********************]  3 of 3 completed

In [38]: data.head
Out[38]:
<bound method NDFrame.head of                   SPR             ...        AAPL
                 Open       High  ...       Close        Volume
Date                              ...
2020-01-01  73.271088  75.070135  ...  253.687912  3.058574e+09
2020-02-07        NaN        NaN  ...         NaN           NaN
2020-02-19        NaN        NaN  ...         NaN           NaN
2020-03-19        NaN        NaN  ...         NaN           NaN
2020-04-01  22.469999  25.320000  ...  293.160004  9.100395e+08
2020-05-04  19.139999  20.420000  ...  293.160004  3.339199e+07

[6 rows x 15 columns]>

参考学习资料:
https://pypi.org/project/yfinance/

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,546评论 6 507
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,224评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,911评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,737评论 1 294
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,753评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,598评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,338评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,249评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,696评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,888评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,013评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,731评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,348评论 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,929评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,048评论 1 270
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,203评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,960评论 2 355