一、介绍

Tushare是一个免费、开源的python财经数据接口包。

安装包:
pip install tushare


二、简单策略

输出该股票所有收盘比开盘上涨3%以上的日期。输出该股票所有开盘比前日收盘跌幅超过2%的日期。

假如我从2010年1月1日开始,每月第一个交易日买入1手股票,每年最后一个交易日卖出所有股票,到今天为止,我的收益如何?

importtushareastsdf=ts.get_k_data("600519",start="1990-01-01")df.to_csv("600519.csv",index=False)#写入文件中,得到股票历史数据信息#对股票信息进行策略分析importnumpyasnpimportpandasaspddf=pd.read_csv("600519.csv",index_col="date",parse_dates=["date"])#从600519.csv中读取数据,date列作为索引df[(df["close"]-df["open"])/df["open"]>0.03].index#收盘比开盘上涨3%的所有日期df[(df["open"]-df["close"].shift(1))/df["close"].shift(1)<-0.02].index#df["close"].shift(1)前一天收盘价df_monthly=df.resample("M").first()#每月的第一个交易日,日期看着是最后一天,数据是第一天的df_yearly=df.resample("A").last()#每年的最后一个交易日df_yearly=df_yearly.iloc[:-1,:]#去掉最后一行,因为本年最后还没到,取得是昨天的数据cost=0num=0foryearinrange(2010,2019):cost+=(df_monthly[str(year)]["open"]*100).sum()#df_monthly[str(year)]["open"]每月的开盘价买进num=100*len(df_monthly[str(year)]["open"])#每月买一手,一手是100股ifyear!=2018:cost-=df_yearly[str(year)]["open"][0]*num#卖出股票,抵消花费num=0cost-=num*df["close"].iloc[-1]print(-cost)#df.resample("W").mean()#每周的平均值#df.resample("W").first()#每周的第一天

三、双均线策略

均线:对于每一个交易日,都可以计算出前N天的移动平均值,然后把这些移动平均值连起来,成为一条线,就叫做N日移动平均线。

移动平均线常用线有5天、10天、30天、60天、120天和240天的指标。

5天和10天的是短线操作的参照指标,称做日均线指标;

30天和60天的是中期均线指标,称做季均线指标;

120天、240天的是长期均线指标,称做年均线指标。

金叉:短期均线上穿长期均线

死叉:短期均线下穿长期均线


策略:分析5日均线和30日均线,在金叉把所有钱(开始有100000元)买入股票,死叉抛出所有股票

importnumpyasnpimportpandasaspdimportmatplotlib.pyplotaspltimporttushareastsdf["ma5"]=np.nandf["ma30"]=np.nan#foriinrange(4,len(df)):#df.loc[df.index[i],"ma5"]=df["close"][i-4:i+1].mean()#foriinrange(29,len(df)):#df.loc[df.index[i],"ma30"]=df["close"][i-29:i+1].mean()df["ma5"]=df["open"].rolling(5).mean()#5日双均线df["ma30"]=df["open"].rolling(30).mean()#30日双均线#处理数据:丢掉nan并取到需要的时间段df=df.dropna()df=df["2010-01-01":]#取到金叉和死叉的值golden_cross=[]death_cross=[]#foriinrange(1,len(df)):#ifdf["ma5"][i]>=df["ma30"][i]anddf["ma5"][i-1]<df["ma30"][i-1]#5日均线作天小于30日均线,在今天大于等于30日均线#golden_cross.append(df.index[i].to_pydatetime())##ifdf["ma5"][i]<=df["ma30"][i]anddf["ma5"][i-1]>df["ma30"][i-1]#5日均线昨天大于30日均线,在今天小于等于30日均线#death_cross.append(df.index[i].to_pydatetime())sr1=df["ma5"]<df["ma30"]sr2=df["ma5"]>=df["ma30"]death_cross=df[sr1&sr2.shift(1)].indexgolden_cross=df[~((sr1)|(sr2.shift(1)))].index#golden_cross=df[((~sr1)&(~sr2.shift(1)))].index#把金叉和死叉合并起来,一个金叉接着一个死叉排序sr1=pd.Series(1,index=golden_cross)sr2=pd.Series(0,index=death_cross)sr=sr1.append(sr2).sort_index()first_money=100000money=first_moneyhold=0#有多少股的股票foriinrange(0,len(sr)):p=df["open"][sr.index[i]]#单股价格ifsr.iloc[i]==1:#金叉buy=(money//(100*p))#可以买多少手股票hold+=buy*100#股票数money-=buy*100*p#剩余多少钱else:money+=hold*p#卖出股票hold=0p=df["close"][-1]now_money=hold*p+moneyprint(now_money)