ai_api_talking
  • Home
  • Stock_analysis
  • Crypto_analysis
  • Weather_analysis
  • Caffee_analysis
  • Word_cloud
  • SEPA_Invest
  • Gold_Invest
  • Llamar_AI
  • ellemer_AI
  • mall_AI
  • GeminiR_AI

On this page

  • 1 개요
    • 1.1 기술적 지표 설명
      • 1.1.1 이동평균선 (Moving Averages)
      • 1.1.2 RSI (Relative Strength Index)
  • 2 데이터 수집 및 전처리
  • 3 분석 결과
    • 3.1 가격 동향 분석
    • 3.2 투자 점수 계산
    • 3.3 투자 추천
  • 4 투자 전략 가이드라인
    • 4.1 매수 전략
    • 4.2 매도 전략
  • 5 주의사항
  • 6 결론

미국 주가 데이터 분석

Author

waterfirst

Published

May 5, 2025

1 개요

이 문서는 미국 주요 기업들의 주가 기술적 분석과 투자 전략을 다룹니다. 다양한 기술적 지표를 활용하여 투자 결정을 돕는 종합적인 분석을 제공합니다.

1.1 기술적 지표 설명

1.1.1 이동평균선 (Moving Averages)

  • 20일 이동평균선 (SMA20): 단기 추세
  • 50일 이동평균선 (SMA50): 중기 추세
  • 200일 이동평균선 (SMA200): 장기 추세

이동평균선은 다음 공식으로 계산됩니다: \(SMA_n = \frac{P_1 + P_2 + ... + P_n}{n}\)

1.1.2 RSI (Relative Strength Index)

RSI는 과매수/과매도 상태를 판단하는 지표입니다.

Code
RSI = 100 - \frac{100}{1 + RS}

여기서 RS는 상승평균/하락평균 입니다.

  • 70 이상: 과매수 구간
  • 30 이하: 과매도 구간
  • 30-70: 중립 구간

2 데이터 수집 및 전처리

Code
# 필요한 패키지 설치 및 로드
library(tidyverse)
library(tidyquant)
library(plotly)
library(TTR)
library(lubridate)
library(scales)
library(purrr)

# 분석할 주식 설정
stocks <- c("AAPL", "MSFT", "GOOGL", "AMZN", "NVDA", "META", "TSLA", "JPM")
start_date <- Sys.Date() - 365  # 1년 전부터
end_date <- Sys.Date()          # 오늘까지

# 주식 이름 매핑 함수
get_stock_name <- function(symbol) {
  stock_names <- c(
    "AAPL" = "Apple Inc.",
    "MSFT" = "Microsoft Corp.",
    "GOOGL" = "Alphabet Inc.",
    "AMZN" = "Amazon.com Inc.",
    "NVDA" = "NVIDIA Corp.",
    "META" = "Meta Platforms Inc.",
    "TSLA" = "Tesla Inc.",
    "JPM" = "JPMorgan Chase & Co."
  )
  
  result <- stock_names[symbol]
  ifelse(is.na(result), as.character(symbol), result)
}

# 달러 통화 형식 함수
dollar_format_custom <- function(x) {
  scales::dollar_format(largest_with_cents = 1)(x)
}

# 데이터 수집 및 전처리
stock_data <- tq_get(stocks, 
                    from = start_date, 
                    to = end_date,
                    get = "stock.prices") %>%
  arrange(symbol, date) %>%
  group_by(symbol) %>%
  filter(n() >= 20) %>%  # 최소 20일치 데이터 필요
  mutate(
    display_name = get_stock_name(symbol),
    # 이동평균선
    SMA20 = TTR::SMA(close, n = 20),
    SMA50 = TTR::SMA(close, n = 50),
    SMA200 = TTR::SMA(close, n = 200),
    
    # RSI
    RSI = TTR::RSI(close, n = 14),
    
    # MACD
    macd_data = TTR::MACD(close, nFast = 12, nSlow = 26, nSig = 9),
    MACD = macd_data[,'macd'],
    Signal = macd_data[,'signal'],
    
    # Bollinger Bands
    bb_data = TTR::BBands(close, n = 20),
    BB_up = bb_data[,'up'],
    BB_mid = bb_data[,'mavg'],
    BB_down = bb_data[,'dn'],
    
    # 변동성 및 수익률
    daily_returns = (close/lag(close) - 1),
    volatility = roll::roll_sd(daily_returns, width = 20) * sqrt(252) * 100
  ) %>%
  ungroup()

3 분석 결과

3.1 가격 동향 분석

Code
# 가격 차트 시각화
price_charts <- stock_data %>%
  ggplot(aes(x = date, y = close, color = display_name)) +
  geom_line() +
  geom_line(aes(y = SMA20), linetype = "dashed", alpha = 0.5) +
  geom_line(aes(y = SMA50), linetype = "dashed", alpha = 0.5) +
  geom_line(aes(y = SMA200), linetype = "dashed", alpha = 0.5) +
  facet_wrap(~display_name, scales = "free_y", ncol=2) +
  labs(title = "Stock Price Trends",
       subtitle = "With 20, 50, and 200-day Moving Averages",
       x = "Date",
       y = "Price (USD)") +
  theme_minimal() +
  scale_y_continuous(labels = scales::dollar_format()) +
  scale_color_brewer(palette = "Set1") +
  theme(legend.position = "none")

print(price_charts)

Code
## 볼린저 밴드 분석
bollinger_charts <- stock_data %>%
  ggplot(aes(x = date)) +
  geom_line(aes(y = close), color = "black") +
  geom_line(aes(y = BB_up), color = "blue", linetype = "dashed") +
  geom_line(aes(y = BB_down), color = "blue", linetype = "dashed") +
  geom_ribbon(aes(ymin = BB_down, ymax = BB_up), fill = "blue", alpha = 0.1) +
  facet_wrap(~display_name, scales = "free_y", ncol=2) +
  labs(title = "Bollinger Bands Analysis",
       x = "Date",
       y = "Price (USD)") +
  theme_minimal() +
  scale_y_continuous(labels = scales::dollar_format())

print(bollinger_charts)

Code
## RSI 분석
rsi_charts <- stock_data %>%
  ggplot(aes(x = date, y = RSI, color = display_name)) +
  geom_line() +
  geom_hline(yintercept = c(30, 70), linetype = "dashed", color = "red") +
  facet_wrap(~display_name, ncol=2) +
  labs(title = "RSI Indicator",
       subtitle = "With 30/70 Overbought/Oversold Levels",
       x = "Date",
       y = "RSI") +
  theme_minimal() +
  theme(legend.position = "none")

print(rsi_charts)

Code
## 거래량 분석
volume_charts <- stock_data %>%
  ggplot(aes(x = date, y = volume/1e6, fill = display_name)) +
  geom_col(alpha = 0.7) +
  facet_wrap(~display_name, scales = "free_y", ncol=2) +
  labs(title = "Trading Volume Analysis",
       x = "Date",
       y = "Volume (Millions)") +
  theme_minimal() +
  theme(legend.position = "none")

print(volume_charts)

Code
## 상관관계 분석
correlation_data <- stock_data %>%
  select(date, symbol, close) %>%
  pivot_wider(names_from = symbol, values_from = close) %>%
  select(-date) %>%
  cor(use = "complete.obs")

correlation_plot <- correlation_data %>%
  as.data.frame() %>%
  rownames_to_column("Stock1") %>%
  pivot_longer(-Stock1, names_to = "Stock2", values_to = "Correlation") %>%
  ggplot(aes(x = Stock1, y = Stock2, fill = Correlation)) +
  geom_tile() +
  scale_fill_gradient2(low = "red", high = "blue", mid = "white", 
                      midpoint = 0, limit = c(-1,1)) +
  geom_text(aes(label = round(Correlation, 2)), color = "black") +
  labs(title = "Stock Correlation Matrix") +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

print(correlation_plot)

3.2 투자 점수 계산

Code
# 투자 점수 계산
investment_score <- stock_data %>%
  group_by(symbol) %>%
  summarise(
    # 추세 점수 (30%)
    trend_score = mean(close > SMA50, na.rm = TRUE) * 3,
    
    # 모멘텀 점수 (20%)
    momentum_score = mean(RSI > 50 & RSI < 70, na.rm = TRUE) * 2,
    
    # 거래량 점수 (20%)
    volume_score = mean(volume > lag(SMA(volume, n = 20)), na.rm = TRUE) * 2,
    
    # 변동성 점수 (15%)
    volatility_score = (1 - mean(volatility, na.rm = TRUE) / 
                         max(volatility, na.rm = TRUE)) * 1.5,
    
    # 볼린저 밴드 점수 (15%)
    bb_score = mean(close > BB_mid, na.rm = TRUE) * 1.5,
    
    # 최근 추세 점수
    recent_trend = mean(tail(daily_returns, 20) > 0, na.rm = TRUE) * 2,
    
    # 총점 계산
    total_score = trend_score + momentum_score + volume_score + 
      volatility_score + bb_score + recent_trend
  ) %>%
  arrange(desc(total_score))

# 현재 상태 계산
current_status <- stock_data %>%
  group_by(symbol) %>%
  mutate(volume_ma = SMA(volume, n = 20)) %>%
  slice_tail(n = 1) %>%
  select(symbol, display_name, close, RSI, volume, volume_ma, volatility) %>%
  left_join(investment_score, by = "symbol")

# 투자 점수 출력
print(investment_score %>% 
      select(symbol, total_score) %>% 
      arrange(desc(total_score)))
# A tibble: 8 × 2
  symbol total_score
  <chr>        <dbl>
1 JPM           6.74
2 META          6.56
3 AAPL          6.31
4 TSLA          6.00
5 AMZN          5.94
6 GOOGL         5.60
7 NVDA          5.45
8 MSFT          4.96

3.3 투자 추천

Code
cat("\n=== 투자 전략 권장사항 ===\n")

=== 투자 전략 권장사항 ===
Code
top_picks <- investment_score %>% 
  slice_head(n = 3)

cat(sprintf("\n추천 투자 순위:\n"))

추천 투자 순위:
Code
for(i in 1:nrow(top_picks)) {
  current_stock <- current_status %>% 
    filter(symbol == top_picks$symbol[i])
  
  cat(sprintf("\n%d. %s (%s)\n", 
              i, 
              current_stock$display_name,
              current_stock$symbol))
  
  cat(sprintf("   점수: %.2f\n", top_picks$total_score[i]))
  cat(sprintf("   현재가: $%.2f\n", current_stock$close))
  cat(sprintf("   RSI: %.2f\n", current_stock$RSI))
  cat(sprintf("   변동성: %.2f%%\n", current_stock$volatility))
  
  # 투자 전략 제안
  cat("\n   투자 전략:\n")
  
  # RSI 기반 전략
  if(current_stock$RSI < 30) {
    cat("   - 과매도 구간으로 단기 반등 가능성 높음\n")
  } else if(current_stock$RSI > 70) {
    cat("   - 과매수 구간으로 단기 조정 가능성 있음\n")
  } else {
    cat("   - RSI 중립구간으로 추세 따라 매매 전략 구사\n")
  }
  
  # 거래량 기반 전략
  if(current_stock$volume > current_stock$volume_ma) {
    cat("   - 거래량 증가로 현재 추세 강화 신호\n")
  } else {
    cat("   - 거래량 감소로 신중한 접근 필요\n")
  }
}

1. JPMorgan Chase & Co. (JPM)
   점수: 6.74
   현재가: $252.51
   RSI: 62.12
   변동성: 49.23%

   투자 전략:
   - RSI 중립구간으로 추세 따라 매매 전략 구사
   - 거래량 감소로 신중한 접근 필요

2. Meta Platforms Inc. (META)
   점수: 6.56
   현재가: $597.02
   RSI: 60.39
   변동성: 72.62%

   투자 전략:
   - RSI 중립구간으로 추세 따라 매매 전략 구사
   - 거래량 증가로 현재 추세 강화 신호

3. Apple Inc. (AAPL)
   점수: 6.31
   현재가: $205.35
   RSI: 48.05
   변동성: 74.83%

   투자 전략:
   - RSI 중립구간으로 추세 따라 매매 전략 구사
   - 거래량 증가로 현재 추세 강화 신호

4 투자 전략 가이드라인

4.1 매수 전략

  1. 기술적 지표 조합
    • RSI < 30 (과매도)
    • 가격이 주요 이동평균선 근처
    • 거래량 증가 추세
  2. 리스크 관리
    • 포지션 크기: 총 자산의 5% 이하
    • 손절가: 매수가의 -5%
    • 목표가: 매수가의 +15%

4.2 매도 전략

  1. 기술적 지표 기반
    • RSI > 70 (과매수)
    • 이동평균선 하향돌파
    • 거래량 감소
  2. 수익 실현
    • 단계적 매도: 목표가 도달 시 30%, 50%, 100%
    • 추세 전환 시 전량 매도

5 주의사항

  1. 리스크 관리의 중요성
    • 분산 투자 필수
    • 레버리지 신중하게 사용
    • 적절한 포지션 사이징
  2. 기술적 분석의 한계
    • 펀더멘털 분석 병행 필요
    • 시장 상황에 따른 전략 조정
    • 과거 성과가 미래 수익을 보장하지 않음
  3. 시장 환경 고려
    • 전반적인 시장 추세 확인
    • 업종별 순환매 고려
    • 거시경제 지표 모니터링

6 결론

이 분석은 주요 미국 기업들의 기술적 분석을 기반으로 투자 전략을 제시합니다. 하지만 기술적 분석만으로는 완벽한 투자 판단을 내릴 수 없으며, 다음 요소들을 함께 고려해야 합니다:

  1. 기업의 펀더멘털
    • 실적 및 성장성
    • 시장 점유율
    • 재무건전성
  2. 산업 동향
    • 업종 성장성
    • 경쟁 환경
    • 규제 변화
  3. 거시경제 환경
    • 금리 동향
    • 인플레이션
    • 경제 성장률

투자자는 이러한 종합적인 분석을 바탕으로 자신의 투자 성향과 위험 감수 성향에 맞는 포트폴리오를 구성해야 합니다.