使用python和tushare,1.选取前三年内的任意一天,如果当日上涨家数小于1700家,则这一天作为trade_date,2.从trade_date往前推90天,选出这90天内最高价是最低价的2倍以上的股票作为股票池,3.在trade_date当日如果,股票池股票收十字线,则买入,持有3天则卖出,4.起始资金1000万,每次最多买5只,打印出结果和收益曲线
时间: 2024-03-24 21:37:15 浏览: 56
tushare.rar_python 抓取股票_tushare实时数据_tushare抓取股票_股票 python_获取美股数据
好的,我会根据您的要求进行回答。首先,需要安装tushare模块,可以使用以下命令:
```python
!pip install tushare
```
然后,需要获取股票数据。以下是获取tushare数据的代码:
```python
import tushare as ts
# 设置tushare token
ts.set_token('your_token_here')
# 初始化pro接口
pro = ts.pro_api()
# 获取交易日历
trade_cal = pro.trade_cal(exchange='', start_date='20180101', end_date='20201231', fields='cal_date, is_open')
# 获取前三年内的任意一天作为trade_date
import random
trade_date = random.choice(trade_cal[trade_cal['is_open'] == 1].cal_date.tolist())
print('选定的交易日为:', trade_date)
# 获取trade_date前90天的数据
df = pro.daily(trade_date=trade_date, fields='ts_code, trade_date, open, high, low, close, pre_close, pct_chg')
# 筛选出trade_date前90天最高价是最低价的2倍以上的股票作为股票池
df['spread'] = df['high'] / df['low']
stock_pool = df[df['trade_date'] < trade_date].groupby('ts_code').filter(lambda x: x['spread'].max() >= 2)
print('股票池选取的股票数为:', len(stock_pool))
```
接下来,需要编写判断十字线的函数:
```python
# 判断是否是十字星线
def is_doji(df):
# 获取开盘价和收盘价
open_price = df.iloc[-2]['open']
close_price = df.iloc[-2]['close']
# 判断是否满足十字星线的条件
if abs(open_price - close_price) / (df.iloc[-3]['high'] - df.iloc[-3]['low']) <= 0.1 and \
min(open_price, close_price) > df.iloc[-3]['close']:
return True
else:
return False
```
然后,需要编写买卖股票的函数:
```python
# 买卖股票的函数
def trade(stock_pool, money):
# 获取当前时间的股票数据
df = pro.daily(trade_date=trade_date, ts_code=','.join(stock_pool['ts_code'].tolist()), fields='ts_code, trade_date, open, high, low, close, pre_close, pct_chg')
# 筛选出当天收十字线的股票
doji_stocks = []
for ts_code in stock_pool['ts_code'].tolist():
sub_df = df[df['ts_code'] == ts_code]
if is_doji(sub_df):
doji_stocks.append(ts_code)
# 如果没有股票收十字线,则不进行交易
if len(doji_stocks) == 0:
return money
# 计算每只股票的购买数量
num_per_stock = min(5, len(doji_stocks))
per_stock_money = money / num_per_stock
num_per_stock = [int(per_stock_money / sub_df.iloc[-1]['close']) for ts_code, sub_df in df[df['ts_code'].isin(doji_stocks)].groupby('ts_code')]
# 购买股票
for i, ts_code in enumerate(doji_stocks[:num_per_stock]):
sub_df = df[df['ts_code'] == ts_code]
buy_price = sub_df.iloc[-1]['close']
money -= num_per_stock[i] * buy_price
# 持有3天后卖出
sell_date = pro.trade_cal(exchange='', start_date=trade_date, end_date='20201231', fields='cal_date, is_open')
sell_date = sell_date[sell_date['is_open'] == 1].iloc[3]['cal_date']
df = pro.daily(trade_date=sell_date, ts_code=','.join(stock_pool['ts_code'].tolist()), fields='ts_code, trade_date, open, high, low, close, pre_close, pct_chg')
sell_money = 0
for ts_code, num in zip(doji_stocks[:num_per_stock], num_per_stock):
sub_df = df[df['ts_code'] == ts_code]
sell_price = sub_df.iloc[-1]['close']
sell_money += num * sell_price
return money + sell_money
```
最后,可以运行主程序,计算收益曲线:
```python
# 主程序
money = 100000000
profits = []
for i, row in trade_cal[trade_cal['cal_date'] >= trade_date].iterrows():
if row['is_open'] == 1:
# 计算收益
money = trade(stock_pool, money)
profit = (money - 100000000) / 100000000
profits.append(profit)
print('交易日:{},当前资产:{},收益率:{}%'.format(row['cal_date'], money, round(profit * 100, 2)))
# 绘制收益曲线
import matplotlib.pyplot as plt
plt.plot(profits)
plt.xlabel('交易日')
plt.ylabel('收益率')
plt.title('收益曲线')
plt.show()
```
希望对您有帮助!
阅读全文