尝试运用使用接口Tushare中的gethistdata()功能,结合数据文件"S50(1)csv"中的上证50股票代码,抓取这50只股票近一个月的日收盘指数。
时间: 2024-05-15 14:12:50 浏览: 126
好的,首先需要安装Tushare库,并导入所需的库和模块:
```
!pip install tushare
import tushare as ts
import pandas as pd
```
然后读取包含上证50股票代码的CSV文件,并提取股票代码:
```
df = pd.read_csv('S50(1).csv', encoding='gbk')
codes = df['代码'].tolist()
```
接下来使用Tushare中的get_hist_data()函数来获取近一个月的日收盘指数:
```
data = {}
for code in codes:
try:
hist_data = ts.get_hist_data(code, start='2021-08-01', end='2021-08-31')
data[code] = hist_data['close']
except Exception as e:
print(code, e)
```
最后将获取到的数据存储到一个CSV文件中:
```
df = pd.DataFrame(data)
df.to_csv('S50_hist_data.csv')
```
完整的代码如下:
```
!pip install tushare
import tushare as ts
import pandas as pd
df = pd.read_csv('S50(1).csv', encoding='gbk')
codes = df['代码'].tolist()
data = {}
for code in codes:
try:
hist_data = ts.get_hist_data(code, start='2021-08-01', end='2021-08-31')
data[code] = hist_data['close']
except Exception as e:
print(code, e)
df = pd.DataFrame(data)
df.to_csv('S50_hist_data.csv')
```
阅读全文