tushare获取某日所有股票数据,并计算炸板率
时间: 2025-01-01 10:31:40 浏览: 24
### 使用 Tushare 获取特定日期所有股票的数据并计算炸板率
为了实现这一目标,首先需要安装并初始化 Tushare 库。接着,可以通过 `daily` 和 `trade_cal` 接口获取指定日期内所有股票的日线行情数据以及交易日历。对于炸板率的计算,则需关注涨停未封住的情况。
#### 安装和导入必要的库
```bash
pip install tushare numpy pandas
```
```python
import tushare as ts
import pandas as pd
from datetime import datetime, timedelta
```
#### 初始化 Tushare Pro API
```python
ts.set_token('your_tushare_pro_api_token')
pro = ts.pro_api()
```
#### 获取指定日期内的所有股票列表及其基本信息
```python
def get_all_stocks(trade_date):
df = pro.stock_basic(exchange='', list_status='L', fields='ts_code,symbol,name,list_date')
return df[df['list_date'] <= trade_date]
all_stocks_df = get_all_stocks(date)
print(all_stocks_df.head())
```
#### 获取单个股票的日线行情数据
```python
def fetch_daily_data(ts_code, trade_date):
try:
daily_data = pro.daily(ts_code=ts_code, start_date=trade_date, end_date=trade_date)
return daily_data.iloc[0] if not daily_data.empty else None
except Exception as e:
print(f"Error fetching {ts_code}: {e}")
return None
```
#### 批量获取多个股票的日线行情数据
```python
def batch_fetch_daily_data(stock_list, trade_date):
results = []
for index, row in stock_list.iterrows():
result = fetch_daily_data(row['ts_code'], trade_date)
if result is not None:
results.append(result)
return pd.DataFrame(results).reset_index(drop=True)
batched_results = batch_fetch_daily_data(all_stocks_df[['ts_code']], date)
print(batched_results.shape)
```
#### 计算炸板率
炸板是指开盘价达到涨跌停后又打开的现象。通常情况下,如果某只个股当天最高价等于前一日收盘价乘以1.1(即上涨10%),而最终收盘价低于这个价格,则认为发生了炸板现象。
```python
def calculate_breakout_rate(df):
previous_close_prices = {}
# 预处理前一天的价格信息
prev_day = (datetime.strptime(date, '%Y%m%d') - timedelta(days=1)).strftime('%Y%m%d')
pre_daily_data = pro.daily(trade_date=prev_day)
for _, item in pre_daily_data.iterrows():
previous_close_prices[item['ts_code']] = float(item['close'])
count_total = 0
count_breakouts = 0
for idx, record in df.iterrows():
code = record['ts_code']
close_price_today = float(record['close'])
high_price_today = float(record['high'])
if code in previous_close_prices and abs(high_price_today / previous_close_prices[code] - 1.1) < 1e-6 \
and close_price_today < high_price_today:
count_breakouts += 1
count_total += 1
breakout_rate = round(count_breakouts / max(1, count_total), 4)*100
return f'{breakout_rate}%'
rate = calculate_breakout_rate(batched_results)
print(rate)
```
阅读全文