使用Python包yfinance读取雅虎财经上的股票数据


使用Python包yfinance读取雅虎财经上的股票数据

安装yfinance

yfinance是一个使用简单但是功能强大的开源Python包,通过这个包我们可以获取在雅虎财经上列出来的包含历史数据的所有证券信息。除了通过GitHub上的源码安装外,建议使用传统的pip来安装。

python3 -m pip install yfinance --upgrade --no-cache-dir

导入yfinance

yfinance包有一个Ticker模块,可以通过该模块获取到相应证券的市场数据。以下抓取苹果公司(AAPL)的相关数据为例。

import yfinance as yf

aapl = yf.Ticker('AAPL')

print(aapl)
yfinance.Ticker object <AAPL>

获取股票所对应信息 - info

调用Ticker对象的info函数可以获取该股票的所有信息,返回一个dictionary结构数据,里面包含比如该公司所属sector,员工数,所在城市,和各种财务表现等。由于整个dictionary比较大,下面只选择打印了几个信息。

aapl_info = aapl.info

print('AAPL sector: ', aapl_info['sector'])
print('AAPL EBITA Margins: ', aapl_info['ebitdaMargins'])
print('AAPL Profit Margins: ', aapl_info['profitMargins'])
print('AAPL Gross Margins: ', aapl_info['grossMargins'])
print('AAPL Day High: ', aapl_info['dayHigh'])
AAPL sector:  Technology
AAPL EBITA Margins:  0.32867
AAPL Profit Margins:  0.25882
AAPL Gross Margins:  0.41779
AAPL Day High:  177.725

获取股票历史数据 - history

调用history函数可以获取到该股票的历史数据。该函数有以下几个参数可供配置。

  • period,表示获取多久的数据,有10种选择:1d, 5d, 1mo, 3mo, 6mo, 1y, 2y, 5y, 10y, ytd, max。
  • interval,表示数据的精度,有13种选择:1m, 2m, 5m, 15m, 30m, 60m, 90m, 1h, 1d, 5d, 1wk, 1mo, 3mo。天以内的数据只能最多采集60天以内的,精度越高,能采集的数据天数更少,比如1m数据只能采集7天以内的。
  • start,如果没有配置period,也可以使用start即数据开始时间和end即数据结束时间来定义应该获取多久的数据
  • end,同上
  • prepost,是否包含盘前和盘后价格,默认False不包含
  • auto_adjust,是否按照美国线(英语:Open-High-Low-Close chart,OHLC chart)来调整,含开盘价、最高价、最低价、收盘价,默认True
  • actions,是否包含分红和扩股信息,默认包含
# 获取AAPL所有的历史数据,并打印最开始5天的记录
aapl_history_max = aapl.history(period='max')
aapl_history_max.head()

OpenHighLowCloseVolumeDividendsStock Splits
Date
1980-12-120.1004530.1008900.1004530.1004534690336000.00.0
1980-12-150.0956490.0956490.0952130.0952131758848000.00.0
1980-12-160.0886610.0886610.0882240.0882241057280000.00.0
1980-12-170.0904080.0908450.0904080.090408864416000.00.0
1980-12-180.0930290.0934660.0930290.093029734496000.00.0
# 获取AAPL从2021年12月1日到2021年12月15日精度为2分钟的历史数据,并打印最开始的5条记录。
aapl_history_1m = aapl.history(start="2021-12-01", end="2021-12-15", interval="2m")
aapl_history_1m.head()

OpenHighLowCloseVolumeDividendsStock Splits
Datetime
2021-12-01 09:30:00-05:00166.839996167.095901166.559998166.845001757814000
2021-12-01 09:32:00-05:00166.845001166.990005166.429993166.429993121214700
2021-12-01 09:34:00-05:00166.242203166.500000166.139999166.259995130402200
2021-12-01 09:36:00-05:00166.250000166.800003166.089996166.468796139051400
2021-12-01 09:38:00-05:00167.000000167.419907167.000000167.399994157209200

获取股票的分红和扩股数据 - actions

其实在获取历史数据的时候我们就可以直接获取到股票的分红和扩股数据,但是并不是每一条历史数据上都有分红或者扩股,使用actions函数可以直接获取到该信息。结合上面的历史数据信息我们可以看到AAPL在1980年发行以后到1987年5月11日才开始第一次分红,同年的6月16日开始第一次扩股。

aapl_actions = aapl.actions

aapl_actions.head()

DividendsStock Splits
Date
1987-05-110.0005360.0
1987-06-160.0000002.0
1987-08-100.0005360.0
1987-11-170.0007140.0
1988-02-120.0007140.0

获取股票的分红数据 - dividends

actions函数的返回结果同时记录了分红和扩股信息,如果只想看分红信息,可以直接使用dividends。

aapl_dividends = aapl.dividends

aapl_dividends.head()
Date
1987-05-11    0.000536
1987-08-10    0.000536
1987-11-17    0.000714
1988-02-12    0.000714
1988-05-16    0.000714
Name: Dividends, dtype: float64

获取股票的分红数据 - splits

actions函数的返回结果同时记录了分红和扩股信息,如果只想看扩股信息,可以直接使用splits。

aapl_splits = aapl.splits

aapl_splits.head()
Date
1987-06-16    2.0
2000-06-21    2.0
2005-02-28    2.0
2014-06-09    7.0
2020-08-31    4.0
Name: Stock Splits, dtype: float64

获取重要持股人信息 - major_holders

可以看到AAPL主要由机构持股。

aapl_major_holders = aapl.major_holders

aapl_major_holders

01
00.07%% of Shares Held by All Insider
158.81%% of Shares Held by Institutions
258.86%% of Float Held by Institutions
34959Number of Institutions Holding Shares

获取重要机构持股人信息 - institutional_holders

aapl_institutional_holders = aapl.institutional_holders

aapl_institutional_holders.head()

HolderSharesDate Reported% OutValue
0Vanguard Group, Inc. (The)12663326672021-09-290.0772179186072380
1Blackrock Inc.10262239832021-09-290.0626145210693594
2Berkshire Hathaway, Inc8871355542021-09-290.0541125529680891
3State Street Corporation6221635412021-09-290.037988036141051
4FMR, LLC3506177592021-09-290.021449612412898

获取共同基金持股人信息 - mutualfund_holders

aapl_mutualfund_holders = aapl.mutualfund_holders

aapl_mutualfund_holders.head()

HolderSharesDate Reported% OutValue
0Vanguard Total Stock Market Index Fund4437976602021-09-290.027162797368890
1Vanguard 500 Index Fund3297770512021-09-290.020146663452716
2SPDR S&P 500 ETF Trust1660475292021-09-290.010123495725353
3Fidelity 500 Index Fund1521736222021-10-300.009322795608575
4Invesco ETF Tr-Invesco QQQ Tr, Series 1 ETF1452544262021-10-300.008921759113014

获取详细财务信息

当季财年信息 - calendar

aapl_calendar = aapl.calendar

aapl_calendar

01
Earnings Date2022-01-25 21:00:002022-01-31 21:00:00
Earnings Average1.881.88
Earnings Low1.751.75
Earnings High1.971.97
Revenue Average118137000000118137000000
Revenue Low111806000000111806000000
Revenue High121303000000121303000000

年度营业收入和税后收益 - earnings

只显示最近四次财务统计期

aapl_earnings = aapl.earnings

aapl_earnings

RevenueEarnings
Year
201826559500000059531000000
201926017400000055256000000
202027451500000057411000000
202136581700000094680000000

季度营业收入和税后收益 - quarterly_earnings

只显示最近四次财务统计期

aapl_quarterly_earnings = aapl.quarterly_earnings

aapl_quarterly_earnings

RevenueEarnings
Quarter
4Q202011143900000028755000000
1Q20218958400000023630000000
2Q20218143400000021744000000
3Q20218336000000020551000000

年度详细财报 - financials

只显示最近四个财务统计期

aapl_financials = aapl.financials

aapl_financials

2021-09-252020-09-262019-09-282018-09-29
Research Development21914000000.018752000000.016217000000.014236000000.0
Effect Of Accounting ChargesNoneNoneNoneNone
Income Before Tax109207000000.067091000000.065737000000.072903000000.0
Minority InterestNoneNoneNoneNone
Net Income94680000000.057411000000.055256000000.059531000000.0
Selling General Administrative21973000000.019916000000.018245000000.016705000000.0
Gross Profit152836000000.0104956000000.098392000000.0101839000000.0
Ebit108949000000.066288000000.063930000000.070898000000.0
Operating Income108949000000.066288000000.063930000000.070898000000.0
Other Operating ExpensesNoneNoneNoneNone
Interest Expense-2645000000.0-2873000000.0-3576000000.0-3240000000.0
Extraordinary ItemsNoneNoneNoneNone
Non RecurringNoneNoneNoneNone
Other ItemsNoneNoneNoneNone
Income Tax Expense14527000000.09680000000.010481000000.013372000000.0
Total Revenue365817000000.0274515000000.0260174000000.0265595000000.0
Total Operating Expenses256868000000.0208227000000.0196244000000.0194697000000.0
Cost Of Revenue212981000000.0169559000000.0161782000000.0163756000000.0
Total Other Income Expense Net258000000.0803000000.01807000000.02005000000.0
Discontinued OperationsNoneNoneNoneNone
Net Income From Continuing Ops94680000000.057411000000.055256000000.059531000000.0
Net Income Applicable To Common Shares94680000000.057411000000.055256000000.059531000000.0

季度详细财报 - quarterly_financials

只显示最近四个财务统计期

aapl_quarterly_financials = aapl.quarterly_financials

aapl_quarterly_financials

2021-09-252021-06-262021-03-272020-12-26
Research Development5772000000.05717000000.05262000000.05163000000.0
Effect Of Accounting ChargesNoneNoneNoneNone
Income Before Tax23248000000.024369000000.028011000000.033579000000.0
Minority InterestNoneNoneNoneNone
Net Income20551000000.021744000000.023630000000.028755000000.0
Selling General Administrative5616000000.05412000000.05314000000.05631000000.0
Gross Profit35174000000.035255000000.038079000000.044328000000.0
Ebit23786000000.024126000000.027503000000.033534000000.0
Operating Income23786000000.024126000000.027503000000.033534000000.0
Other Operating ExpensesNoneNoneNoneNone
Interest Expense-672000000.0-665000000.0-670000000.0-638000000.0
Extraordinary ItemsNoneNoneNoneNone
Non RecurringNoneNoneNoneNone
Other ItemsNoneNoneNoneNone
Income Tax Expense2697000000.02625000000.04381000000.04824000000.0
Total Revenue83360000000.081434000000.089584000000.0111439000000.0
Total Operating Expenses59574000000.057308000000.062081000000.077905000000.0
Cost Of Revenue48186000000.046179000000.051505000000.067111000000.0
Total Other Income Expense Net-538000000.0243000000.0508000000.045000000.0
Discontinued OperationsNoneNoneNoneNone
Net Income From Continuing Ops20551000000.021744000000.023630000000.028755000000.0
Net Income Applicable To Common Shares20551000000.021744000000.023630000000.028755000000.0

年度资产负债表 - balance_sheet

只显示最近四个财务统计期

aapl_balance_sheet = aapl.balance_sheet

aapl_balance_sheet

2021-09-252020-09-262019-09-282018-09-29
Total Liab2.879120e+112.585490e+112.480280e+112.585780e+11
Total Stockholder Equity6.309000e+106.533900e+109.048800e+101.071470e+11
Other Current Liab5.357700e+104.786700e+104.324200e+103.929300e+10
Total Assets3.510020e+113.238880e+113.385160e+113.657250e+11
Common Stock5.736500e+105.077900e+104.517400e+104.020100e+10
Other Current Assets1.411100e+101.126400e+101.235200e+101.208700e+10
Retained Earnings5.562000e+091.496600e+104.589800e+107.040000e+10
Other Liab4.305000e+104.610800e+105.050300e+104.891400e+10
Treasury Stock1.630000e+08-4.060000e+08-5.840000e+08-3.454000e+09
Other Assets3.876200e+103.395200e+103.297800e+102.228300e+10
Cash3.494000e+103.801600e+104.884400e+102.591300e+10
Total Current Liabilities1.254810e+111.053920e+111.057180e+111.159290e+11
Short Long Term Debt9.613000e+098.773000e+091.026000e+108.784000e+09
Other Stockholder Equity1.630000e+08-4.060000e+08-5.840000e+08-3.454000e+09
Property Plant Equipment4.952700e+104.533600e+103.737800e+104.130400e+10
Total Current Assets1.348360e+111.437130e+111.628190e+111.313390e+11
Long Term Investments1.278770e+111.008870e+111.053410e+111.707990e+11
Net Tangible Assets6.309000e+106.533900e+109.048800e+101.071470e+11
Short Term Investments2.769900e+105.292700e+105.171300e+104.038800e+10
Net Receivables5.150600e+103.744500e+104.580400e+104.899500e+10
Long Term Debt1.091060e+119.866700e+109.180700e+109.373500e+10
Inventory6.580000e+094.061000e+094.106000e+093.956000e+09
Accounts Payable5.476300e+104.229600e+104.623600e+105.588800e+10

季度资产负债表 - quarterly_balance_sheet

只显示最近四个财务统计期

aapl_quarterly_balance_sheet = aapl.quarterly_balance_sheet

aapl_quarterly_balance_sheet

2021-09-252021-06-262021-03-272020-12-26
Total Liab2.879120e+112.655600e+112.679800e+112.878300e+11
Total Stockholder Equity6.309000e+106.428000e+106.917800e+106.622400e+10
Other Current Liab5.357700e+105.130600e+105.325500e+105.589900e+10
Total Assets3.510020e+113.298400e+113.371580e+113.540540e+11
Common Stock5.736500e+105.498900e+105.420300e+105.174400e+10
Other Current Assets1.411100e+101.364100e+101.337600e+101.368700e+10
Retained Earnings5.562000e+099.233000e+091.526100e+101.430100e+10
Other Liab4.305000e+103.835400e+103.985300e+104.304200e+10
Treasury Stock1.630000e+085.800000e+07-2.860000e+081.790000e+08
Other Assets3.876200e+104.485400e+104.333900e+104.327000e+10
Cash3.494000e+103.405000e+103.846600e+103.601000e+10
Total Current Liabilities1.254810e+111.077540e+111.063850e+111.325070e+11
Short Long Term Debt9.613000e+098.039000e+098.003000e+097.762000e+09
Other Stockholder Equity1.630000e+085.800000e+07-2.860000e+081.790000e+08
Property Plant Equipment4.952700e+103.861500e+103.781500e+103.793300e+10
Total Current Assets1.348360e+111.144230e+111.214650e+111.541060e+11
Long Term Investments1.278770e+111.319480e+111.345390e+111.187450e+11
Net Tangible Assets6.309000e+106.428000e+106.917800e+106.622400e+10
Short Term Investments2.769900e+102.764600e+103.136800e+104.081600e+10
Net Receivables5.150600e+103.390800e+103.303600e+105.862000e+10
Long Term Debt1.091060e+111.057520e+111.086420e+119.928100e+10
Inventory6.580000e+095.178000e+095.219000e+094.973000e+09
Accounts Payable5.476300e+104.040900e+104.012700e+106.384600e+10

年度现金流 - cashflow

只显示最近四个财务统计期

aapl_cashflow = aapl.cashflow

aapl_cashflow

2021-09-252020-09-262019-09-282018-09-29
Investments-2.819000e+095.335000e+095.809300e+103.084500e+10
Change To Liabilities1.400200e+10-1.981000e+09-2.548000e+099.172000e+09
Total Cashflows From Investing Activities-1.454500e+10-4.289000e+094.589600e+101.606600e+10
Net Borrowings1.266500e+102.499000e+09-7.819000e+094.320000e+08
Total Cash From Financing Activities-9.335300e+10-8.682000e+10-9.097600e+10-8.787600e+10
Change To Operating Activities-6.146000e+098.810000e+08-8.960000e+083.001600e+10
Issuance Of Stock1.105000e+098.800000e+087.810000e+086.690000e+08
Net Income9.468000e+105.741100e+105.525600e+105.953100e+10
Change In Cash-3.860000e+09-1.043500e+102.431100e+105.624000e+09
Repurchase Of Stock-9.252700e+10-7.599200e+10-6.971400e+10-7.526500e+10
Total Cash From Operating Activities1.040380e+118.067400e+106.939100e+107.743400e+10
Depreciation1.128400e+101.105600e+101.254700e+101.090300e+10
Other Cashflows From Investing Activities-6.080000e+08-7.910000e+08-1.078000e+09-7.450000e+08
Dividends Paid-1.446700e+10-1.408100e+10-1.411900e+10-1.371200e+10
Change To Inventory-2.642000e+09-1.270000e+08-2.890000e+088.280000e+08
Change To Account Receivables-1.012500e+106.917000e+092.450000e+08-5.322000e+09
Other Cashflows From Financing Activities-1.290000e+08-1.260000e+08-1.050000e+08-1.050000e+08
Change To Netincome2.985000e+096.517000e+095.076000e+09-2.769400e+10
Capital Expenditures-1.108500e+10-7.309000e+09-1.049500e+10-1.331300e+10

季度现金流 - quarterly_cashflow

只显示最近四个财务统计期

aapl_quarterly_cashflow = aapl.quarterly_cashflow

aapl_quarterly_cashflow

2021-09-252021-06-262021-03-272020-12-26
Investments4.608000e+095.747000e+09-7.895000e+09-5.279000e+09
Change To Liabilities1.405000e+103.070000e+08-2.336600e+102.301100e+10
Total Cashflows From Investing Activities8.350000e+083.572000e+09-1.036800e+10-8.584000e+09
Net Borrowings3.220000e+093.220000e+091.042300e+10-9.780000e+08
Total Cash From Financing Activities-2.038200e+10-2.939600e+10-1.132600e+10-3.224900e+10
Change To Operating Activities-5.602000e+09-6.048000e+091.126500e+10-5.761000e+09
Issuance Of Stock5.440000e+085.440000e+085.610000e+085.610000e+08
Net Income2.055100e+102.174400e+102.363000e+102.875500e+10
Change In Cash6.530000e+08-4.730000e+092.287000e+09-2.070000e+09
Repurchase Of Stock-2.044900e+10-2.559500e+10-1.884700e+10-2.763600e+10
Total Cash From Operating Activities2.020000e+102.109400e+102.398100e+103.876300e+10
Depreciation2.989000e+092.832000e+092.797000e+092.666000e+09
Other Cashflows From Investing Activities-5.300000e+08-7.800000e+07-2.040000e+082.040000e+08
Dividends Paid-3.640000e+09-3.767000e+09-3.447000e+09-3.613000e+09
Change To Inventory-1.429000e+091.300000e+07-2.760000e+08-9.500000e+08
Change To Account Receivables-8.809000e+091.031000e+098.598000e+09-1.094500e+10
Other Cashflows From Financing Activities-5.700000e+07-3.400000e+07-1.600000e+07-2.200000e+07
Change To Netincome-1.550000e+091.215000e+091.333000e+091.987000e+09
Capital Expenditures-3.223000e+09-2.093000e+09-2.269000e+09-3.500000e+09

其他信息

证券的ISIN号 - isin

ISIN表征国际证券识别码(英文:International Securities Identification Number,缩写:ISIN),辨别各种证券,是独一无二的编码。相同公司可能在多地上市,不同的证券交易市场会给与不同的股票代码,但是它的ISIN都是一样的。

aapl_isin = aapl.isin

aapl_isin
'US0378331005'

大机构的推荐信息 - recommendations

通过该函数可以获取各大机构在不同时期对该股票做的推荐信息,以下显示最近5个推荐记录。

aapl_recommendations = aapl.recommendations

aapl_recommendations.tail()

FirmTo GradeFrom GradeAction
Date
2021-10-19 12:55:08DA DavidsonBuymain
2021-10-27 13:11:01Morgan StanleyOverweightmain
2021-10-29 10:56:50OppenheimerOutperformmain
2021-10-29 11:16:45BarclaysEqual-Weightmain
2021-10-29 11:41:38Morgan StanleyOverweightmain

后续期权到期时间 - options

以下显示最近5个期权到期时间

aapl_options = aapl.options

aapl.options[:5]
('2021-12-17', '2021-12-23', '2021-12-31', '2022-01-07', '2022-01-14')

相关新闻 - news

以下打印最近的一条新闻

aapl_news = aapl.news

aapl_news[0]
{'uuid': 'e6b5cca0-ce6d-35bf-9d41-b9d2723aa129',
 'title': 'Biden Team Mulls New Clampdown on China’s Largest Chipmaker',
 'publisher': 'Bloomberg',
 'link': 'https://finance.yahoo.com/news/biden-team-considers-clampdown-china-231703320.html',
 'providerPublishTime': 1639556151,
 'type': 'STORY'}

股票分析预测信息 - analysis

可以获取当季,下一季度,下一财年等的分析预测信息,以下打印当季分析信息。

aapl_analysis = aapl.analysis

aapl_analysis.iloc[0]
Max Age                                                   1
End Date                                2021-12-31 00:00:00
Growth                                                0.119
Earnings Estimate Avg                                 1.880
Earnings Estimate Low                                 1.750
Earnings Estimate High                                1.970
Earnings Estimate Year Ago Eps                        1.680
Earnings Estimate Number Of Analysts                 25.000
Earnings Estimate Growth                              0.119
Revenue Estimate Avg                       118137000000.000
Revenue Estimate Low                       111806000000.000
Revenue Estimate High                      121303000000.000
Revenue Estimate Number Of Analysts                  22.000
Revenue Estimate Year Ago Revenue                       NaN
Revenue Estimate Growth                                 NaN
Eps Trend Current                                     1.880
Eps Trend 7Days Ago                                   1.880
Eps Trend 30Days Ago                                  1.880
Eps Trend 60Days Ago                                  1.870
Eps Trend 90Days Ago                                  1.870
Eps Revisions Up Last7Days                            1.000
Eps Revisions Up Last30Days                           2.000
Eps Revisions Down Last30Days                         0.000
Eps Revisions Down Last90Days                           NaN
Name: 0Q, dtype: object

可持续金融信息 - sustainability

可持续金融用来衡量企业追求环境目标,尤其是促进能源转型的金融法规,标准,规范和产品。

aapl.sustainability

Value
2021-9
palmOilFalse
controversialWeaponsFalse
gamblingFalse
socialScore7.99
nuclearFalse
furLeatherFalse
alcoholicFalse
gmoFalse
catholicFalse
socialPercentileNone
peerCount53
governanceScore8.64
environmentPercentileNone
animalTestingFalse
tobaccoFalse
totalEsg16.92
highestControversy3
esgPerformanceUNDER_PERF
coalFalse
pesticidesFalse
adultFalse
percentile13.68
peerGroupTechnology Hardware
smallArmsFalse
environmentScore0.29
governancePercentileNone
militaryContractFalse

Author: wenvenn
Reprint policy: All articles in this blog are used except for special statements CC BY 4.0 reprint policy. If reproduced, please indicate source wenvenn !