我很难把所有的东西都整理好。我想(1)从csv文件中提取股票行情列表(2) 在finviz.com中遍历所有股票代码,以获取某些关键数据点(3) 将所有数据提取到另一个csv文件中进行更多分析。这是我到目前为止的代码
import pandas as pd
from bs4 import BeautifulSoup as bs
import requests
import csv
import time
import datetime
from datetime import datetime as dt
Symbol = []
with open('shortlist.csv') as csvDataFile:
csvReader = csv.reader(csvDataFile)
for row in csvReader:
Symbol.append(row[0])
def get_fundamental_data(df):
for symbol in df.index:
try:
url = 'http://finviz.com/quote.ashx?t=' + symbol.lower()
soup = bs(requests.get(url).content, features='html5lib')
for m in df.columns:
df.loc[symbol, m] = fundamental_metric(soup, m)
except Exception, e:
print (symbol, 'not found')
return df
def fundamental_metric(soup, metric):
return soup.find(text=metric).find_next(class_='snapshot-td2').text
metric = [ # 'Inst Own',
# 'Insider Own',
'Price',
'Shs Outstand',
'Shs Float',
'Short Float',
'Short Ratio',
'Book/sh',
'Cash/sh',
'Rel Volume',
'Earnings',
'Avg Volume',
'Volume',
]
df = pd.DataFrame(index=symbol, columns=metric)
df = get_fundamental_data(df)
print df
df.to_csv('finviz_' + time.strftime('%Y-%m-%d') + '.csv')
附件是要导入的my shortlist.csv:enter image description here
我得到的错误是: enter image description here
我在Pycharm上使用python3
结果应该是这样的: enter image description here
您的“符号”定义在函数
get_fundamental_data()
不能在for循环或函数外使用“symbol”
这三种方法中的一种会让你非常接近你想要的位置
方法1:
方法2:
方法3:
相关问题 更多 >
编程相关推荐