使用Tushare筛选今天适合投资的股票tushare ID=418443
- 一.Tushare介绍
- 二.安装Tushare
- 三.编写代码
- 1、初始化tushare,并且获取所有股票信息。
- 2、收盘价跌破lower线,买入信号计算
- 3、收盘价超过upper线,卖出信号计算
- 4、遍历所有股票,找出符合买入和卖出信号的股票。
- 四.运行结果
一.Tushare介绍
Tushare是一个免费开源的python财经数据接口包。主要实现对股票数据等从数据采集、清晰加工和数据存储的过程。考虑到Python pandas包在金融量化分析中体现出的优势,Tushare返回的绝大部分的数据格式都是pandas DataFrame类型,非常便于用pandas/NumPy/Matplotlib进行数据分析和可视化。当然也可以通过Tushare的数据存储功能将数据保存到本地后用excel或关系数据库分析。
二.安装Tushare
方式1:pip install tushare
方式2:访问https://pypi.python.org/pypi/Tushare/下载安装
可以通过https://tushare.pro/register?reg=418443 注册,在个人中心中获取token值
token=‘你复制下来的token’
ts.set_token(token)
pro=ts.pro_api()
三.编写代码
本次使用pycharm软件作为python开发环境。
1、初始化tushare,并且获取所有股票信息。
token = '你复制下来的token'ts.set_token(token)pro = ts.pro_api(timeout=120)print(ts.__version__)data = pro.stock_basic(exchange='', list_status='L', fields='ts_code,symbol,name,area,industry,list_date')data.to_csv("csvfile\\stock_basic.csv")
2、收盘价跌破lower线,买入信号计算
def signal_buy(data_new, signal_all):temp = copy.deepcopy(signal_all)temp[temp <= 0] = Nonesignal_buy = []for index, row in temp.iterrows():if row[0] > 0:signal_buy.append(data_new[data_new.index == index]['low'] - 0.05)else:signal_buy.append(np.nan)return signal_buy
3、收盘价超过upper线,卖出信号计算
def signal_sell(data_new, signal_all):temp = copy.deepcopy(signal_all)temp[temp >= 0] = Nonesignal_sell = []for index, row in temp.iterrows():if row[0] < 0:signal_sell.append(data_new[data_new.index == index]['high'] + 0.05)else:signal_sell.append(np.nan)return signal_sell
4、遍历所有股票,找出符合买入和卖出信号的股票。
for index, row in data_list.iterrows(): # 遍历所有上市股票ts_code = row['ts_code']# print(ts_code, row['name'])df = get_daily(ts_code=ts_code, start_date=start_date)if df is None:continueif len(df) < 30:# print("股票代码:%s, 股票名称:%s has not enough data,skip..." % (ts_code, row['name']))continuedata_new = dfdata_new.index = pd.to_datetime(df.trade_date.astype(str))data_new.drop(axis=1, columns='trade_date', inplace=True)# 指定列data_new.columns = ['open', 'high', 'low', 'close', 'volume']data_new.sort_index(inplace=True)# 提取收盘价closed = data_new['close']upper, middle, lower = talib.BBANDS(closed, timeperiod=20, nbdevup=2, nbdevdn=2, matype=MA_Type.SMA)signal_all = signal_all_fn(data_new, upper, lower)# 判断最近的一天是否买卖点has_signal = signal_all.iat[len(signal_all)-1, 0]# 判断倒数第二天是否买卖点second_signal = signal_all.iat[len(signal_all)-2, 0]# 提取最后一天的日期last_date = signal_all['signal'].keys()[-1].strftime("%Y-%m-%d")if accept_datetime not in signal_all['signal'].keys():print("最近交易日(%s != %s)昨日,股票代码:%s,股票名称:%s,skip..." % (last_date, accept_date, ts_code, row['name']))continuelast_date = accept_datelast_close = round(list(data_new['close'])[-1], 2)last_upper = round(list(upper)[-1], 2)last_lower = round(list(lower)[-1], 2)if has_signal != 0:if (has_signal > 0) and (second_signal > 0): # 昨天是第一次跌穿,才买入,防止踩雷continue# 计算净资产收益率roe, profit_time = cal_profit(ts_code)if roe is None or (roe is not None and roe < MIN_ROE):continue# 计算市盈率和市净率pb, pe = cal_pbpe(ts_code)if pb is None or pe is None:continueif (has_signal > 0) and (second_signal <= 0): # 昨天是第一次跌穿,才买入,防止踩雷buy_df = buy_df.append({"代码": ts_code, "名称": row['name'], "行业": row['industry'], "收盘价": last_close, "上轨": last_upper, "下轨": last_lower, "净资产收益率": roe, "市盈率": pe, "市净率": pb}, ignore_index=True)print("买入时间:%s,股票代码:%s,股票名称:%s,行业:%s, 收盘价:%s, 上轨:%s, 下轨: %s, %s发布的季度净资产收益率:%s%%, 市盈率:%s, 市净率:%s" % (last_date, ts_code, row['name'], row['industry'], last_close, last_upper, last_lower, profit_time, roe, pe, pb))# 写入文件print("买入时间:%s,股票代码:%s,股票名称:%s,行业:%s, 收盘价:%s, 上轨:%s, 下轨: %s, %s发布的季度净资产收益率:%s%%, 市盈率:%s, 市净率:%s" % (last_date, ts_code, row['name'], row['industry'], last_close, last_upper, last_lower, profit_time, roe, pe, pb), file=fo_buy)elif has_signal < 0:sell_df = sell_df.append({"代码": ts_code, "名称": row['name'], "行业": row['industry'], "收盘价": last_close, "上轨": last_upper, "下轨": last_lower, "净资产收益率": roe, "市盈率": pe, "市净率": pb}, ignore_index=True)print("卖出时间:%s,股票代码:%s,股票名称:%s,行业:%s, 收盘价:%s, 上轨:%s, 下轨: %s, %s发布的季度净资产收益率:%s%%, 市盈率:%s, 市净率:%s" % (last_date, ts_code, row['name'], row['industry'], last_close, last_upper, last_lower, profit_time, roe, pe, pb))print("卖出时间:%s,股票代码:%s,股票名称:%s,行业:%s, 收盘价:%s, 上轨:%s, 下轨: %s, %s发布的季度净资产收益率:%s%%, 市盈率:%s, 市净率:%s" % (last_date, ts_code, row['name'], row['industry'], last_close, last_upper, last_lower, profit_time, roe, pe, pb), file=fo_sell)
四.运行结果
从下面的执行结果,可以方便筛选出今天适合买入或者卖出的股票信息: