이동평균선의 크로스 표시
다음은 일정기간의 sk 하이닉스의 종가를 호출한 것입니다.
import numpy as np import pandas as pd import yfinance as yf import matplotlib.pyplot as plt plt.rcParams['font.family'] ='NanumGothic' plt.rcParams['axes.unicode_minus'] =False
st=pd.Timestamp(2024,1, 10)
et=pd.Timestamp(2024, 9,25)
hy=pd.DataFrame(yf.download("000660.KS",st, et)["Close"])
hy.head(3)
| Close | |
|---|---|
| Date | |
| 2024-01-10 | 133500.0 |
| 2024-01-11 | 136000.0 |
| 2024-01-12 | 134100.0 |
이동평균은 DataFame/Series.rolling(기간).mean() 함수를 사용하여 결정합니다.
hy["sm5"]=hy.Close.rolling(5).mean() hy["sm20"]=hy.Close.rolling(20).mean() hy=hy.dropna() hy.head(3)
| Close | sm5 | sm20 | |
|---|---|---|---|
| Date | |||
| 2024-03-07 | 164900.0 | 163260.0 | 153545.0 |
| 2024-03-08 | 171900.0 | 166400.0 | 155240.0 |
| 2024-03-11 | 166600.0 | 166420.0 | 156670.0 |
위 데이터 hy로부터 골든크로스(golden cross), 데드크로스(dead cross)를 결정하기 위해 np.where(조건) 함수를 사용합니다. 이 함수는 조건에 부합하는 인덱스를 반환합니다. 또한 이 결과에서 연이은 두 인덱스 차이가 1이상이 되면 두 이평선이 교차하는 첫 지점으로 파악합니다.
골든 크로스
gre= np.where(hy["sm5"]>hy["sm20"])[0]
gcross=[gre[0]]
for i in range(1, len(gre)):
if gre[i] - gre[i-1]>1:
gcross.append(gre[i])
print(gcross)
[2, 30, 63, 130]
데드 크로스
re= np.where(hy["sm5"]<hy["sm20"])[0]
dcross=[re[0]]
for i in range(1, len(re)):
if re[i] - re[i-1]>1:
dcross.append(re[i])
print(dcross)
[0, 28, 49, 108, 138]
위 결과를 그래프로 나타냅니다.
plt.figure(figsize=(10, 3))
plt.plot(hy.Close, ls="dotted",label="종가")
plt.plot(hy["sm5"], color="g", label="이평선5")
plt.plot(hy["sm20"], color="r", label="이평선20")
plt.scatter(hy.index[gcross],hy["sm5"][gcross], s=30, c="g", label="골든크로스")
plt.scatter(hy.index[dcross],hy["sm20"][dcross], s=30, c="r", label="데드크로스")
plt.xlabel("날짜")
plt.ylabel("주가")
plt.legend(loc="best")
plt.show()

댓글
댓글 쓰기