mmyjh86

[YouTube] 벡테스팅 - 골든크로스 (가성)

Oct 17th, 2020
964
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. from pykrx import stock
  2. import numpy as np
  3. import pandas as pd
  4. from pandas import Series
  5.  
  6. def 장기_단기_이평선_수익률(df, Ns, Nl):
  7.     df = df[  [ '종가' ] ].copy()
  8.     df['ma_s'] = df['종가'].rolling( Ns ).mean( ).shift ( 1 )
  9.     df['ma_l'] = df['종가'].rolling( Nl ).mean( ).shift ( 1 )
  10.     cond = df['ma_s'] > df['ma_l']
  11.     df['status'] = np.where(cond, 1, 0)
  12.     df.iloc[-1, -1] = 0
  13.    
  14.     # 매수/매도 조건
  15.     매수조건 = (df['status'] == 1) & (df['status'].shift(1) != 1)
  16.     매도조건 = (df['status'] == 0) & (df['status'].shift(1) == 1)
  17.    
  18.     # 수익률 계산
  19.     수익률 = df.loc[매도조건, '종가'].reset_index(drop=True) / df.loc[매수조건, '종가'].reset_index(drop=True)
  20.     수익률 = 수익률 - 0.002
  21.     return 수익률.cumprod().iloc[-1]
  22.  
  23. df = stock.get_index_ohlcv_by_date("20200101", "20200831", "1001")
  24. df = df[  [ '종가' ] ]
  25.  
  26. result = [ ]
  27. for i in range(2, 17):
  28.     for j in range(30, 61):
  29.         result.append(장기_단기_이평선_수익률(df, i, j))
  30.  
  31. index = pd.MultiIndex.from_product([ range(2, 17), range(30, 61)  ])
  32. s = Series(result, index)
  33.  
  34. print(s.idxmax())
  35. print(s.max())
RAW Paste Data