파이썬(Python)/웹스크롤링

[Python] yfinance 함수 사용법 정리 (코스피,테슬라)

끄적끄적아무거나 2021. 11. 2. 17:45
반응형

 

목차

     

     

     

     

     

     

     

    [Python] yfinance 함수: 차트 정보 가져오기

     

     

    파이썬 yfinance 함수를 사용해서 야후 파이낸스(Yahoo Finance)의 차트(Chart)의 주가 정보를 가져오겠습니다. (시작가, 종가, etc). yfinance 는 판다스(Pandas)의 Dataframe 함수를 지원합니다. Pandas는 테이블 형식으로 데이터를 정리하여 여러 처리를 쉽게 해주는 라이브러리라고 생각하시면 됩니다. 

     

    yfinance의 return으로 나온 결과 값은 dataframe 형태이므로 추후에 데이터 분석을 할 경우 dataframe의 내부 함수들을 알고 있다면 쉽게 변경 사용할 수 있습니다.

     

     

    코드 실행에 앞서 아래와 같이 라이브러리 설치를 합니다.

     

    pip install pandas_datareader
    pip install yfinance

     

     

    설치 후에도 코드 실행시 아래와 같은 에러메세지가 발생한다면 xx 모듈을 pip install 명령어를 사용하여서 설치하시면 됩니다.

     

    ModuleNotFoundError: No module named '모듈명'

     

    예제 코드에서는 Kospi(코스피) 정보를 가져오겠습니다. 아래 그림처럼 야후 금융에서 Ticker 값을 확인하니 ^KS11 임을 알 수 있었습니다.

     

    코드>>

    from pandas_datareader import data as pdr
    import yfinance as yf
    yf.pdr_override() 
    
    data = pdr.get_data_yahoo("^KS11", start="2020-01-01", end="2021-01-01")
    print(data)

     

    결과>>

    [*********************100%***********************]  1 of 1 completed
                       Open         High          Low        Close    Adj Close   Volume
    Date
    2020-01-02  2201.209961  2202.320068  2171.840088  2175.169922  2175.169922   494700
    2020-01-03  2192.580078  2203.379883  2165.389893  2176.459961  2176.459961   631600
    2020-01-06  2154.969971  2164.419922  2149.949951  2155.070068  2155.070068   592700
    2020-01-07  2166.600098  2181.620117  2164.270020  2175.540039  2175.540039   568200
    2020-01-08  2156.270020  2162.320068  2137.719971  2151.310059  2151.310059   913800
    ...                 ...          ...          ...          ...          ...      ...
    2020-12-23  2737.739990  2769.080078  2716.280029  2759.820068  2759.820068  1121300
    2020-12-24  2762.600098  2812.159912  2762.600098  2806.860107  2806.860107  1030900
    2020-12-28  2820.949951  2834.590088  2799.560059  2808.600098  2808.600098  1006200
    2020-12-29  2810.550049  2823.439941  2792.060059  2820.510010  2820.510010  1046800
    2020-12-30  2820.360107  2878.209961  2809.350098  2873.469971  2873.469971  1074000
    
    [248 rows x 6 columns]

     

    주석>>

    3번 라인 : 의미에 대해서는 별도의 설명은 없지만 차트 값을 불러올 때 필요한 최소한의 로딩으로 보시면 됩니다.

    5번 라인 : 입력값으로 "Ticker(티커명)", start(시작일), end(종료일) 값을 입력하고 해당 범위의 티커 값을 불러 옵니다. 여기서는 2020년 1년간의 데이터를 불러 왔습니다.

    6번 라인 : 데이터 결과량이 많아 head 5줄과 tail 5줄로 표기 됩니다. 만일 전체 결과를 확인하고 싶을 경우 print(data.to_string()) 를 입력하시면 됩니다. 

    반응형

     

     

     

    [Python] yfinance 함수: info함수 회사 요약 정보 불러오기(Tesla)

     

    코드>>

    import yfinance as yf
    
    tlsa_yf = yf.Ticker("TSLA")
    
    tlsa_info = tlsa_yf.info
    print(tlsa_info)

     

    결과>>

    {'zip': '94304', 'sector': 'Consumer Cyclical', 'fullTimeEmployees': 70757, 'longBusinessSummary': 'Tesla, Inc. designs, develops, manufactures, leases, and sells electric vehicles, and energy generation and 
    storage systems in the United States, China, and internationally. The company operates in two segments, Automotive, and Energy Generation and Storage. The Automotive segment offers electric vehicles, as well 
    as sells automotive regulatory credits. It provides sedans and sport utility vehicles through direct and used vehicle sales, a network of Tesla Superchargers, and in-app upgrades; and purchase financing and leasing services. This segment is also involved in the provision of non-warranty after-sales vehicle services, sale of used vehicles, retail merchandise, and vehicle insurance, as well as sale of products through its subsidiaries to third party customers; services for electric vehicles through its company-owned service locations, and Tesla mobile service technicians; and vehicle limited warranties and extended service plans. The Energy Generation and Storage segment engages in the design, manufacture, installation, sale, and leasing of solar energy generation and energy storage products, and related services to residential, commercial, and industrial customers and utilities through its website, stores, and galleries, as well as through a network of channel partners. This segment also offers service and repairs to its energy product customers, including under warranty; and various financing options to its solar customers. The company was formerly known as Tesla Motors, Inc. and changed its name to Tesla, Inc. in February 2017. Tesla, Inc. was founded in 2003 and is headquartered in Palo Alto, California.', 'city': 'Palo Alto', 'phone': '650-681-5000', 'state': 'CA', 'country': 'United States', 'companyOfficers': [], 'website': 'http://www.tesla.com', 'maxAge': 1, 'address1': '3500 Deer Creek Road', 'industry': 'Auto Manufacturers', 'ebitdaMargins': 0.15512, 'profitMargins': 0.07403, 'grossMargins': 0.23107, 'operatingCashflow': 9930999808, 'revenueGrowth': 0.568, 'operatingMargins': 0.09789, 'ebitda': 7266999808, 'targetLowPrice': 67, 'recommendationKey': 'hold', 'grossProfits': 6630000000, 'freeCashflow': 4644624896, 'targetMedianPrice': 855, 'currentPrice': 1114, 'earningsGrowth': 4.333, 'currentRatio': 1.385, 'returnOnAssets': 0.055370003, 'numberOfAnalystOpinions': 36, 'targetMeanPrice': 779.34, 'debtToEquity': 35.65, 'returnOnEquity': 0.15641, 'targetHighPrice': 1300, 'totalCash': 16094999552, 'totalDebt': 10158000128, 'totalRevenue': 46848000000, 'totalCashPerShare': 16.027, 'financialCurrency': 'USD', 'revenuePerShare': 48.272, 'quickRatio': 1.002, 'recommendationMean': 2.6, 'exchange': 'NMS', 'shortName': 'Tesla, Inc.', 'longName': 'Tesla, Inc.', 'exchangeTimezoneName': 'America/New_York', 'exchangeTimezoneShortName': 'EDT', 'isEsgPopulated': False, 'gmtOffSetMilliseconds': '-14400000', 'quoteType': 'EQUITY', 'symbol': 'TSLA', 'messageBoardId': 'finmb_27444752', 'market': 'us_market', 'annualHoldingsTurnover': None, 'enterpriseToRevenue': 23.784, 'beta3Year': None, 'enterpriseToEbitda': 153.331, '52WeekChange': 1.7814536, 'morningStarRiskRating': None, 'forwardEps': 7.91, 'revenueQuarterlyGrowth': None, 'sharesOutstanding': 1004259968, 'fundInceptionDate': None, 'annualReportExpenseRatio': None, 'totalAssets': None, 'bookValue': 26.945, 'sharesShort': 30337020, 'sharesPercentSharesOut': 0.030199999, 'fundFamily': None, 'lastFiscalYearEnd': 1609372800, 'heldPercentInstitutions': 0.41202998, 'netIncomeToCommon': 3468000000, 'trailingEps': 3.062, 'lastDividendValue': None, 'SandP52WeekChange': 0.39125264, 'priceToBook': 41.34348, 'heldPercentInsiders': 0.18979, 'nextFiscalYearEnd': 1672444800, 'yield': None, 'mostRecentQuarter': 1632960000, 'shortRatio': 1.6, 'sharesShortPreviousMonthDate': 1631664000, 'floatShares': 815824595, 'beta': 1.89365, 'enterpriseValue': 1114254999552, 'priceHint': 2, 'threeYearAverageReturn': None, 'lastSplitDate': 1598832000, 'lastSplitFactor': '5:1', 'legalType': None, 'lastDividendDate': None, 'morningStarOverallRating': None, 'earningsQuarterlyGrowth': 3.888, 'priceToSalesTrailing12Months': 23.88033, 'dateShortInterest': 1634256000, 'pegRatio': 2.44, 'ytdReturn': None, 'forwardPE': 140.8344, 'lastCapGain': None, 'shortPercentOfFloat': 0.0372, 'sharesShortPriorMonth': 26999741, 'impliedSharesOutstanding': None, 'category': None, 'fiveYearAverageReturn': None, 'previousClose': 1077.04, 'regularMarketOpen': 1081.86, 'twoHundredDayAverage': 708.0305, 'trailingAnnualDividendYield': None, 'payoutRatio': 0, 'volume24Hr': None, 'regularMarketDayHigh': 1115.13, 'navPrice': None, 'averageDailyVolume10Day': 39294100, 'regularMarketPreviousClose': 1077.04, 'fiftyDayAverage': 830.86743, 'trailingAnnualDividendRate': None, 'open': 1081.86, 'toCurrency': None, 'averageVolume10days': 39294100, 'expireDate': None, 'algorithm': None, 'dividendRate': None, 'exDividendDate': None, 'circulatingSupply': None, 'startDate': None, 'regularMarketDayLow': 1073.205, 'currency': 'USD', 'trailingPE': 363.81448, 'regularMarketVolume': 29918867, 'lastMarket': None, 'maxSupply': None, 'openInterest': None, 'marketCap': 1118745657344, 'volumeAllCurrencies': None, 'strikePrice': None, 'averageVolume': 20309168, 'dayLow': 1073.205, 'ask': 1128.15, 'askSize': 1100, 'volume': 29918867, 'fiftyTwoWeekHigh': 1115.21, 'fromCurrency': None, 'fiveYearAvgDividendYield': None, 'fiftyTwoWeekLow': 392.3, 'bid': 1128, 'tradeable': False, 'dividendYield': None, 'bidSize': 1000, 'dayHigh': 1115.13, 'regularMarketPrice': 1114, 'preMarketPrice': None, 'logo_url': 'https://logo.clearbit.com/tesla.com'}

     

     

    주석>>

    5번 라인: info 내장 함수를 통해 회사의 요약 정보를 가져 올 수 있습니다.

     

     

     

    [Python] yfinance 함수: action함수 회사 배당,분할 정보 불러오기(Tesla)

     

    코드>>

    import yfinance as yf
    
    tlsa_yf = yf.Ticker("TSLA")
    
    tlsa_data = tlsa_yf.actions
    print(tlsa_data)

     

    결과>>

                Dividends  Stock Splits
    Date
    2020-08-31        0.0           5.0

     

    주석>>

    5번 라인: action 함수를 사용해서 회사의 배당(dividends), 주식 분할(Stock splits) 사례가 있으면 불러옵니다. 아래와 같이 각 각 별도로 사용 가능합니다.

     

    import yfinance as yf
    
    tlsa_yf = yf.Ticker("TSLA")
    
    tlsa_data = tlsa_yf.dividends
    print(tlsa_data)
    
    tlsa_data = tlsa_yf.splits
    print(tlsa_data)

     

     

     

     

    [Python] yfinance 함수: financial, major_holder함수 회사 재무제표, 주주정보(Tesla)

     

    코드>>

    import yfinance as yf
    
    tlsa_yf = yf.Ticker("TSLA")
    
    tlsa_data = tlsa_yf.financials
    print(tlsa_data)
    
    print("#############################")
    
    tlsa_data = tlsa_yf.major_holders
    print(tlsa_data)

     

    결과>>

                                               2020-12-31     2019-12-31     2018-12-31     2017-12-31
    Research Development                     1491000000.0   1343000000.0   1460000000.0   1378000000.0
    Effect Of Accounting Charges                     None           None           None           None
    Income Before Tax                        1154000000.0   -665000000.0  -1005000000.0  -2209000000.0
    Minority Interest                        1454000000.0   1492000000.0   1390000000.0   1395080000.0
    Net Income                                721000000.0   -862000000.0   -976000000.0  -1962000000.0
    Selling General Administrative           3188000000.0   2646000000.0   2835000000.0   2477000000.0
    Gross Profit                             6630000000.0   4069000000.0   4042000000.0   2223000000.0
    Ebit                                     1951000000.0     80000000.0   -253000000.0  -1632000000.0
    Operating Income                         1951000000.0     80000000.0   -253000000.0  -1632000000.0
    Other Operating Expenses                         None           None           None           None
    Interest Expense                         -784000000.0   -725000000.0   -653000000.0   -477000000.0
    Extraordinary Items                              None           None           None           None
    Non Recurring                                    None           None           None           None
    Other Items                                      None           None           None           None
    Income Tax Expense                        292000000.0    110000000.0     58000000.0     32000000.0
    Total Revenue                           31536000000.0  24578000000.0  21461000000.0  11759000000.0
    Total Operating Expenses                29585000000.0  24498000000.0  21714000000.0  13391000000.0
    Cost Of Revenue                         24906000000.0  20509000000.0  17419000000.0   9536000000.0
    Total Other Income Expense Net           -797000000.0   -745000000.0   -752000000.0   -577000000.0
    Discontinued Operations                          None           None           None           None
    Net Income From Continuing Ops            862000000.0   -775000000.0  -1063000000.0  -2241000000.0
    Net Income Applicable To Common Shares    690000000.0   -870000000.0   -976000000.0  -1962000000.0
    #############################
            0                                      1
    0  18.98%        % of Shares Held by All Insider
    1  41.20%       % of Shares Held by Institutions
    2  50.85%        % of Float Held by Institutions
    3    2756  Number of Institutions Holding Shares

     

    주석>>

    5번 라인: financial 함수를 사용해서 1년간의 재무제표 수익 구조를 확인할 수 있습니다. 

    10번 라인 : major_holders 함수를 사용해서 주요 주주 정보를 가져 올 수 있습니다.

     

     

    [Python] yfinance 함수: institutional_holders, balance_sheet, cashflow, earnings함수(Tesla)

     

    • institutional_holders : 기업 주주 정보
    • balance_sheet : 대차 대조표
    • cashflow : 현금흐름표
    • earnings : 기업 실적

     

    코드>>

    import yfinance as yf
    
    tlsa_yf = yf.Ticker("TSLA")
    
    tlsa_data = tlsa_yf.institutional_holders
    print(tlsa_data)
    
    print("#############################")
    
    tlsa_data = tlsa_yf.balance_sheet
    print(tlsa_data)
    
    print("#############################")
    
    tlsa_data = tlsa_yf.cashflow
    print(tlsa_data)
    
    print("#############################")
    
    tlsa_data = tlsa_yf.earnings
    print(tlsa_data)

     

    결과>>

                                  Holder    Shares Date Reported   % Out        Value
    0         Vanguard Group, Inc. (The)  58931414    2021-06-29  0.0587  40055682095
    1                     Blackrock Inc.  50452309    2021-06-29  0.0502  34292434427
    2            Capital World Investors  37282565    2021-06-29  0.0371  25340959430
    3           State Street Corporation  29828814    2021-06-29  0.0297  20274644875
    4        Baillie Gifford and Company  13853124    2021-09-29  0.0138  10742820599
    5      Geode Capital Management, LLC  12311100    2021-06-29  0.0123   8367854670
    6            Jennison Associates LLC  10332413    2021-06-29  0.0103   7022941116
    7                           FMR, LLC   9575696    2021-06-29  0.0095   6508600571
    8         Northern Trust Corporation   8166550    2021-06-29  0.0081   5550804035
    9  Norges Bank Investment Management   7790070    2020-12-30  0.0078   5497218696
    #############################
                                 2020-12-31    2019-12-31    2018-12-31    2017-12-31
    Intangible Assets          3.130000e+08  3.390000e+08  2.820000e+08  3.615020e+08
    Capital Surplus            2.726000e+10  1.273600e+10  1.024900e+10  9.178024e+09
    Total Liab                 2.846900e+10  2.619900e+10  2.342700e+10  2.302305e+10
    Total Stockholder Equity   2.222500e+10  6.618000e+09  4.923000e+09  4.237242e+09
    Minority Interest          1.454000e+09  1.492000e+09  1.390000e+09  1.395080e+09
    Other Current Liab         4.147000e+09  3.693000e+09  2.955000e+09  3.098379e+09
    Total Assets               5.214800e+10  3.430900e+10  2.974000e+10  2.865537e+10
    Common Stock               1.000000e+06  1.000000e+06           NaN  1.690000e+05
    Other Current Assets       2.380000e+08  2.460000e+08  1.930000e+08  1.553230e+08
    Retained Earnings         -5.399000e+09 -6.083000e+09 -5.318000e+09 -4.974299e+09
    Other Liab                 3.302000e+09  2.969000e+09  2.318000e+09  4.196294e+09
    Good Will                  2.070000e+08  1.980000e+08  6.800000e+07  6.023700e+07
    Treasury Stock             3.630000e+08 -3.600000e+07 -8.000000e+06  3.334800e+07
    Other Assets               1.536000e+09  1.469000e+09  1.380000e+09  1.166193e+09
    Cash                       1.938400e+10  6.268000e+09  3.686000e+09  3.367914e+09
    Total Current Liabilities  1.424800e+10  1.066700e+10  9.993000e+09  7.674740e+09
    Short Long Term Debt       1.758000e+09  1.399000e+09  2.284000e+09  9.639320e+08
    Other Stockholder Equity   3.630000e+08 -3.600000e+07 -8.000000e+06  3.334800e+07
    Property Plant Equipment   2.337500e+10  2.019900e+10  1.969100e+10  2.049162e+10
    Total Current Assets       2.671700e+10  1.210300e+10  8.307000e+09  6.570520e+09
    Net Tangible Assets        2.170500e+10  6.081000e+09  4.573000e+09  3.815503e+09
    Net Receivables            1.903000e+09  1.324000e+09  9.490000e+08  5.153810e+08
    Long Term Debt             8.571000e+09  1.037500e+10  8.461000e+09  9.486248e+09
    Inventory                  4.101000e+09  3.552000e+09  3.113000e+09  2.263537e+09
    Accounts Payable           6.051000e+09  3.771000e+09  3.405000e+09  2.390250e+09
    Long Term Investments               NaN  1.000000e+06  1.200000e+07  5.304000e+06
    #############################
                                                 2020-12-31    2019-12-31    2018-12-31    2017-12-31
    Change To Liabilities                      2.423000e+09  1.447000e+09  2.203000e+09  8.570000e+08
    Total Cashflows From Investing Activities -3.132000e+09 -1.436000e+09 -2.337000e+09 -4.196000e+09
    Net Borrowings                            -2.488000e+09  7.980000e+08  8.900000e+07  3.385000e+09
    Total Cash From Financing Activities       9.973000e+09  1.529000e+09  5.740000e+08  4.415000e+09
    Change To Operating Activities            -1.165000e+09 -1.000000e+09 -6.250000e+08 -1.150000e+09
    Issuance Of Stock                          1.268600e+10  1.111000e+09  2.960000e+08  6.590000e+08
    Net Income                                 7.210000e+08 -8.620000e+08 -9.760000e+08 -1.962000e+09
    Change In Cash                             1.311800e+10  2.506000e+09  3.120000e+08  1.980000e+08
    Effect Of Exchange Rate                    3.340000e+08  8.000000e+06 -2.300000e+07  4.000000e+07
    Total Cash From Operating Activities       5.943000e+09  2.405000e+09  2.098000e+09 -6.100000e+07
    Depreciation                               2.322000e+09  2.092000e+09  1.888000e+09  1.636000e+09
    Other Cashflows From Investing Activities  1.230000e+08  4.600000e+07  4.600000e+07  4.600000e+07
    Change To Inventory                       -4.220000e+08 -4.290000e+08 -1.023000e+09 -1.790000e+08
    Change To Account Receivables             -6.520000e+08 -3.670000e+08 -4.970000e+08 -2.500000e+07
    Other Cashflows From Financing Activities -2.250000e+08 -3.800000e+08  1.890000e+08  3.710000e+08
    Change To Netincome                        2.536000e+09  1.336000e+09  9.690000e+08  6.710000e+08
    Capital Expenditures                      -3.232000e+09 -1.432000e+09 -2.319000e+09 -4.081000e+09
    #############################
              Revenue    Earnings
    Year
    2017  11759000000 -1962000000
    2018  21461000000  -976000000
    2019  24578000000  -862000000
    2020  31536000000   721000000

     

     

     

    [Python] yfinance 함수: 특정 값 불러오고 수정하기

     

     

    코드>>

    import yfinance as yf
    
    tlsa_yf = yf.Ticker("TSLA")
    
    tlsa_data = tlsa_yf.institutional_holders
    print(type(tlsa_data))
    print(tlsa_data)
    tlsa_data["Shares"][0] = 77777
    print(tlsa_data)

     

    결과>>

    <class 'pandas.core.frame.DataFrame'>
                                  Holder    Shares Date Reported   % Out        Value
    0         Vanguard Group, Inc. (The)  58931414    2021-06-29  0.0587  40055682095
    1                     Blackrock Inc.  50452309    2021-06-29  0.0502  34292434427
    2            Capital World Investors  37282565    2021-06-29  0.0371  25340959430
    3           State Street Corporation  29828814    2021-06-29  0.0297  20274644875
    4        Baillie Gifford and Company  13853124    2021-09-29  0.0138  10742820599
    5      Geode Capital Management, LLC  12311100    2021-06-29  0.0123   8367854670
    6            Jennison Associates LLC  10332413    2021-06-29  0.0103   7022941116
    7                           FMR, LLC   9575696    2021-06-29  0.0095   6508600571
    8         Northern Trust Corporation   8166550    2021-06-29  0.0081   5550804035
    9  Norges Bank Investment Management   7790070    2020-12-30  0.0078   5497218696
    c:\Users\forgo\Documents\python_ex\py_test\vix_analyzer.py:8: SettingWithCopyWarning:
    A value is trying to be set on a copy of a slice from a DataFrame
    
    See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
      tlsa_data["Shares"][0] = 77777
                                  Holder    Shares Date Reported   % Out        Value
    0         Vanguard Group, Inc. (The)     77777    2021-06-29  0.0587  40055682095
    1                     Blackrock Inc.  50452309    2021-06-29  0.0502  34292434427
    2            Capital World Investors  37282565    2021-06-29  0.0371  25340959430
    3           State Street Corporation  29828814    2021-06-29  0.0297  20274644875
    4        Baillie Gifford and Company  13853124    2021-09-29  0.0138  10742820599
    5      Geode Capital Management, LLC  12311100    2021-06-29  0.0123   8367854670
    6            Jennison Associates LLC  10332413    2021-06-29  0.0103   7022941116
    7                           FMR, LLC   9575696    2021-06-29  0.0095   6508600571
    8         Northern Trust Corporation   8166550    2021-06-29  0.0081   5550804035
    9  Norges Bank Investment Management   7790070    2020-12-30  0.0078   5497218696

     

    주석>>

    6번 라인 : 결과 type을 확인하였습니다. 판다스(Pandas) Dataframe임을 알 수 있습니다.

    Dataframe 사용에 대해 궁금하시면 아래 링크를 참조하시면 됩니다. 

    https://scribblinganything.tistory.com/371

     

    [Python] Pandas DataFrames이란? 선언, 데이터 찾기, 정렬하기 예제

    목차 [Python] Pandas DataFrames이란? 파이썬의 판다스는 데이터 처리에 용이한 라이브러리 입니다. 앞서 설명한 Pandas Series와 마찬가지로 DataFrames은 데이터를 엑셀과 비슷한 방식으로 관리하기 위해

    scribblinganything.tistory.com

     

    8번 라인: 행과 열의 값을 테이블 형식으로 입력하면 값을 불러오거나 수정할 수 있습니다.

     

     

    반응형