大家好,这是我第一次来这里,我是 Python 的初学者。我正在编写一个程序,该程序根据另一个包含公司名称的 txt 文档(Watchlist)的输入,返回一个包含股票信息的 txt 文档(Watchlist Info.txt)。
为此,我写了3个函数,其中2个函数reuters_ticker(),stock_price()完成如下图:
def reuters_ticker(desired_search):
#from company name execute google search for and return reuters stock ticker
try:
from googlesearch import search
except ImportError:
print('No module named google found')
query = desired_search + ' reuters'
for j in search(query, tld="com.sg", num=1, stop=1, pause=2):
result = j
ticker = re.search(r'\w+\.\w+$', result)
return ticker.group()
股票价格:
def stock_price(company, doc=None):
ticker = reuters_ticker(company)
request = 'https://www.reuters.com/companies/' + ticker
raw_main = pd.read_html(request)
data1 = raw_main[0]
data1.set_index(0, inplace=True)
data1 = data1.transpose()
data2 = raw_main[1]
data2.set_index(0, inplace=True)
data2 = data2.transpose()
stock_info = pd.concat([data1,data2], axis=1)
if doc == None:
print(company + '\n')
print('Previous Close: ' + str(stock_info['Previous Close'][1]))
print('Forward PE: ' + str(stock_info['Forward P/E'][1]))
print('Div Yield(%): ' + str(stock_info['Dividend (Yield %)'][1]))
else:
from datetime import date
with open(doc, 'a') as output:
output.write(date.today().strftime('%d/%m/%y') + '\t' + str(stock_info['Previous Close'][1]) + '\t' + str(stock_info['Forward P/E'][1]) + '\t' + '\t' + str(stock_info['Dividend (Yield %)'][1]) + '\n')
output.close()
第三个函数watchlist_report()是我在以所需格式编写信息时遇到问题的地方。
因此,我的问题是:
1)为什么我的输出格式是这样的?
2) 我必须更改我的代码的哪一部分才能以我想要的格式进行书面输出?
关于如何清理我的代码以及我可以用来使我的代码更好的任何库的任何其他建议也非常感谢!
陪伴而非守候
相关分类