1. Python 라이브러리¶
- pip : Python 패키지 매니저. 앱스토어와 비슷한 역할입니다.
pip install LIBRARY_NAME
명령어를 통해 설치가 가능합니다.
- yfinance : https://github.com/ranaroussi/yfinance?tab=readme-ov-file
- Yahoo Finance API wrapper 라이브러리를 예시로 활용해보겠습니다.
pip install -U yfinance
In [ ]:
Copied!
# install yfinance library
%pip install -U yfinance
# install yfinance library
%pip install -U yfinance
In [2]:
Copied!
import yfinance as yf
# Fetch historical data for a specific stock
data = yf.download("AAPL", start="2023-01-01", end="2023-12-31")
data.head() # View the first few rows
import yfinance as yf
# Fetch historical data for a specific stock
data = yf.download("AAPL", start="2023-01-01", end="2023-12-31")
data.head() # View the first few rows
[*********************100%***********************] 1 of 1 completed
Price Close High Low Open Volume Ticker AAPL AAPL AAPL AAPL AAPL Date 2023-01-03 123.768456 129.537780 122.877820 128.924237 112117500 2023-01-04 125.045036 127.321104 123.778358 125.569520 89113600 2023-01-05 123.718979 126.440361 123.461690 125.807022 80962700 2023-01-06 128.271103 128.934129 123.590330 124.698677 87754700 2023-01-09 128.795578 132.021662 128.538289 129.112255 70790800
In [6]:
Copied!
# Create a Ticker object
ticker = yf.Ticker("AAPL")
# Get stock info
info = ticker.info
print(info)
# Historical market data
hist = ticker.history(period="1mo") # Data for the last 1 month
hist
# Create a Ticker object
ticker = yf.Ticker("AAPL")
# Get stock info
info = ticker.info
print(info)
# Historical market data
hist = ticker.history(period="1mo") # Data for the last 1 month
hist
{'address1': 'One Apple Park Way', 'city': 'Cupertino', 'state': 'CA', 'zip': '95014', 'country': 'United States', 'phone': '(408) 996-1010', 'website': 'https://www.apple.com', 'industry': 'Consumer Electronics', 'industryKey': 'consumer-electronics', 'industryDisp': 'Consumer Electronics', 'sector': 'Technology', 'sectorKey': 'technology', 'sectorDisp': 'Technology', 'longBusinessSummary': 'Apple Inc. designs, manufactures, and markets smartphones, personal computers, tablets, wearables, and accessories worldwide. The company offers iPhone, a line of smartphones; Mac, a line of personal computers; iPad, a line of multi-purpose tablets; and wearables, home, and accessories comprising AirPods, Apple TV, Apple Watch, Beats products, and HomePod. It also provides AppleCare support and cloud 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, as well as advertising services include third-party licensing arrangements and its own advertising platforms. In addition, the company offers various subscription-based services, such as Apple Arcade, a game subscription service; Apple Fitness+, a personalized fitness 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 founded in 1976 and is headquartered in Cupertino, California.', 'fullTimeEmployees': 164000, 'companyOfficers': [{'maxAge': 1, 'name': 'Mr. Timothy D. Cook', 'age': 62, 'title': 'CEO & Director', 'yearBorn': 1961, 'fiscalYear': 2023, 'totalPay': 16239562, 'exercisedValue': 0, 'unexercisedValue': 0}, {'maxAge': 1, 'name': 'Mr. Luca Maestri', 'age': 60, 'title': 'CFO & Senior VP', 'yearBorn': 1963, 'fiscalYear': 2023, 'totalPay': 4612242, 'exercisedValue': 0, 'unexercisedValue': 0}, {'maxAge': 1, 'name': 'Mr. Jeffrey E. Williams', 'age': 59, 'title': 'Chief Operating Officer', 'yearBorn': 1964, 'fiscalYear': 2023, 'totalPay': 4637585, 'exercisedValue': 0, 'unexercisedValue': 0}, {'maxAge': 1, 'name': 'Ms. Katherine L. Adams', 'age': 59, 'title': 'Senior VP, General Counsel & Secretary', 'yearBorn': 1964, 'fiscalYear': 2023, 'totalPay': 4618064, 'exercisedValue': 0, 'unexercisedValue': 0}, {'maxAge': 1, 'name': "Ms. Deirdre O'Brien", 'age': 56, 'title': 'Chief People Officer & Senior VP of Retail', 'yearBorn': 1967, 'fiscalYear': 2023, 'totalPay': 4613369, 'exercisedValue': 0, 'unexercisedValue': 0}, {'maxAge': 1, 'name': 'Mr. Chris Kondo', 'title': 'Senior Director of Corporate Accounting', 'fiscalYear': 2023, 'exercisedValue': 0, 'unexercisedValue': 0}, {'maxAge': 1, 'name': 'Suhasini Chandramouli', 'title': 'Director of Investor Relations', 'fiscalYear': 2023, 'exercisedValue': 0, 'unexercisedValue': 0}, {'maxAge': 1, 'name': 'Mr. Greg Joswiak', 'title': 'Senior Vice President of Worldwide Marketing', 'fiscalYear': 2023, 'exercisedValue': 0, 'unexercisedValue': 0}, {'maxAge': 1, 'name': 'Mr. Adrian Perica', 'age': 49, 'title': 'Head of Corporate Development', 'yearBorn': 1974, 'fiscalYear': 2023, 'exercisedValue': 0, 'unexercisedValue': 0}, {'maxAge': 1, 'name': 'Mr. Michael Fenger', 'title': 'VP of Worldwide Sales', 'fiscalYear': 2023, 'exercisedValue': 0, 'unexercisedValue': 0}], 'auditRisk': 6, 'boardRisk': 1, 'compensationRisk': 2, 'shareHolderRightsRisk': 1, 'overallRisk': 1, 'governanceEpochDate': 1733011200, 'compensationAsOfEpochDate': 1703980800, 'irWebsite': 'http://investor.apple.com/', 'maxAge': 86400, 'priceHint': 2, 'previousClose': 255.27, 'open': 255.37, 'dayLow': 255.31, 'dayHigh': 258.21, 'regularMarketPreviousClose': 255.27, 'regularMarketOpen': 255.37, 'regularMarketDayLow': 255.31, 'regularMarketDayHigh': 258.21, 'dividendRate': 1.0, 'dividendYield': 0.0039, 'exDividendDate': 1731024000, 'payoutRatio': 0.1612, 'fiveYearAvgDividendYield': 0.62, 'beta': 1.24, 'trailingPE': 42.537067, 'forwardPE': 31.076347, 'volume': 20965006, 'regularMarketVolume': 20965006, 'averageVolume': 44261774, 'averageVolume10days': 54343500, 'averageDailyVolume10Day': 54343500, 'bid': 258.01, 'ask': 268.27, 'bidSize': 200, 'askSize': 100, 'marketCap': 3902899748864, 'fiftyTwoWeekLow': 164.08, 'fiftyTwoWeekHigh': 258.21, 'priceToSalesTrailing12Months': 9.9809475, 'fiftyDayAverage': 235.914, 'twoHundredDayAverage': 211.7723, 'trailingAnnualDividendRate': 0.98, 'trailingAnnualDividendYield': 0.0038390723, 'currency': 'USD', 'enterpriseValue': 3900713730048, 'profitMargins': 0.23971, 'floatShares': 15091184209, 'sharesOutstanding': 15115799552, 'sharesShort': 154104746, 'sharesShortPriorMonth': 133040194, 'sharesShortPreviousMonthDate': 1730332800, 'dateShortInterest': 1732838400, 'sharesPercentSharesOut': 0.010199999, 'heldPercentInsiders': 0.02056, 'heldPercentInstitutions': 0.61926, 'shortRatio': 3.41, 'shortPercentOfFloat': 0.010199999, 'impliedSharesOutstanding': 15332100096, 'bookValue': 3.767, 'priceToBook': 68.54261, 'lastFiscalYearEnd': 1727481600, 'nextFiscalYearEnd': 1759017600, 'mostRecentQuarter': 1727481600, 'earningsQuarterlyGrowth': -0.358, 'netIncomeToCommon': 93736001536, 'trailingEps': 6.07, 'forwardEps': 8.31, 'lastSplitFactor': '4:1', 'lastSplitDate': 1598832000, 'enterpriseToRevenue': 9.975, 'enterpriseToEbitda': 28.967, '52WeekChange': 0.33381546, 'SandP52WeekChange': 0.26272178, 'lastDividendValue': 0.25, 'lastDividendDate': 1731024000, 'exchange': 'NMS', 'quoteType': 'EQUITY', 'symbol': 'AAPL', 'underlyingSymbol': 'AAPL', 'shortName': 'Apple Inc.', 'longName': 'Apple Inc.', 'firstTradeDateEpochUtc': 345479400, 'timeZoneFullName': 'America/New_York', 'timeZoneShortName': 'EST', 'uuid': '8b10e4ae-9eeb-3684-921a-9ab27e4d87aa', 'messageBoardId': 'finmb_24937', 'gmtOffSetMilliseconds': -18000000, 'currentPrice': 258.2, 'targetHighPrice': 300.0, 'targetLowPrice': 184.0, 'targetMeanPrice': 246.25833, 'targetMedianPrice': 250.0, 'recommendationMean': 1.89362, 'recommendationKey': 'buy', 'numberOfAnalystOpinions': 42, 'totalCash': 65171001344, 'totalCashPerShare': 4.311, 'ebitda': 134660997120, 'totalDebt': 119058997248, 'quickRatio': 0.745, 'currentRatio': 0.867, 'totalRevenue': 391034994688, 'debtToEquity': 209.059, 'revenuePerShare': 25.485, 'returnOnAssets': 0.21464, 'returnOnEquity': 1.5741299, 'freeCashflow': 110846001152, 'operatingCashflow': 118254002176, 'earningsGrowth': -0.341, 'revenueGrowth': 0.061, 'grossMargins': 0.46206, 'ebitdaMargins': 0.34437, 'operatingMargins': 0.31171, 'financialCurrency': 'USD', 'trailingPegRatio': 2.3608}
Out[6]:
| Open | High | Low | Close | Volume | Dividends | Stock Splits | |
|---|---|---|---|---|---|---|---|
| Date | |||||||
| 2024-11-25 00:00:00-05:00 | 231.460007 | 233.250000 | 229.740005 | 232.869995 | 90152800 | 0.0 | 0.0 |
| 2024-11-26 00:00:00-05:00 | 233.330002 | 235.570007 | 233.330002 | 235.059998 | 45986200 | 0.0 | 0.0 |
| 2024-11-27 00:00:00-05:00 | 234.470001 | 235.690002 | 233.809998 | 234.929993 | 33498400 | 0.0 | 0.0 |
| 2024-11-29 00:00:00-05:00 | 234.809998 | 237.809998 | 233.970001 | 237.330002 | 28481400 | 0.0 | 0.0 |
| 2024-12-02 00:00:00-05:00 | 237.270004 | 240.789993 | 237.160004 | 239.589996 | 48137100 | 0.0 | 0.0 |
| 2024-12-03 00:00:00-05:00 | 239.809998 | 242.759995 | 238.899994 | 242.649994 | 38861000 | 0.0 | 0.0 |
| 2024-12-04 00:00:00-05:00 | 242.869995 | 244.110001 | 241.250000 | 243.009995 | 44383900 | 0.0 | 0.0 |
| 2024-12-05 00:00:00-05:00 | 243.990005 | 244.539993 | 242.130005 | 243.039993 | 40033900 | 0.0 | 0.0 |
| 2024-12-06 00:00:00-05:00 | 242.910004 | 244.630005 | 242.080002 | 242.839996 | 36870600 | 0.0 | 0.0 |
| 2024-12-09 00:00:00-05:00 | 241.830002 | 247.240005 | 241.750000 | 246.750000 | 44649200 | 0.0 | 0.0 |
| 2024-12-10 00:00:00-05:00 | 246.889999 | 248.210007 | 245.339996 | 247.770004 | 36914800 | 0.0 | 0.0 |
| 2024-12-11 00:00:00-05:00 | 247.960007 | 250.800003 | 246.259995 | 246.490005 | 45205800 | 0.0 | 0.0 |
| 2024-12-12 00:00:00-05:00 | 246.889999 | 248.740005 | 245.679993 | 247.960007 | 32777500 | 0.0 | 0.0 |
| 2024-12-13 00:00:00-05:00 | 247.820007 | 249.289993 | 246.240005 | 248.130005 | 33155300 | 0.0 | 0.0 |
| 2024-12-16 00:00:00-05:00 | 247.990005 | 251.380005 | 247.649994 | 251.039993 | 51694800 | 0.0 | 0.0 |
| 2024-12-17 00:00:00-05:00 | 250.080002 | 253.830002 | 249.779999 | 253.479996 | 51356400 | 0.0 | 0.0 |
| 2024-12-18 00:00:00-05:00 | 252.160004 | 254.279999 | 247.740005 | 248.050003 | 56774100 | 0.0 | 0.0 |
| 2024-12-19 00:00:00-05:00 | 247.500000 | 252.000000 | 247.089996 | 249.789993 | 60882300 | 0.0 | 0.0 |
| 2024-12-20 00:00:00-05:00 | 248.039993 | 255.000000 | 245.690002 | 254.490005 | 147495300 | 0.0 | 0.0 |
| 2024-12-23 00:00:00-05:00 | 254.770004 | 255.649994 | 253.449997 | 255.270004 | 40858800 | 0.0 | 0.0 |
| 2024-12-24 00:00:00-05:00 | 255.490005 | 258.209991 | 255.289993 | 258.200012 | 23234700 | 0.0 | 0.0 |
In [12]:
Copied!
# Fetch data for multiple stocks
data = yf.download(["AAPL", "GOOGL", "MSFT"], start="2023-01-01", end="2023-12-31")
data.head()
# Fetch data for multiple stocks
data = yf.download(["AAPL", "GOOGL", "MSFT"], start="2023-01-01", end="2023-12-31")
data.head()
[*********************100%***********************] 3 of 3 completed
Out[12]:
| Price | Close | High | Low | Open | Volume | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Ticker | AAPL | GOOGL | MSFT | AAPL | GOOGL | MSFT | AAPL | GOOGL | MSFT | AAPL | GOOGL | MSFT | AAPL | GOOGL | MSFT |
| Date | |||||||||||||||
| 2023-01-03 | 123.768456 | 88.798103 | 236.183517 | 129.537780 | 90.721133 | 242.266045 | 122.877820 | 88.200264 | 234.034415 | 128.924237 | 89.266399 | 239.633899 | 112117500 | 28131200 | 25740000 |
| 2023-01-04 | 125.045036 | 87.761856 | 225.852081 | 127.321104 | 90.322573 | 229.568624 | 123.778358 | 86.954777 | 222.756597 | 125.569520 | 90.023653 | 228.986992 | 89113600 | 34854800 | 50623400 |
| 2023-01-05 | 123.718979 | 85.888649 | 219.158356 | 126.440361 | 87.253703 | 224.324075 | 123.461690 | 85.589737 | 218.616150 | 125.807022 | 87.154066 | 223.979031 | 80962700 | 27194400 | 39585600 |
| 2023-01-06 | 128.271103 | 87.024529 | 221.741226 | 128.934129 | 87.373270 | 222.559461 | 123.590330 | 84.553490 | 216.240345 | 124.698677 | 86.476520 | 219.838594 | 87754700 | 41381500 | 43613600 |
| 2023-01-09 | 128.795578 | 87.702065 | 223.900162 | 132.021662 | 89.724738 | 227.961764 | 128.538289 | 87.542646 | 223.200236 | 129.112255 | 88.040840 | 223.239662 | 70790800 | 29003900 | 27369800 |
In [10]:
Copied!
# Get the latest market price
latest_price = ticker.history(period="1d")['Close'][-1]
print(f"Latest Close Price: {latest_price}")
# Get the latest market price
latest_price = ticker.history(period="1d")['Close'][-1]
print(f"Latest Close Price: {latest_price}")
Latest Close Price: 258.20001220703125
/var/folders/kx/c6xk17ln6blbs7f3nf_p1str0000gn/T/ipykernel_7776/404107778.py:2: FutureWarning: Series.__getitem__ treating keys as positions is deprecated. In a future version, integer keys will always be treated as labels (consistent with DataFrame behavior). To access a value by position, use `ser.iloc[pos]` latest_price = ticker.history(period="1d")['Close'][-1]
In [11]:
Copied!
# Fetch historical data for a specific stock
data = yf.download("AAPL", start="2023-01-01", end="2023-12-31")
# Save to CSV
data.to_csv("AAPL_data.csv")
print("Data saved to AAPL_data.csv")
# Fetch historical data for a specific stock
data = yf.download("AAPL", start="2023-01-01", end="2023-12-31")
# Save to CSV
data.to_csv("AAPL_data.csv")
print("Data saved to AAPL_data.csv")
[*********************100%***********************] 1 of 1 completed
Data saved to AAPL_data.csv