2024년 3월 30일 토요일

몬테카를로 시뮬레이션 기반 주가 예측

이 글은 몬테카를로 시뮬레이션 기반 주가 예측하는 방법을 보여준다. 

주가를 다운로드하여, 평균, 편차를 계산한 후, 95% 수준에서 시뮬레이션을 수행해, 수익률을 예측해 본다. 다음은 이를 구현한 코드이다. 

import numpy as np
import matplotlib.pyplot as plt
from eodhd import APIClient
import config as cfg

api = APIClient(cfg.API_KEY)

def get_ohlc_data():
    df = api.get_historical_data("GSPC.INDX", "d", results=365)
    return df

if __name__ == "__main__":
    df = get_ohlc_data()

    # 날짜별 계산
    daily_returns = df["adjusted_close"].pct_change().dropna()

    # 시뮬레이션 파라메터
    initial_investment = 10000  # 초기 투자량
    num_simulations = 1000    # 시뮬레이션 횟수
    forecast_days = 365    # Investment horizon in days
    desired_return = 0.10  # Desired return (10%)

    # Calculate the average daily return
    average_daily_return = daily_returns.mean()

    # Calculate volatility as the standard deviation of daily returns
    volatility = daily_returns.std()

    print(f"Average Daily Return: {average_daily_return}")
    print(f"Volatility: {volatility}")

    # Simulating future returns
    simulated_end_returns = np.zeros(num_simulations)
    for i in range(num_simulations):
        random_returns = np.random.normal(
            average_daily_return, volatility, forecast_days
        )
        cumulative_return = np.prod(1 + random_returns)
        simulated_end_returns[i] = initial_investment * cumulative_return

    # Calculate the final investment values
    final_investment_values = simulated_end_returns

    # Calculate Value at Risk (VaR) and Expected Tail Loss (Conditional VaR)
    confidence_level = 0.95
    sorted_returns = np.sort(final_investment_values)
    index_at_var = int((1 - confidence_level) * num_simulations)
    var = initial_investment - sorted_returns[index_at_var]
    conditional_var = initial_investment - sorted_returns[:index_at_var].mean()

    print(f"Value at Risk (95% confidence): £{var:,.2f}")
    print(f"Expected Tail Loss (Conditional VaR): £{conditional_var:,.2f}")

    num_success = np.sum(
        final_investment_values >= initial_investment * (1 + desired_return)
    )
    probability_of_success = num_success / num_simulations

    print(
        f"Probability of achieving at least a {desired_return*100}% return: {probability_of_success*100:.2f}%"
    )

    plt.figure(figsize=(10, 6))
    plt.hist(final_investment_values, bins=50, alpha=0.75)
    plt.axvline(
        initial_investment * (1 + desired_return),
        color="r",
        linestyle="dashed",
        linewidth=2,
    )
    plt.axvline(initial_investment - var, color="g", linestyle="dashed", linewidth=2)
    plt.title("Distribution of Final Investment Values")
    plt.xlabel("Final Investment Value")
    plt.ylabel("Frequency")
    plt.show()

    """
    # Plotting the results
    plt.figure(figsize=(10, 6))
    plt.plot(simulations.T, color="blue", alpha=0.025)
    plt.title("Monte Carlo Simulation of Future Prices")
    plt.xlabel("Day")
    plt.ylabel("Price")
    plt.show()
    """

레퍼런스

댓글 없음:

댓글 쓰기