매매 여부를 결정하는 %를 정해야하는데요. 낮으면 자주 거래가 일어나겠지만 큰 파동의 경우에 적게 먹을 수 밖에 없고, 높으면 거래가 자주 일어나지 않기 때문에 잔파동은 무시하게 됩니다. 어떤 결과가 나올지는 돌려봐야 알 수 있을 것 같습니다.
어제 작업한 코드를 함수화하여 percent 값을 입력으로 받을 수 있도록 수정을 합니다.
def simulation(df, code, percent, save=0) :
### init
init_invest = 1000000
extra_start = 3000000
extra_inv = extra_start
sell_perc = 1+percent/100 # 입력%이상이면 매도
buy_perc = 1-percent/100 # 입력%이하이면 매수
init_qty = init_invest / df.iloc[0]['close']
qty = []
sell_qty = []
cur_value = []
sell_amount = []
buy_qty = []
buy_amount = []
pre_qty = init_qty
total_inv = init_invest
for i in range(0,len(df)) :
tuple = df.iloc[i]
# sell 조건
if tuple['close']*pre_qty > init_invest * sell_perc :
sell_vol = (tuple['close']*pre_qty-init_invest)/tuple['close'] # close가격으로 판다
new_vol = pre_qty - sell_vol
pre_qty = new_vol
qty.append(new_vol)
gain = sell_vol*tuple['close']
extra_inv += gain
cur_value.append(new_vol*tuple['close'])
sell_qty.append(sell_vol)
sell_amount.append(sell_vol*tuple['close'])
buy_qty.append(0)
buy_amount.append(0)
elif tuple['close']*pre_qty < init_invest * buy_perc :
buy_vol = (init_invest-tuple['close']*pre_qty)/tuple['close'] # close가격으로 판다
new_vol = pre_qty + buy_vol
pre_qty = new_vol
qty.append(new_vol)
extra = buy_vol*tuple['close']
extra_inv -= extra
cur_value.append(new_vol*tuple['close'])
sell_qty.append(0)
sell_amount.append(0)
buy_qty.append(buy_vol)
buy_amount.append(buy_vol*tuple['close'])
else :
qty.append(pre_qty)
cur_value.append(pre_qty * tuple['close'])
sell_qty.append(0)
sell_amount.append(0)
buy_qty.append(0)
buy_amount.append(0)
df['qty'] = qty
df['cur_value'] = cur_value
df['sell_qty'] = sell_qty
df['sell_amount'] = sell_amount
df['buy_qty'] = buy_qty
df['buy_amount'] = buy_amount
# 최근 데이터
if save :
print("initial: ", format(int(init_invest), ",d"))
print("additional inv :", format(int(extra_inv),",d"))
num_buy = len(df[df['buy_amount']>0])
num_sell = len(df[df['sell_amount']>0])
if save :
print("# trading: buy ", format(int(num_buy), ",d"), "sell :", format(int(num_sell), ",d"))
# 최근 거래데이터로 현 자산 구하기
tuple = df.iloc[len(df)-1]
cur_total = tuple['close'] * pre_qty
diff = extra_inv - extra_start
if diff < 0 :
base = init_invest + diff * -1
else :
base = init_invest
print("profit[", format(percent,"2d"), "] ", format(int(diff), ",d"), "earning :", format(diff/(base)*100, "4.2f"),"%")
if save :
df.to_excel('.\\{}.xlsx'.format(code+interval))
return diff
이 후 다양한 퍼센트(1-20%)를 입력하면서 그 결과를 보도록 하겠습니다.
for i in range(1, 21) : # 1% - 20%까지
diff = simulation(df, code, i)
검증데이터는 Kodex200 2020년 3월 1일 부터 4월 6일 까지 60분 데이터를 대상으로 합니다.
- 3/2일 종가 27,090
- 4/6일 종가 24,540
- 3/2일 종가에 사서 계속 보유시 : -9.4%
기간이 짧아서 그런지 계속 보유한 경우와 매매를 한 경우가 비슷한 수익률을 보여주는군요. 매매 기준 %를 높일 수록 수익률은 나빠지는 경향을 보이고 있습니다. 이것은 일반적인 상황은 아니고 주어진 데이터에서는 이런 결과가 나왔다는 의미입니다.
기간을 좀 길게해보면 어떤 결과가 나올까요?
검증데이터는 Kodex200 2020년 1월 2일 부터 4월 3일 까지 일 데이터를 대상으로 합니다.
- 1/2일 종가 29,410
- 4/3일 종가 23,600
- 1/2일 종가에 사서 계속 보유시 : -19.7%
결과가 비슷하게 나오는군요. 그냥 보유하고 있는 경우보다는 수익률이 좋지만 정액 투자법이 하락시에 선방을 하는 것은 아닌 것 같습니다. 물론 이런 상태에서 약간의 변동을 주면서 오래 지속된다면 수익률은 개선이 될 것 같습니다.
매매 전략에 대해서는 좀 더 고민을 해 봐야 할 것 같습니다.
다음에는 이베스트증권에서 실제 거래하는 예를 소개하도록 하겠습니다.
JCAR 4월 구독보팅입니다.
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
와..천재십니다....
자동매매좋아보이네요
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit