나는 이것을 제목으로 지정하는 방법을 정말로 몰랐지만 내 질문은 다음과 같습니다. 기본 SMA 크로스 오버로 거래 알고리즘을 만들고 있습니다. 코드는 다음과 같습니다.
import pandas as pd
import pandas_datareader as data
import datetime as dt
import numpy as np
start = dt.datetime(2017, 1, 1)
end = dt.datetime(2020, 1, 20)
d = data.get_data_yahoo('URI', start, end)
d['sma50'] = np.round(d['Close'].rolling(window=2).mean())
d['sma200'] = np.round(d['Close'].rolling(window=14).mean(), decimals = 2)
d['200-50'] = d['sma200'] - d['sma50']
_buy = -2
d['Crossover_Long'] = np.where(d['200-50'] < _buy, 1, 0)
d['buy'] = np.where(d['Crossover_Long']==1, 'buy', 'sell')
pd.set_option('display.max_rows', 400)
d.drop(['High', 'Low', 'Volume', 'Adj Close', 'Open'], axis=1, inplace=True)
d.dropna(inplace=True)
d.head()
따라서 처음 5 개 행은 다음과 같습니다.
Close sma50 sma200 200-50 Crossover_Long buy
Date
2017-01-23 110.110001 111.0 109.04 -1.96 0 sell
2017-01-24 113.610001 112.0 109.35 -2.65 1 buy
2017-01-25 114.260002 114.0 109.67 -4.33 1 buy
2017-01-26 127.059998 121.0 110.87 -10.13 1 buy
2017-01-27 128.259995 128.0 112.22 -15.78 1 buy
1이 있으면 매수해야하고 0이 있으면 매도해야합니다. 이제 문제는 sma2가 sma14보다 높을 때 1을 계속 쓰는 대신 크로스 오버가있을 때 1 만 인쇄하도록하는 방법입니다. 다음 크로스 오버까지 0 inbetween. 어떤 아이디어? 감사!
시리즈 에서 diff()
메소드를 사용할 수 있습니다. Crossover_Long
이미 0 또는 1로 코딩 되었기 때문에 상태가 변경 될 때 한 행만 1 또는 -1의 diff를 얻습니다. 그런 다음 0이 아닌 행을 찾아 그에 따라 플래그를 지정하십시오.
d['Crossover_Long_Change']=d.Crossover_Long.diff()
# code it as 1 where the value is not 0 (i.e. there is a change)
d['Crossover_Long_Change']=d['Crossover_Long_Change'].fillna(0).map(lambda x: 1 if x!=0 else 0)
d.head()
Close sma50 sma200 200-50 Crossover_Long buy Crossover_Long_Change
Date
2017-01-23 110.110001 111.0 109.04 -1.96 0 sell 0
2017-01-24 113.610001 112.0 109.35 -2.65 1 buy 1
2017-01-25 114.260002 114.0 109.67 -4.33 1 buy 0
2017-01-26 127.059998 121.0 110.87 -10.13 1 buy 0
2017-01-27 128.259995 128.0 112.22 -15.78 1 buy 0
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다