스파르타/파이썬

파이썬 _ 04주차 _ 백테스팅1 _ 단기/장기이평선

옒르 2023. 1. 19. 10:48

1) 단기 / 장기이평선 구하기

df = fdr.DataReader('005930','2018')

df = df[['Close']].copy()

df['ma_1'] = df['Close'].rolling(3).mean().shift(1)
df['ma_2'] = df['Close'].rolling(10).mean().shift(1)

df.head(30)

 

 

2) 적절한 값으로 수정하기

df = fdr.DataReader('005930','2018')

df = df[['Close']].copy()

df['ma_1'] = df['Close'].rolling(3).mean().shift(1)
df['ma_2'] = df['Close'].rolling(10).mean().shift(1)

df['action'] = np.where(df['ma_1'] > df['ma_2'], 'buy', 'sell')

df.iloc[-1,-1] = 'sell'

cond1 = (df['action'] == 'buy') & (df['action'].shift(1) == 'sell')
cond2 = (df['action'] == 'sell') & (df['action'].shift(1) == 'buy')

df_buy = df[cond1].reset_index()
df_buy.columns = ['날짜','종가(buy)','이평값1','이평값2','액션']

df_sell = df[cond2].reset_index()
df_sell.columns = ['날짜','종가(sell)','이평값1','이평값2','액션']

df_result = pd.concat([df_buy,df_sell],axis=1)

df_result['수익률'] = df_result['종가(sell)'] / df_result['종가(buy)']

(df_result[['수익률']].cumprod().iloc[-1,-1] - 1)*100

 

 

3) 함수로 만들어두기

def get_return_sl(code,short,long) :
   df = fdr.DataReader(code,'2018')

   df = df[['Close']].copy()

   df['ma1']=df['Close'].rolling(short).mean().shift(1)
   df['ma2']=df['Close'].rolling(long).mean().shift(1)

   df['action'] = np.where(df['ma1'] > df['ma2'],'buy','sell')

   df.iloc[-1,-1] = 'sell'

   cond_1=(df['action']=='buy') & (df['action'].shift(1) =='sell')
   cond_2=(df['action']=='sell') & (df['action'].shift(1) =='buy')

   df_buy = df[cond_1].reset_index()
   df_buy.colums=['date','close','ma1','ma2','action']

   df_sell = df[cond_2].reset_index()
   df_sell.colums=['date','close','ma1','ma2','action']

   df_result = pd.concat([df_buy,df_sell],axis=1)

   df_result['수익률'] = df_sell['Close'] / df_buy['Close']

   df_final = (df_result[['수익률']].cumprod().tail(1)-1)*100
   df_final['단기'] = short
   df_final['장기'] = long

  return df_final

+ if ) get_return_sl('005930',6,30)