我能够查看单个股票数据,但不确定如何使用循环将数据保存到MktSmithData.csv文件。
此外,我使用两个df框架变量,不确定这是否是最好的方法,我认为有一个更好的方法来做我正在做的事情。
需要保存股票,GR,EPR,基金价值观在一个csv文件。感谢任何帮助。谢谢你,谢谢
代码:
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 25 13:43:22 2023
@author: eruku
"""
import pandas as pd
import requests
infile = 'C:/Volume/PythonProjects/WIP_Projects/Marketsmithindia/StocksList.txt'
outfile = 'C:/Volume/PythonProjects/WIP_Projects/Marketsmithindia/MktSmithData.csv'
timeout = 10
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36"
}
starturl = 'https://msi-gcloud-prod.appspot.com/gateway/simple-api/ms-india/instr/0/3023210/symboldetails.json?s=20180719&e=20230719&text='
endurl = '&lang=en&isConsolidated=0&ms-auth=3990+MarketSmithINDUID-Web0000000000+MarketSmithINDUID-Web0000000000+0+230325200706+-514613229'
# stock = 'TCS'
with open(infile, 'r') as IN, open(outfile, 'w') as OUT:
for stock in IN:
stock = stock.strip()
url = starturl + stock + endurl
r = requests.get(url, headers=headers)
try:
# line = '%s,%s,%s,%s' % (
# stock,
# )
df1 = pd.json_normalize(r.json()['response']['quarterlySalesAndEarningsInternational']['quarterlySalesAndEarningsOrigin'][0])
# df = pd.json_normalize(r.json()['response']['detailsGeneralInformationHeader'])
df2 = pd.json_normalize(r.json()['response']['detailsGeneralInformationHeader'])
GR = df2.loc[:,"industryGroupRank"]
EPR = df2.loc[:,"epsRank"]
Funds = df1.loc[:,"noOfFunds"]
df1.to_csv('MktSmithData.csv', index=False)
# print(line, file=OUT)
except KeyError as E:
print(stock, 'KeyError:', E)
# print(df)
print(GR)
print(EPR)
print(Funds)
字符串
1条答案
按热度按时间4dbbbstv1#
如果我理解正确的话,我们可以将每一行构建成一个列表,因为你在for循环中找到了值,并将其附加到另一个列表中。然后我们可以使用csv模块将列表的列表写入一个csv文件
字符串