官网
http://www.tushare.org
安装
pip install tushare
引用
import tushare
tushare.get_k_data('601318','1991-01-01') # 取K线历史数据
tushare.trade_cal() # 获取交易日信息
例子
1.获取某股票历史行情信息
import numpy as np
import pandas as pd
import matplotlib.pyplot ps plt
import tushare as ts
df = ts.get_k_data("600519",start="1988-01-01")
df.to_csv("600519.csv")
df = pd.read_csv("600519.csv",index_col='date',parse_dates=['date'])[['open','close','high','low']]
df
2.输出改股票所有收盘比开盘上涨3%以上的日期
df[(df['close']-df['open'])/df['open']>=0.03].index
3.输出改股票所有开盘比前日收盘幅度超过2%的日期
df[(df['open']-df['close'].shift(1))/df['close'].shift(1)<=-0.02].index
4.加入从2010年1月1日开始,每月第一个交易日买入1手股票,每年最后一个交易日卖出,至今为止收益如何
price_last = df['open'][-1] #最后一条股票的价格
df = df['2001-09':'2018-12'] #剔除首尾数据
df_monthly = df.resample("M").first()#每月第一个交易日
df_yearly = df.resample("A").last().[:-1]#每年最后一个交易日
cost_monthly = 0
hold = 0
for year in range(2001,2018):
cost_money +=df_monthly[str(year)][open].sum()*100 #每个月买100股
hold += len(df_monthly[str(year)]['open']) * 100
if year != 2017:
cost_money -= df_year[str(year)]['open'][0]*hold #每年最后一个交易日卖出
hold=0
print(cost_money)
cost_money -= hold * price_last
print(-cost_money)
5.获取股票数据计算该骨片的5日均线和30日均线
import numpy as np
import pandas as pd
import matplotlib.pyplot ps plt
import tushare as ts
df = pd.read_csv("601318.csv",index_col='date',parse_dates=['date'])['open','close','low','high']
df['ma5'] = np.nan #新加列
df['ma30'] = np.nan
#循环写法
for i in range(4,len(df)): #从第5行开始到最后
df.loc[df.index[i],'ma5'] = df['close'][i-4:i+1].mean() #每5个求平均并赋值
for i in range(29,len(df)):
df.loc[df.index[i],'ma30'] = df['close'][i-29:i+1].mean()
#rolling写法,滚动数据取值
df['ma5'] = df['close'].rolling(5).mean()
df['ma30'] = df['close'].rolling(30).mean()
6.使用matplotlib包绘制两条均线
df[['close','ma5','ma30']].plot()
plt.show()
df.loc['2012',['close','ma5','ma30']].plot() #只画一年
plt.show()
7.输出所有的金叉日期和死叉日期
df = df.dropna()
df = df['2010-01-01':] #截取数据
golden_cross = []
death_cross = []
#循环写法
for i in range(30,len(df)):#按天循环,从长期均线有值的数据开始
#今天的ma5>=ma30并且昨天的ma5小于ma30
if df['ma5'][i] >=df['ma30'][i] and df['ma5'][i-1]<df['ma30'][i-1]:
golden_cross.append(df.index[i].to_pydatetime())#保存金叉数据
#今天的ma5<=ma30并且昨天的ma5大于ma30
if df['ma5'][i] <=df['ma30'][i] and df['ma5'][i-1]>df['ma30'][i-1]:
death_cross.append(df.index[i].to_pydatetime())#保存死叉数据
#shift写法,不使用循环
str1 = df['ma5'] < df['ma30']
str2 = df['ma5'] >= df['ma30']
death_cross = df[str1 & str2.shift(1)].index
golden_cross = df[~(str1 | str2.shift(1))].index
8.如果从2010年开始,初始资金10万,金叉买入死叉卖出,到尽头为止的收入是多少
first_money = 100000 #初始资金
money = first_money
hold = 0 #持有股份数量
#日期排序
sr1 = pd.Series(1,index=golden_cross)
sr2 = pd.Series(0,index=death_cross)
sr = sr1.append(sr2).sort_index()
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['open'][-1] #最后一天开盘价
now_money = hold * p + money
print(now_money - first_money)
量化投资在线平台
聚宽,优矿,米筐,quantopian
开源框架:RQAlpha,QUANTAXIS