본문 바로가기
Quant Stock

분할매수에 대한 테스팅

by quantWhale 2024. 5. 14.
반응형

안녕하세요. 인천고래입니다.

 

이번 글에서는 분할 매수를 진행함에 있어서 상승장과 하락장 일 때 분할매수를 어떤 방식으로 해야할지에 대한 결과(?)를 얻어 보도록 하겠습니다.

 

우선 말씀 드릴 사항이 있는데 실제 주가는 상승과 하락을 반복합니다.

그래서 단순 하락장과 단순 상승장의 데이터를 가지고 테스트 하였음을 알려드립니다.

상승장과 하락장 분할매수 시뮬레이션 결과

 

아래는 관련 코드입니다.

'''

'''

import yfinance as yf
import numpy as np
import matplotlib.pyplot as plt


# 주가 데이터 다운로드 함수
def download_stock_data(ticker, start_date, end_date):
    stock_data = yf.download(ticker, start=start_date, end=end_date)
    return stock_data['Adj Close']


# 주가 데이터 시뮬레이션 함수
def simulate_strategy_with_real_data(prices, initial_seed, initial_weight, num_splits):
    buy_records = []
    remaining_seed = initial_seed
    total_shares = 0

    for i in range(num_splits):
        if i == 0:
            investment = initial_seed * initial_weight
            remaining_seed -= investment
            shares = investment / prices[0]
            buy_records.append({'Price': prices[0], 'Shares': shares})
        else:
            price = prices[min(i, len(prices) - 1)]

            investment = remaining_seed / (num_splits - i)
            remaining_seed -= investment
            shares = investment / price
            buy_records.append({'Price': price, 'Shares': shares})

        total_shares += shares

    # 전체 주식 수 및 평균 매입 단가
    total_investment = sum([record['Price'] * record['Shares'] for record in buy_records])
    average_price = total_investment / total_shares

    # 최종 자산 가치
    final_price = prices[-1]
    final_value = total_shares * final_price
    profit = final_value - initial_seed

    return profit, buy_records


# 리스크 분석 함수
def risk_analysis_with_real_data(prices, initial_seed, num_splits):
    profits = []
    for weight in np.linspace(0.1, 0.9, 9):
        profit, _ = simulate_strategy_with_real_data(prices, initial_seed, weight, num_splits)
        profits.append(profit)

    max_profit = max(profits)
    min_profit = min(profits)
    volatility = np.std(profits)

    return max_profit, min_profit, volatility


# 실제 데이터 다운로드
# ticker = "AAPL"  # 분석할 주식의 티커
ticker = "005930.KS"  # 삼성전자 주식의 티커
start_date = "2023-01-01"
end_date = "2023-12-31"

initial_seed = 40000000

prices = download_stock_data(ticker, start_date, end_date)

# 상승장 시나리오
ascending_prices = prices * (1 + 0.01 * np.arange(len(prices)))

# 하락장 시나리오
descending_prices = prices * (1 - 0.01 * np.arange(len(prices)))

# 3분할과 5분할에 대한 리스크 분석
split_counts = [3, 5]
ascending_results = {}
descending_results = {}

for num_splits in split_counts:
    max_profit, min_profit, volatility = risk_analysis_with_real_data(ascending_prices, initial_seed, num_splits)
    ascending_results[num_splits] = {
        'Max Profit': max_profit,
        'Min Profit': min_profit,
        'Volatility': volatility
    }

    max_profit, min_profit, volatility = risk_analysis_with_real_data(descending_prices, initial_seed, num_splits)
    descending_results[num_splits] = {
        'Max Profit': max_profit,
        'Min Profit': min_profit,
        'Volatility': volatility
    }

# 결과 출력
print("Ascending Market Results:")
for num_splits, results in ascending_results.items():
    print(f"Risk Analysis for {num_splits} Splits in Ascending Market:")
    print(f"  Max Profit: {results['Max Profit']}")
    print(f"  Min Profit: {results['Min Profit']}")
    print(f"  Volatility: {results['Volatility']}\n")

print("Descending Market Results:")
for num_splits, results in descending_results.items():
    print(f"Risk Analysis for {num_splits} Splits in Descending Market:")
    print(f"  Max Profit: {results['Max Profit']}")
    print(f"  Min Profit: {results['Min Profit']}")
    print(f"  Volatility: {results['Volatility']}\n")

# 그래프 출력
for num_splits in split_counts:
    profits = []
    for weight in np.linspace(0.1, 0.9, 9):
        profit, _ = simulate_strategy_with_real_data(ascending_prices, initial_seed, weight, num_splits)
        profits.append(profit)

    plt.plot(np.linspace(0.1, 0.9, 9), profits, marker='o', label=f'{num_splits} Splits - Ascending')

    profits = []
    for weight in np.linspace(0.1, 0.9, 9):
        profit, _ = simulate_strategy_with_real_data(descending_prices, initial_seed, weight, num_splits)
        profits.append(profit)

    plt.plot(np.linspace(0.1, 0.9, 9), profits, marker='o', linestyle='--', label=f'{num_splits} Splits - Descending')

plt.title("Profit vs. Initial Investment Weight in Ascending and Descending Markets")
plt.xlabel("Initial Investment Weight")
plt.ylabel("Profit")
plt.legend()
plt.grid(True)
plt.show()

 

이 글이 퀀트 프로그램을 만드시는 분들께 자그마한 아이디어라도 얻을 수 있기를 바랍니다.

감사합니다.

반응형
-

댓글