使用python和tushare,起始资金100万,最多买三个票,起始时间是2021年,当一个股票一个月内上涨幅度超过50%,且在后面两月个内出现两根长下影线则买入,持有3天卖出,打印出买入和卖出列表
时间: 2024-03-14 09:47:27 浏览: 50
好的,让我来解答你的问题。
首先,需要安装tushare库和pandas库,使用以下命令安装:
```python
pip install tushare pandas
```
然后,我们可以按照以下步骤实现:
1. 导入所需库和模块
```python
import tushare as ts
import pandas as pd
```
2. 获取股票数据
```python
start_date = '20210101' # 起始时间
end_date = '20211231' # 结束时间
stocks = ['000001.SH', '000002.SH', '000003.SH'] # 股票代码
df = pd.DataFrame() # 创建空的DataFrame
for stock in stocks:
data = ts.get_k_data(stock, start=start_date, end=end_date)
data['code'] = stock # 添加股票代码列
df = df.append(data, ignore_index=True) # 将数据添加到DataFrame中
```
3. 根据条件筛选出买入信号
```python
buy_signals = []
for stock in stocks:
data = df[df['code'] == stock] # 筛选出当前股票的数据
for i in range(2, len(data)):
if data.loc[i, 'close'] > 1.5 * data.loc[i-1, 'close'] and \
data.loc[i-1:i, 'low'].min() < data.loc[i-1:i, 'open'].min() and \
data.loc[i-1:i, 'low'].min() < data.loc[i-1:i, 'close'].min():
buy_signals.append((stock, data.loc[i, 'date']))
```
4. 根据买入信号计算买入价格和卖出价格
```python
buy_list = []
sell_list = []
for signal in buy_signals:
stock = signal[0]
date = signal[1]
data = df[df['code'] == stock] # 筛选出当前股票的数据
buy_price = data[data['date'] == date]['open'].values[0] # 买入价格为当天开盘价
sell_price = data[data['date'] > date].iloc[2]['open'] # 卖出价格为买入后第3天的开盘价
buy_list.append((stock, date, buy_price))
sell_list.append((stock, data[data['date'] > date].iloc[2]['date'], sell_price))
```
5. 打印买入和卖出列表
```python
print('买入列表:')
for item in buy_list:
print(f'{item[0]} {item[1]} 买入价格:{item[2]:.2f}元')
print('卖出列表:')
for item in sell_list:
print(f'{item[0]} {item[1]} 卖出价格:{item[2]:.2f}元')
```
完整代码如下:
阅读全文