keilab

파이썬으로 미국 주식 정보 가져오기(야후 파이낸스 api) 본문

Python

파이썬으로 미국 주식 정보 가져오기(야후 파이낸스 api)

datapy 2022. 10. 3. 21:01

파이썬으로 미국 주식 정보를 가져와보겠습니다.

야후 파이낸스(yahoo finance)에서 제공하는 API를 사용하여 어떤 정보를 가져올 수 있는지 살펴보겠습니다.

 

준비

yahoo finance API를 사용하기 위해 라이브러리를 설치합니다.

pip install yfinance

코드

yfinance 라이브러리를  import 합니다.

result 변수에 애플(apple) 회사의 주식 티커  'AAPL'을 넣어 어떤 정보를 제공하는지 출력해보겠습니다.

import yfinance as yf

result=yf.Ticker('AAPL')
print(result.info)

실행결과

아래와 같이 dictionary 형태로 여러 정보를 제공하고 있습니다.

이 중 자신에게 필요한 key값만 선택하면 한눈에 필요한 정보만 추출할 수 있겠네요

{'zip': '95014',
 'sector': 'Technology',
 'fullTimeEmployees': 154000,
 'longBusinessSummary': 'Apple Inc. designs, manufactures, and markets smartphones, personal computers, tablets, wearables, and accessories worldwide. It also sells various related services. In addition, the company offers iPhone, a line of smartphones; Mac, a line of personal computers; iPad, a line of multi-purpose tablets; AirPods Max, an over-ear wireless headphone; and wearables, home, and accessories comprising AirPods, Apple TV, Apple Watch, Beats products, HomePod, and iPod touch. Further, it provides AppleCare support services; cloud services store services; and operates various platforms, including the App Store that allow customers to discover and download applications and digital content, such as books, music, video, games, and podcasts. Additionally, the company offers various services, such as Apple Arcade, a game subscription service; Apple Music, which offers users a curated listening experience with on-demand radio stations; Apple News+, a subscription news and magazine service; Apple TV+, which offers exclusive original content; Apple Card, a co-branded credit card; and Apple Pay, a cashless payment service, as well as licenses its intellectual property. The company serves consumers, and small and mid-sized businesses; and the education, enterprise, and government markets. It distributes third-party applications for its products through the App Store. The company also sells its products through its retail and online stores, and direct sales force; and third-party cellular network carriers, wholesalers, retailers, and resellers. Apple Inc. was incorporated in 1977 and is headquartered in Cupertino, California.',
 'city': 'Cupertino',
 'phone': '408 996 1010',
 'state': 'CA',
 'country': 'United States',
 'companyOfficers': [],
 'website': 'https://www.apple.com',
 'maxAge': 1,
 'address1': 'One Apple Park Way',
 'industry': 'Consumer Electronics',
 'ebitdaMargins': 0.3343,
 'profitMargins': 0.25709,
 'grossMargins': 0.43313998,
 'operatingCashflow': 118224003072,
 'revenueGrowth': 0.019,
 'operatingMargins': 0.30533,
 'ebitda': 129556996096,
 'targetLowPrice': 130,
 'recommendationKey': 'buy',
 'grossProfits': 152836000000,
 'freeCashflow': 83344621568,
 'targetMedianPrice': 185,
 'currentPrice': 138.2,
 'earningsGrowth': -0.077,
 'currentRatio': 0.865,
 'returnOnAssets': 0.22204,
 'numberOfAnalystOpinions': 41,
 'targetMeanPrice': 183.5,
 'debtToEquity': 205.984,
 'returnOnEquity': 1.62816,
 'targetHighPrice': 220,
 'totalCash': 48230998016,
 'totalDebt': 119691001856,
 'totalRevenue': 387541991424,
 'totalCashPerShare': 3.001,
 'financialCurrency': 'USD',
 'revenuePerShare': 23.732,
 'quickRatio': 0.697,
 'recommendationMean': 1.9,
 'exchange': 'NMS',
 'shortName': 'Apple Inc.',
 'longName': 'Apple Inc.',
 'exchangeTimezoneName': 'America/New_York',
 'exchangeTimezoneShortName': 'EDT',
 'isEsgPopulated': False,
 'gmtOffSetMilliseconds': '-14400000',
 'quoteType': 'EQUITY',
 'symbol': 'AAPL',
 'messageBoardId': 'finmb_24937',
 'market': 'us_market',
 'annualHoldingsTurnover': None,
 'enterpriseToRevenue': 5.915,
 'beta3Year': None,
 'enterpriseToEbitda': 17.694,
 '52WeekChange': -0.0067557693,
 'morningStarRiskRating': None,
 'forwardEps': 6.46,
 'revenueQuarterlyGrowth': None,
 'sharesOutstanding': 16070800384,
 'fundInceptionDate': None,
 'annualReportExpenseRatio': None,
 'totalAssets': None,
 'bookValue': 3.61,
 'sharesShort': 116076947,
 'sharesPercentSharesOut': 0.0072000003,
 'fundFamily': None,
 'lastFiscalYearEnd': 1632528000,
 'heldPercentInstitutions': 0.59604,
 'netIncomeToCommon': 99632996352,
 'trailingEps': 6.05,
 'lastDividendValue': 0.23,
 'SandP52WeekChange': -0.16622406,
 'priceToBook': 38.282547,
 'heldPercentInsiders': 0.0007,
 'nextFiscalYearEnd': 1695600000,
 'yield': None,
 'mostRecentQuarter': 1656115200,
 'shortRatio': 1.53,
 'sharesShortPreviousMonthDate': 1660521600,
 'floatShares': 16052270635,
 'beta': 1.234119,
 'enterpriseValue': 2292438007808,
 'priceHint': 2,
 'threeYearAverageReturn': None,
 'lastSplitDate': 1598832000,
 'lastSplitFactor': '4:1',
 'legalType': None,
 'lastDividendDate': 1659657600,
 'morningStarOverallRating': None,
 'earningsQuarterlyGrowth': -0.106,
 'priceToSalesTrailing12Months': 5.7309523,
 'dateShortInterest': 1663200000,
 'pegRatio': 2.39,
 'ytdReturn': None,
 'forwardPE': 21.393188,
 'lastCapGain': None,
 'shortPercentOfFloat': 0.0072000003,
 'sharesShortPriorMonth': 115400891,
 'impliedSharesOutstanding': 0,
 'category': None,
 'fiveYearAverageReturn': None,
 'previousClose': 142.48,
 'regularMarketOpen': 141.28,
 'twoHundredDayAverage': 159.86165,
 'trailingAnnualDividendYield': 0.006246491,
 'payoutRatio': 0.1471,
 'volume24Hr': None,
 'regularMarketDayHigh': 143.1,
 'navPrice': None,
 'averageDailyVolume10Day': 105076960,
 'regularMarketPreviousClose': 142.48,
 'fiftyDayAverage': 159.7342,
 'trailingAnnualDividendRate': 0.89,
 'open': 141.28,
 'toCurrency': None,
 'averageVolume10days': 105076960,
 'expireDate': None,
 'algorithm': None,
 'dividendRate': 0.92,
 'exDividendDate': 1659657600,
 'circulatingSupply': None,
 'startDate': None,
 'regularMarketDayLow': 138,
 'currency': 'USD',
 'trailingPE': 22.842974,
 'regularMarketVolume': 124925274,
 'lastMarket': None,
 'maxSupply': None,
 'openInterest': None,
 'marketCap': 2220984631296,
 'volumeAllCurrencies': None,
 'strikePrice': None,
 'averageVolume': 78897638,
 'dayLow': 138,
 'ask': 0,
 'askSize': 1000,
 'volume': 124925274,
 'fiftyTwoWeekHigh': 182.94,
 'fromCurrency': None,
 'fiveYearAvgDividendYield': 1.02,
 'fiftyTwoWeekLow': 129.04,
 'bid': 0,
 'tradeable': False,
 'dividendYield': 0.0067000003,
 'bidSize': 1100,
 'dayHigh': 143.1,
 'coinMarketCapLink': None,
 'regularMarketPrice': 138.2,
 'preMarketPrice': 137.59,
 'logo_url': 'https://logo.clearbit.com/apple.com',
 'trailingPegRatio': 2.4734}

 

이번에는 2022년 1월 1일부터의 애플 주가 정보를 가져와보겠습니다.

코드

import yfinance as yf

result=yf.download('AAPL',start = '2022-01-01')
print(result)

결과

날짜별로 Open(시가), High(고가), Low(저가), Close(종가), Adj Close(조정 종가), Volume(거래량) 정보를 제공합니다.