PYTHON笔记十二:通过yfinance获取股票信息并写入EXCEL文件中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import requests
import pandas as pd
import yfinance as yf
import time as tm

url = 'https://www.slickcharts.com/sp500'
headers = {"User-Agent" : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36'}
request = requests.get(url, headers = headers)
data = pd.read_html(request.text)[0]
#stk_list = data.Symbol
stk_list = data.Symbol.apply(lambda x: x.replace('.', '-'))
#print(stk_list)

stk_basic_data = yf.Ticker('AAPL').info
#print(stk_basic_data)
info_columns = list(stk_basic_data.keys())

stk_info_df = pd.DataFrame(index = stk_list.sort_values(), columns = info_columns)
#stk_info_df = stk_info_df.head(3)
#print(stk_info_df)

failed_list = []

for i in stk_info_df.index:
try:
print('processing: ' + i)
info_dict = yf.Ticker(i).info
columns_included = list(info_dict.keys())
#print(columns_included)
intersect_columns = [x for x in info_columns if x in columns_included]
#print(intersect_columns)
stk_info_df.loc[i,intersect_columns] = list(pd.Series(info_dict)[intersect_columns].values)
tm.sleep(2)
except:
failed_list.append(i)
continue
print(failed_list)
stk_info_df.to_csv('sp500.csv')
  • 本文作者:括囊无誉
  • 本文链接: python-12-yfinance-download/
  • 版权声明: 本博客所有文章均为原创作品,转载请注明出处!
------ 本文结束 ------
坚持原创文章分享,您的支持将鼓励我继续创作!