import pandas as pd import numpy as np import datetime import time #获取数据 df=pd.read_csv('C:/Users/HXWD/Desktop/000001.csv',encoding='gbk') df.columns=['date','code','name','close','high','low','open','preclose', 'change','change_per','volume','amt'] df=df[['date','open','high','low','close','volume','amt']] df.head() def get_SAR(df,N=10,step=2,maxp=20): sr_value=[] sr_up=[] ep_up=[] af_up=[] sr_down=[] ep_down=[] af_down=[] for i in range(len(df)): if i >=N: if len(sr_up)==0 and len(sr_down)==0: if df.ix[i,'close']>df.ix[0,'close']: #标记为上涨趋势 sr0=df['low'][0:i].min() af0=0.02 ep0=df.ix[i,'high'] sr_up.append(sr0) ep_up.append(ep0) af_up.append(af0) sr_value.append(sr0) if df.ix[i,'close']<=df.ix[0,'close']: #标记为上涨趋势 sr0=df['high'][0:i].max() af0=0.02 ep0=df.ix[i,'high'] sr_down.append(sr0) ep_down.append(ep0) af_down.append(af0) sr_value.append(sr0) if len(sr_up)>0: if df.ix[i-1,'low']>sr_up[-1]: sr0=sr_up[-1] ep0=df['high'][-len(sr_up):].max() if df.ix[i,'high']>df['high'][-(len(sr_up)-1):].max() : af0=af_up[-1]+0.02 if df.ix[i,'high']<=df['high'][-(len(sr_up)-1):].max() : af0=af_up[-1] sr=sr0+af0*(ep0-sr0) sr_up.append(sr) ep_up.append(ep0) af_up.append(af0) sr_value.append(sr) print('上涨sr0={},ep0={},af0={},sr={}'.format(sr0,ep0,af0,sr)) if df.ix[i-1,'low']<=sr_up[-1]: ep0=df['high'][-len(sr_up):].max() sr0=ep0 af0=0.02 sr_down.append(sr0) ep_down.append(ep0) af_down.append(af0) sr_value.append(sr0) sr_up=[] ep_up=[] af_up=[] if len(sr_down)>0: if df.ix[i-1,'high']<sr_down[-1]: sr0=sr_down[-1] ep0=df['low'][-len(sr_down):].max() if df.ix[i,'low']<df['low'][-(len(sr_down)-1):].max() : af0=af_down[-1]+0.02 if df.ix[i,'low']>=df['low'][-(len(sr_down)-1):].max() : af0=af_down[-1] sr=sr0+af0*(ep0-sr0) sr_down.append(sr) ep_down.append(ep0) af_down.append(af0) sr_value.append(sr) print('下跌sr0={},ep0={},af0={},sr={}'.format(sr0,ep0,af0,sr)) if df.ix[i-1,'high']>=sr_down[-1]: ep0=df['low'][-len(sr_up):].max() sr0=ep0 af0=0.02 sr_up.append(sr0) ep_up.append(ep0) af_up.append(af0) sr_value.append(sr0) sr_down=[] ep_down=[] af_down=[] return sr_value sar=get_SAR(df)
#测试下来看,似乎中间逻辑有问题,有时间进一步修改