인공지능과 경제

모멘텀전략 Momentum Strategy 총정리

2에코랩 2023. 3. 7.

오늘은 퀀트투자에서 주로 활용하는 모멘텀전략 Momentum Strategy 을 살펴보도록 하겠습니다.


모멘텀 전략은 퀀트투자에서 매우 인기 있는 전략 중 하나입니다. 모멘텀 전략은 과거 일정 기간 동안 수익률이 좋았던 자산들에 투자하여 미래에도 좋은 수익을 내겠다는 전략입니다.

모멘텀 전략 적용 예시



보통 모멘텀 전략은 상대 모멘텀과 절대 모멘텀 두 가지 유형으로 나뉘어집니다. 상대 모멘텀은 주어진 기간 동안 자산 수익률의 상대적 순위를 비교하여 높은 순위에 있는 자산들에 투자하는 것입니다. 반면, 절대 모멘텀은 자산의 과거 수익률이 일정 기준치 이상인 경우에만 해당 자산에 투자하는 것입니다.



모멘텀 전략은 트렌드 추종 전략과는 다릅니다. 트렌드 추종 전략은 자산의 가격이 상승 추세에 있을 때 매수하고, 하락 추세에 있을 때 매도하는 전략입니다. 반면, 모멘텀 전략은 자산의 수익률의 상대적인 강도를 비교하여 투자 결정을 내리는 전략입니다.

 

 

오늘은 퀀트투자에서 주로 활용하는 모멘텀전략 Momentum Strategy 을 상세히 살펴보도록 하겠습니다.

 

 

퀀트 투자에서 모멘텀 전략 Momentum Strategy이 중요한 이유는 다음과 같습니다.


 

경제학 이론적 근거
모멘텀은 경제학에서 잘 알려진 표현 중 하나로, 기업 재무 성과나 경제 성장률 등이 이전의 성과와 관련이 있다는 가정에 기반합니다. 이론적으로 모멘텀 전략은 이러한 경제학적 이론을 바탕으로 성과를 예측하는 데 유용할 수 있습니다.
효율적 시장 가설의 한계
효율적 시장 가설은 시장이 모든 정보를 반영하고 있으며 시장 참가자들이 미래에 대한 정보를 이미 반영하고 있기 때문에 시장에서 초과 수익을 올리는 것은 불가능하다는 가설입니다. 그러나 이 가설에는 일부 한계가 있으며, 모멘텀 전략은 이러한 한계를 극복할 수 있는 방법 중 하나입니다.
과거 성과를 기반으로한 전략
모멘텀 전략은 일정 기간 동안의 성과를 기반으로 투자 결정을 내리는 전략입니다. 이러한 전략은 장기적인 경향을 파악하는 것보다 과거 성과에 집중하여 수익을 내는 것에 초점을 둡니다.
퀀트 투자에서 성과 검증이 용이
퀀트투자에서는 모든 투자 결정이 규칙 기반으로 이루어지기 때문에, 성과 검증이 용이합니다. 따라서 모멘텀 전략을 포함한 다양한 전략을 시뮬레이션하고 검증하는 것이 비교적 쉽습니다.

Monthly returns of momentum strategy and value strategy 출처 : 한국 주식시장에서의 융합적 모멘텀 투자전략

 

 

퀀트 투자에서 모멘텀 전략의 방법과 절차는 다음과 같습니다.


 

구분 항목 내용
1 대상 종목 선택
우선, 투자 대상 종목을 선택합니다. 이때, 주식, 채권, 화폐, 상품 등 어떤 자산 클래스에 대해서 모멘텀 전략을 수행할 것인지를 결정합니다.
2 모멘텀 지표 선택
다양한 모멘텀 지표 중에서 선택합니다. 일반적으로 주가 수익률, 수익률의 이동평균, 상대적 강도 지수(RSI), MACD 등을 사용합니다.
3 투자 대상 종목의 데이터 수집
모멘텀 전략에서는 투자 대상 종목의 과거 데이터를 수집하여 모멘텀 지표를 계산합니다.
4 모멘텀 지표 계산
수집한 데이터를 기반으로 모멘텀 지표를 계산합니다.
5 종목 선정
계산된 모멘텀 지표를 기반으로 모멘텀이 높은 상위 종목을 선택합니다. 일반적으로 과거 일정 기간 동안 가장 수익률이 높은 종목을 선택합니다.
6 리밸런싱
일정 기간마다 모멘텀이 높은 종목을 선정하여 포트폴리오를 리밸런싱합니다. 리밸런싱 주기는 투자자의 전략과 성향에 따라 다르게 결정됩니다.
7 투자 실행
선택된 종목에 대해서 투자 실행을 합니다. 투자 방식은 개별 종목에 대한 매수, 전략에 따라 가중치를 부여하여 매수 등 다양한 방식이 있습니다.
8 모니터링
투자 포트폴리오를 모니터링하면서 수익률과 위험성을 평가하고, 필요에 따라 포트폴리오를 수정하거나 재조정합니다.

모멘텀전략 및 반대전략의 White p값 출처 : 모멘텀전략과 반대전략에 대한 사실성 체크검정

퀀트투자에서 모멘턴 전략을 수행하는 알고리즘은 다음과 같습니다.


퀀트 투자에서 모멘텀 전략을 수행할 수 있는 다양한 알고리즘이 있습니다. 상대 모멘텀 알고리즘 (Relative Momentum Algorithm), 절대 모멘텀 알고리즘 (Absolute Momentum Algorithm), 이동평균선 모멘텀 알고리즘 (Moving Average Momentum Algorithm), 모멘텀 리밸런싱 알고리즘 (Momentum Rebalancing Algorithm)입니다. 

 

하나씩 자세히 살펴보도록 하겠습니다.

 

 

상대 모멘텀 알고리즘 (Relative Momentum Algorithm)

  • 가장 많이 사용되는 모멘텀 전략 중 하나입니다.
  • 상대 모멘텀 알고리즘은 주식, ETF 또는 기타 자산의 수익률을 계산하고, 일정 기간 동안 상승한 자산을 매수하고 하락한 자산을 매도하는 전략입니다.
  • 일반적으로 12개월 (252 거래일) 기간 동안의 수익률을 계산합니다.
import pandas as pd
import yfinance as yf

# Define parameters
symbols = ['AAPL', 'MSFT', 'GOOG']  # List of symbols to use
lookback = 252  # Lookback period in trading days
holding_period = 21  # Holding period in trading days

# Download historical price data
prices = yf.download(symbols, period='max', interval='1d', group_by='ticker')
prices = prices['Adj Close'].fillna(method='ffill')

# Calculate returns over lookback period
returns = prices.pct_change(lookback)

# Calculate mean return over lookback period for each symbol
mean_returns = returns.mean()

# Sort symbols by mean return in descending order
sorted_symbols = mean_returns.sort_values(ascending=False).index.tolist()

# Create portfolio with top-performing symbols
portfolio = sorted_symbols[:int(len(symbols)/2)]

# Define entry and exit signals
entry_signal = 0
exit_signal = 0

# Loop through each trading day
for i in range(lookback, len(prices)):
    # Calculate portfolio returns over holding period
    portfolio_returns = prices[portfolio].iloc[i:i+holding_period].pct_change().sum(axis=1)
    
    # Calculate market return over holding period
    market_return = prices.iloc[i+holding_period] / prices.iloc[i]
    
    # Calculate excess return of portfolio over market
    excess_return = portfolio_returns.mean() - market_return
    
    # Update entry and exit signals based on excess return
    if excess_return > entry_signal:
        entry_signal = excess_return
    elif excess_return < exit_signal:
        exit_signal = excess_return
        
    # If entry signal is triggered, buy portfolio
    if excess_return >= entry_signal and not portfolio:
        portfolio = sorted_symbols[:int(len(symbols)/2)]
    
    # If exit signal is triggered, sell portfolio
    if excess_return <= exit_signal and portfolio:
        portfolio = []
        
    # Print portfolio and excess return at end of each holding period
    if i % holding_period == 0:
        print(f"Portfolio: {portfolio}, Excess Return: {excess_return}")

절대 모멘텀 알고리즘 (Absolute Momentum Algorithm)

  • 일정 기간 동안 자산의 수익률이 양수인 경우 해당 자산을 보유하고, 음수인 경우 다른 자산으로 교체하는 전략입니다.
  • 예를 들어, 일정 기간 (예: 12개월) 동안 S&P 500 지수의 수익률이 양수인 경우 S&P 500 지수를 보유하고, 음수인 경우 국채나 캐시로 교체합니다.
import pandas as pd
import yfinance as yf

# set parameters
tickers = ["AAPL"]
lookback = 200
threshold = 0.05

# download data from Yahoo Finance API
data = yf.download(tickers, period="max")

# calculate returns and rolling standard deviation
returns = data["Adj Close"].pct_change()
std = returns.rolling(lookback).std()

# calculate the absolute momentum signal
signal = returns > threshold * std

# calculate positions based on the signal
positions = signal.astype(int).diff()

# calculate strategy returns
strategy_returns = positions.shift(1) * returns

# calculate cumulative returns
cumulative_returns = (1 + strategy_returns).cumprod()

# plot the cumulative returns
cumulative_returns.plot()

이동평균선 모멘텀 알고리즘 (Moving Average Momentum Algorithm)

  • 이동평균선 모멘텀 알고리즘은 단기 이동평균선이 중장기 이동평균선을 상향돌파하면 매수, 하향돌파하면 매도하는 전략입니다.
  • 예를 들어, 50일 이동평균선이 200일 이동평균선을 상향돌파하면 해당 자산을 매수하고, 하향돌파하면 해당 자산을 매도합니다.
import pandas as pd
import yfinance as yf

# Define the stock symbol and moving average periods
symbol = 'AAPL'
short_period = 50
long_period = 200

# Download historical data from Yahoo Finance API
data = yf.download(symbol, start='2010-01-01')

# Calculate the short and long moving averages
data['short_ma'] = data['Close'].rolling(window=short_period).mean()
data['long_ma'] = data['Close'].rolling(window=long_period).mean()

# Define the buy/sell signals based on the moving average crossover
data['signal'] = 0.0
data['signal'][short_period:] = \
    ((data['short_ma'][short_period:] > data['long_ma'][short_period:]) * 1.0)

# Calculate the returns based on the positions and the market price
data['returns'] = data['Close'].pct_change()
data['strategy_returns'] = data['signal'].shift(1) * data['returns']

# Print the cumulative returns of the strategy
cumulative_returns = (1 + data['strategy_returns']).cumprod()
print(cumulative_returns.tail())

모멘텀 리밸런싱 알고리즘 (Momentum Rebalancing Algorithm)

  • 모멘텀 리밸런싱 알고리즘은 모멘텀 전략을 구현하기 위해 일정 기간마다 자산 구성을 조정하는 전략입니다.
  • 예를 들어, 12개월 기간 동안 수익률이 높은 상위 10개의 자산을 매수하고, 12개월이 지난 후 재조정하여 최신 상위 10개의 자산을 매수하는 전략입니다.
import pandas as pd
import yfinance as yf

# Set the parameters
symbols = ['AAPL', 'AMZN', 'GOOG', 'NFLX'] # List of stock symbols
start_date = '2015-01-01' # Start date for data retrieval
end_date = '2021-01-01' # End date for data retrieval
lookback_period = 252 # Lookback period for momentum calculation
rebalancing_period = 63 # Rebalancing period for portfolio rebalancing

# Download the price data from Yahoo Finance API
prices_df = yf.download(symbols, start=start_date, end=end_date)['Adj Close']

# Calculate the momentum of each stock over the lookback period
momentum = prices_df.pct_change(lookback_period)

# Create a DataFrame to store the positions for each stock
positions = pd.DataFrame(index=momentum.index, columns=symbols)

# Loop through the data to populate the positions DataFrame
for i in range(lookback_period, len(momentum)):
    # Determine the stocks with the highest momentum
    top_momentum = momentum.iloc[i].nlargest(len(symbols))
    # Set the positions for these stocks to 1 and the rest to 0
    positions.loc[momentum.index[i], top_momentum.index] = 1
    positions.loc[momentum.index[i], top_momentum.index[-1]+1:] = 0

# Create a DataFrame to store the portfolio returns
portfolio_returns = pd.DataFrame(index=prices_df.index, columns=['Returns'])

# Loop through the data to calculate the portfolio returns
for i in range(lookback_period, len(prices_df)):
    # Determine the current positions of each stock
    current_positions = positions.loc[prices_df.index[i-1]]
    # Calculate the returns for each stock
    stock_returns = prices_df.iloc[i] / prices_df.iloc[i-1] - 1
    # Calculate the overall return for the portfolio
    portfolio_return = current_positions.dot(stock_returns)
    portfolio_returns.loc[prices_df.index[i]] = portfolio_return

    # Rebalance the portfolio if the rebalancing period has elapsed
    if i % rebalancing_period == 0:
        momentum = prices_df.pct_change(lookback_period)
        top_momentum = momentum.iloc[i].nlargest(len(symbols))
        positions.loc[momentum.index[i], top_momentum.index] = 1
        positions.loc[momentum.index[i], top_momentum.index[-1]+1:] = 0

# Print the portfolio returns
print(portfolio_returns)

 

 

오늘은 퀀트투자에서 평균회귀전략만큼 중요하게 활용되는 모멘텀전략 Momentum Strategy에 대해서 살펴보았습니다. 위에서 제시한 알고리즘은 야후파이낸스 api를 활용하는 예시 코드이니, 참고용으로만 활용하기 바랍니다. 또한 투자는 어디까지 본인의 주관과 결정에 따른 것으로 책임은 전적으로 자신에게 있음을 꼭 명심하시기 바랍니다. 

 

또한 알고리즘 투자, 퀀트투자 역시 인간이 설계한 알고리즘에 따라 기계적으로 이루어지는 투자임을 기억하기 바랍니다.

 

이상으로 모멘텀전략 Momentum Strategy 총정리 포스팅을 마칩니다. 감사합니다.

반응형

댓글

💲 추천 글