Data Analysis/Python for DA

[Invest Class] 3. Halloween 투자 전략 함수 생성

Jiyeon's Desk 2025. 3. 29. 16:31

1. Halloween 투자 전략

11월 첫날에 시작 각격으로 구매하여 4월 마지막날에 종가로 판매하는 투자 전략(투자 전략이랄 것도 없는 ㅎㅎ..!) 재미용으로 봐주세요!

 

*시계열 데이터에서 시간을 합하는 방법

from dateutil.relativedelta import relativedelta
start = datetime(year = 2000, month=11, day=1)
start + relativedelta(months=5)

 

* datime객체를 다시 문자열로 바꿔서 loc을 걸어주는 이유

halloween_df = pd.DataFrame()

for i in range(2000, 2011):
    start = datetime(year = i, month =11, day =1)
    end = start + relativedelta(months = 5)
    
    start= start.strftime('%Y-%m')
    end= end.strftime('%Y-%m')
    
    start_df = df.loc[start].head(1)
    end_df =df.loc[end].tail(1)
    halloween_df = pd.concat([halloween_df, start_df, end_df])
halloween_df

 

-> df.loc[..]에서 인덱스의 정확한 형식이 중요하기 때문에 df.index 가 datetimeindex이면 문자열 '연-월'만 지정해도 괜찮지만, datetime객체 그대로 쓰면 day까지 포함한 그날만 찾으려고 하기 때문에 오류가 남.

halloween_df = pd.DataFrame()

for i in range(2000,2011,1):
    buy_mon = f"{i}-11"
    sell_mon = f"{i+1}-4"
    start = df.loc[buy_mon].head(1)
    end = df.loc[sell_mon].tail(1)
    halloween_df = pd.concat([halloween_df, start, end])
halloween_df

 이렇게도 작성할 수 있음 ☘️

 

2. Halloween 투자 전략 함수 생성

* utc?

 df.index = pd.to_datetime(df.index, utc=True)

 

UTC (Coordinated Universal Time) :전 세계에서 공통적으로 사용하는 표준 시간대

def halloween(_df, start = 2010, end = datetime.now().year, mon = 11):
    df = _df.copy()
    if 'Date' in df.columns:
        df.index = df.set_index('Date')
    df.index = pd.to_datetime(df.index, utc = True)
    
    result = pd.DataFrame()
    
    for i in range(start, end):  
        _start = datetime(year = start, month= mon, day=1)
        _end = _start + relativedelta(months=5)
        _start = _start.strftime('%Y-%m')
        _end = _end.strftime('%Y-%m')
        start_df = df.loc[_start].head(1)
        end_df = df.loc[_end].tail(1)
        result = pd.concat([result, start_df, end_df], axis =0)
    
    result['rtn'] = 1
    for i in range(0, len(halloween_df),2):
        buy = halloween_df.iloc[i]['Open']
        sell = halloween_df.iloc[i+1]['Close']
        rtn = sell/buy
        result.iloc[i+1,-1] =rtn
    
    result['acc_rtn'] = result['rtn'].cumprod()
    acc_rtn = result.iloc[-1,-1]
    
    return result, acc_rtn

결과값 잘 나옴~!