필자는 재테크에는 재능이 없습니다. 주식 투자도 하지 않습니다. 그러나 최근에는 동학개미, 서학개미라는 사회 이슈적인 신조어를 심심치 않게 듣습니다. 2017년도 금융 데이터 수집을 위해서 국내외 데이터 수집을 위한 프토토타입을 만든 적이 있습니다. 그 때의 기억을 소환해서 서학개미가 관심있을 미국 주식 데이터를 수집하는 방법을 다룹니다.
2017년도 금융관련 데이터를 수집하기 위해서 R을 이용한 Finance Analysis
를 소책자를 pdf 문서로 만든 적이 있습니다. 회사의 리소스(일정 부분을 회사의 업무 시간에 수행해서)를 사용한 문서라 공유할 수는 없습니다만…
오늘 리마인드를 해보니 5년의 시간이 여러 이슈를 만들었습니다. 종목코드(symbols)를 가져오는 TTR 패키지의 stockSymbols() 함수가 이전과 다르게 동작하였고, 원천 데이터 소스인 API에서 제공하는 정보의 제한으로 가져오는 정보도 종목코드 외에는 거의 없었습니다.
Nasdaq 거래소의 https://api.nasdaq.com 사이트에서 다음 미국 주식 시장에 상장된 회사의 종목코드를 크롤링니다.
library(dplyr)
symbol_usa <- c("NYSE", "NASDAQ", "AMEX") %>%
purrr::map_df(
function(x) {
url <- "https://api.nasdaq.com/api/screener/stocks"
glue::glue("{url}?tableonly=true&limit=25&offset=0&exchange={x}&download=true") %>%
jsonlite::fromJSON() %>%
"$"(data) %>%
"$"(rows) %>%
bind_cols(exchange = x)
}
)
주식 거래는 하지 않지만, 뉴욕 증권거래소 앞에서 뉴욕 방문 기념으로 한 컷 남긴 사진이 있습니다.
가져온 3대 거래소의 종목코드 정보는 다음과 같습니다. NASDAQ에 약 60%가 상장되어 있습니다.
symbol_usa %>%
group_by(exchange) %>%
tally() %>%
mutate(pct = n /sum(n) * 100) %>%
rename(
"거래소" = exchange,
"종목수" = n,
"비율(%)" = pct
) %>%
kableExtra::kable(digits = 2, format.args = list(big.mark = ",", scientific = FALSE)) %>%
kableExtra::kable_styling(bootstrap_options = c("striped", "hover"))
거래소 | 종목수 | 비율(%) |
---|---|---|
AMEX | 279 | 3.42 |
NASDAQ | 4,745 | 58.09 |
NYSE | 3,144 | 38.49 |
미국 증권시장에 11개 한국 기업이 상장되어 있습니다. 포스코, SK텔레콤, KT, 한국전력공사, LG디스플레이, KB금융그룹, 산한금융그룹, 우리금융그룹과 게임회사인 그라비티, 더블다운인터렛티브, 쿠팡입니다. 쿠팡의 경우는 쿠팡의 지분 100%를 가진 모기업 쿠팡 LLC
인 미국회사가 상장되어 있습니다.
symbol_usa %>%
filter(stringr::str_detect(country, "Korea")) %>%
bind_rows(
symbol_usa %>%
filter(stringr::str_detect(name, "Coupang Inc"))
)
symbol
1 KB
2 KEP
3 KT
4 LPL
5 PKX
6 SHG
7 SKM
8 WF
9 DDI
10 GRVY
11 CPNG
name
1 KB Financial Group Inc
2 Korea Electric Power Corporation Common Stock
3 KT Corporation Common Stock
4 LG Display Co Ltd AMERICAN DEPOSITORY SHARES
5 POSCO Holdings Inc. American Depositary Shares (Each representing 1/4th of a share of Common Stock)
6 Shinhan Financial Group Co Ltd American Depositary Shares
7 SK Telecom Co. Ltd. Common Stock
8 Woori Financial Group Inc. American Depositary Shares (each representing three (3) shares of Common Stock)
9 DoubleDown Interactive Co. Ltd. American Depository Shares
10 GRAVITY Co. Ltd. American Depository Shares
11 Coupang Inc. Class A Common Stock
lastsale netchange pctchange volume marketCap country
1 $48.07 -0.31 -0.641% 226861 18729722483.00 South Korea
2 $8.49 -0.16 -1.85% 82695 10900550027.00 South Korea
3 $14.33 -0.14 -0.968% 937310 6758261464.00 South Korea
4 $7.25 -0.01 -0.138% 474246 5188327650.00 South Korea
5 $57.45 -1.09 -1.862% 213956 18114982102.00 South Korea
6 $33.11 0.01 0.03% 104582 16979510462.00 South Korea
7 $27.10 -0.32 -1.167% 478161 10644822846.00 South Korea
8 $39.51 0.76 1.961% 13613 9584027069.00 South Korea
9 $11.03 0.08 0.731% 9895 546574443.00 South Korea
10 $50.00 -1.24 -2.42% 13879 347445000.00 South Korea
11 $14.07 -0.36 -2.495% 7664960 24702130023.00
ipoyear industry sector
1 Commercial Banks Finance
2 1994 Electrical Products Consumer Durables
3 Telecommunications Equipment Public Utilities
4 2004 Industrial Machinery/Components Capital Goods
5 1994 Steel/Iron Ore Basic Industries
6 Major Banks Finance
7 Telecommunications Equipment Public Utilities
8 Commercial Banks Finance
9 2021 EDP Services Technology
10 2005 Business Services Miscellaneous
11 2021 Recreational Products/Toys Capital Goods
url exchange
1 /market-activity/stocks/kb NYSE
2 /market-activity/stocks/kep NYSE
3 /market-activity/stocks/kt NYSE
4 /market-activity/stocks/lpl NYSE
5 /market-activity/stocks/pkx NYSE
6 /market-activity/stocks/shg NYSE
7 /market-activity/stocks/skm NYSE
8 /market-activity/stocks/wf NYSE
9 /market-activity/stocks/ddi NASDAQ
10 /market-activity/stocks/grvy NASDAQ
11 /market-activity/stocks/cpng NYSE
서학개미에게 애플, 테슬라, 엔비디아라는 기술 테마주가 관심이 많다고 들었습니다. 이들 주가를 조회하기 위해서 종목코드를 살펴봅니다.
symbol_usa %>%
filter(stringr::str_detect(name, "Apple Inc|NVIDIA|Tesla Inc"))
symbol name lastsale netchange pctchange
1 AAPL Apple Inc. Common Stock $161.79 -4.63 -2.782%
2 NVDA NVIDIA Corporation Common Stock $195.15 -6.68 -3.31%
3 TSLA Tesla Inc. Common Stock $1005.05 -3.73 -0.37%
volume marketCap country ipoyear
1 84882424 2805008238600.00 United States 1980
2 62471343 488658400598.00 United States 1999
3 23232186 1038726824436.00 United States 2010
industry sector url
1 Computer Manufacturing Technology /market-activity/stocks/aapl
2 Semiconductors Technology /market-activity/stocks/nvda
3 Auto Manufacturing Capital Goods /market-activity/stocks/tsla
exchange
1 NASDAQ
2 NASDAQ
3 NASDAQ
결과를 보면 애플의 경우는 시가총액이 2조 8천억 달러이고, 테슬라도 1조 달러가 넘습니다. 검색을 하니, 2021년 8월 한국 증시의 시가총액이 약 2조 4천억 달러라 합니다. 애플의 시가총액보다도 적습니다.
애플의 주식 거래 정보를 가져옵니다. quantmod 패캐지의 getSymbols() 함수로 1980년 1월 1일 이후의 거래 정보를 가져옵니다. (애플은 1980년 12월 12일에 상장되었다고 합니다.)
trade_apple <- symbol_usa %>%
filter(stringr::str_detect(name, "Apple Inc")) %>%
select(symbol) %>%
pull() %>%
quantmod::getSymbols(from = "1980-01-01", auto.assign = FALSE)
head(trade_apple)
AAPL.Open AAPL.High AAPL.Low AAPL.Close AAPL.Volume
1980-12-12 0.128348 0.128906 0.128348 0.128348 469033600
1980-12-15 0.122210 0.122210 0.121652 0.121652 175884800
1980-12-16 0.113281 0.113281 0.112723 0.112723 105728000
1980-12-17 0.115513 0.116071 0.115513 0.115513 86441600
1980-12-18 0.118862 0.119420 0.118862 0.118862 73449600
1980-12-19 0.126116 0.126674 0.126116 0.126116 48630400
AAPL.Adjusted
1980-12-12 0.100326
1980-12-15 0.095092
1980-12-16 0.088112
1980-12-17 0.090293
1980-12-18 0.092911
1980-12-19 0.098581
tail(trade_apple)
AAPL.Open AAPL.High AAPL.Low AAPL.Close AAPL.Volume
2022-04-14 170.62 171.27 165.04 165.29 75237500
2022-04-18 163.92 166.60 163.57 165.07 69023900
2022-04-19 165.02 167.82 163.91 167.40 67723800
2022-04-20 168.76 168.88 166.10 167.23 67929800
2022-04-21 168.91 171.53 165.91 166.42 87227800
2022-04-22 166.46 167.87 161.50 161.79 84775200
AAPL.Adjusted
2022-04-14 165.29
2022-04-18 165.07
2022-04-19 167.40
2022-04-20 167.23
2022-04-21 166.42
2022-04-22 161.79
is(trade_apple)
[1] "xts" "oldClass" "xtsORzoo"
getSymbols() 함수는 시계열 데이터 구조의 xts 클래스 객체를 반환합니다. 이것을 데이터 프레임 객체로 변환하려면 zoo 패키지의 fortify.zoo() 함수를 사용합니다.
trade_apple_df <- trade_apple %>%
zoo::fortify.zoo()
head(trade_apple_df)
Index AAPL.Open AAPL.High AAPL.Low AAPL.Close AAPL.Volume
1 1980-12-12 0.128348 0.128906 0.128348 0.128348 469033600
2 1980-12-15 0.122210 0.122210 0.121652 0.121652 175884800
3 1980-12-16 0.113281 0.113281 0.112723 0.112723 105728000
4 1980-12-17 0.115513 0.116071 0.115513 0.115513 86441600
5 1980-12-18 0.118862 0.119420 0.118862 0.118862 73449600
6 1980-12-19 0.126116 0.126674 0.126116 0.126116 48630400
AAPL.Adjusted
1 0.100326
2 0.095092
3 0.088112
4 0.090293
5 0.092911
6 0.098581
is(trade_apple_df)
[1] "data.frame" "list" "oldClass" "vector"
애플의 상장 첫 거래 정보와 최근 거래 정보를 가져옵니다.
compare_trade <- trade_apple_df %>%
summarise(
first = min(Index),
last = max(Index)
) %>%
tidyr::pivot_longer(
everything(),
names_to = "date_flag",
values_to = "base_date"
) %>%
inner_join(
trade_apple_df,
by = c("base_date" = "Index")
)
compare_trade
# A tibble: 2 × 8
date_flag base_date AAPL.Open AAPL.High AAPL.Low AAPL.Close
<chr> <date> <dbl> <dbl> <dbl> <dbl>
1 first 1980-12-12 0.128 0.129 0.128 0.128
2 last 2022-04-22 166. 168. 162. 162.
# … with 2 more variables: AAPL.Volume <dbl>, AAPL.Adjusted <dbl>
첫 상장일의 종가대비 최근 거래일의 종가를 보면 약 1613배 주가가 상승했음을 알 수 있습니다.
compare_trade$AAPL.Adjusted[2] / compare_trade$AAPL.Adjusted[1]
[1] 1612.643
테슬라는 2010년 6월 29일에 상장했다고 합니다. getSymbols() 함수에는 시작일자를 “2000-01-01”로 입력해도 알아서 상장일 이후의 데이터를 가져옵니다. 우리가 회사의 상장일을 일일이 다 알 수 없으무로 대충 작은 값을 입력합니다.
trade_tesla <- symbol_usa %>%
filter(stringr::str_detect(name, "Tesla")) %>%
select(symbol) %>%
pull() %>%
quantmod::getSymbols(from = "2000-01-01", auto.assign = FALSE)
xts 객체를 핸들링하는 방법으로 테슬라의 상장일의 종가와 최근 거래일인 2022-04-22일의 종가를 비교해 봅니다. 4.8 달러로 시작한 주가가 약 210배 상승하여 1005달러에 거래를 마쳤습니다.
TSLA.Open TSLA.High TSLA.Low TSLA.Close TSLA.Volume
2010-06-29 3.80 5.00 3.508 4.778 93831500
2022-04-22 1014.91 1034.85 994.000 1005.050 23181600
TSLA.Adjusted
2010-06-29 4.778
2022-04-22 1005.050
trade_tesla[NROW(trade_tesla), "TSLA.Adjusted"] %>%
as.numeric() %>%
"/" (trade_tesla[1, "TSLA.Adjusted"] %>% as.numeric)
[1] 210.3495
일반적으로 주식거래에 대한 시계열 데이터는 캔들차트(Candlestick Chart)로 시각화합니다. 캔들차트는 quantmod 패키지의 chartSeries() 함수를 사용합니다. 테마를 이용하여, 다음처럼 상승의 패턴은 빨간색, 하락의 패턴은 파란색으로 표시합니다.
trade_apple %>%
quantmod::chartSeries(
theme = quantmod::chartTheme("white", up.col = "red", dn.col = "blue")
)
워낙 긴 기간의 트랜드이라 캔들차트인지, 단순 시계열 라인차트인지 구분이 되지 않습니다. 그래서 출력 기간을 올해 1월부터 제한을 해 봅니다. 이제 캔들차트처럼 보입니다. 지금이 하락장인가보군요. 주가가 하락하는 트랜드를 보이고 있습니다.
trade_apple %>%
quantmod::chartSeries(
subset="2022-01-01::2022-04-22",
theme = quantmod::chartTheme("white", up.col = "red", dn.col = "blue")
)
테슬라의 주가 흐름도 애플과 거의 유사한 것 같습니다. 주식의 문외한이라 좀 더 정교한 해석은 어렵지만, 기술 우량주인 두 주가와 비슷한 패턴으로 NASDAQ의 주가 흐름도 유사할 것 같습니다.
trade_tesla %>%
quantmod::chartSeries(
subset="2022-01-01::2022-04-22",
theme = quantmod::chartTheme("white", up.col = "red", dn.col = "blue")
)
간단하게 미국 주식의 거래 정보 데이터를 수집하는 방법을 다루어 보았습니다.
종목코드 정보를 가져오고, 종목코드로 해당 업체의 주식 거래 정보를 수집합니다. 그리 어려운 작업이 아니기 때문에 간단한 R 코드로 여러분이 관심있는 업체의 주식 거래정보를 획득할 수 있을 것입니다.
결국 외부 API를 이용하는 패키지의 안정성은 보장할 수 없을 것 같습니다. TTR{target="_blank} 패키지처럼 API의 정책의 변화로 정상적인 기능이 어느 순간에 비정상적인 상태로 변화할 수 있으니까요. 그러나 “구더기 무서워 장 못담그랴.”는 속담처럼, 유용한 기능의 제공을 위해서는 시도해야할 작업들인 것이지요.
다음에는 국내 업체의 주식 거래 정보를 수집하고, 수익률과 Value-at-Risk, 연간 성장률을 구하는 방법을 다루어 보겠습니다. 5년 전에 만들었던 책자에 포함되었던 주제입니다.
For attribution, please cite this work as
유충현 (2022, April 24). Dataholic: 미국 주가정보 가져오기. Retrieved from https://choonghyunryu.github.io/2022-04-24-usa-stock.Rmd
BibTeX citation
@misc{유충현2022미국, author = {유충현, }, title = {Dataholic: 미국 주가정보 가져오기}, url = {https://choonghyunryu.github.io/2022-04-24-usa-stock.Rmd}, year = {2022} }