温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

tushare做量化投资分析

发布时间:2020-07-07 22:17:53 来源:网络 阅读:4132 作者:宋鹏超 栏目:编程语言

一、介绍

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

安装包:

pip install tushare


二、简单策略

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

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

import tushare as ts

df = ts.get_k_data("600519",start="1990-01-01")
df.to_csv("600519.csv",index=False)                 #写入文件中,得到股票历史数据信息



#对股票信息进行策略分析
import numpy as np
import pandas as pd
df = 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=0
num=0
for year in range(2010,2019):
    cost += (df_monthly[str(year)]["open"] *100 ).sum()           #df_monthly[str(year)]["open"] 每月的开盘价买进
    num= 100 * len(df_monthly[str(year)]["open"])                 #每月买一手,一手是100股
    if year !=2018:
        cost -= df_yearly[str(year)]["open"][0] *num              #卖出股票,抵消花费
        num = 0
cost -= 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元)买入股票,死叉抛出所有股票

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import tushare as ts
df["ma5"]=np.nan
df["ma30"]=np.nan

# for i in range(4,len(df)):
#     df.loc[df.index[i],"ma5"] = df["close"][i-4:i+1].mean()
# for i in range(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 = []
# for i in range(1,len(df)):
#     if df["ma5"][i] >= df["ma30"][i]  and  df["ma5"][i-1] < df["ma30"][i-1]          #5日均线作天小于30日均线,在今天大于等于30日均线
#         golden_cross.append(df.index[i].to_pydatetime())
#
#     if df["ma5"][i] <= df["ma30"][i] and df["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)].index
golden_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=100000
money= first_money
hold=0                             #有多少股的股票
for i in range(0,len(sr)):
    p = df["open"][sr.index[i]]        #单股价格
    if sr.iloc[i] == 1:            #金叉
        buy=(money// (100*p))     #可以买多少手股票
        hold += buy*100          #股票数
        money-= buy*100*p         #剩余多少钱
    else:
        money += hold*p          #卖出股票
        hold = 0
p = df["close"][-1]
now_money= hold*p +money
print(now_money)





向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI