You have your indentation wrong:
import requests
import pandas as pd
all_records = []
records = []
tickers = ['A','AAL','AAPL']
url_metrics = 'https://stockrow.com/api/companies/{}/financials.json?ticker={}&dimension=Q§ion=Metrics'
indicators_url = 'https://stockrow.com/api/indicators.json'
# create a list from all tickers
for s in tickers:
indicators = {i['id']: i for i in requests.get(indicators_url).json()}
all_records = []
for d in requests.get(url_metrics.format(s,s)).json():
d['id'] = indicators[d['id']]['name']
all_records.append(d)
graham_number = next(d for d in all_records if 'Graham Number' in d['id'])
earning_yield = next(d for d in all_records if 'Earnings Yield' in d['id'])
nav = next(d for d in all_records if 'Net Current Asset Value' in d['id'])
# extract data from all tickers list and convert to a dataframe
for (k1, v1), (_, v2), (_, v3) in zip(nav.items(), earning_yield.items(), graham_number.items()):
if k1 in ('id'):
continue
records.append({
'symbol' : s,
'date' : k1,
'net_current_asset_value': v1,
'earnings_yield': v2,
'gramham_number': v3
})
df = pd.DataFrame(records)
print(df)
df.to_csv('data.csv', index=False)
Print:
symbol date net_current_asset_value earnings_yield gramham_number
0 A 2020-07-31 -1320000000.0 0.0233 28.5032
1 A 2020-04-30 -1516000000.0 0.0288 27.6998
2 A 2020-01-31 -1551000000.0 0.0297 29.3613
3 A 2019-10-31 -1515000000.0 0.0448 33.9611
4 A 2019-07-31 -421000000.0 0.0486 33.9655
.. ... ... ... ... ...
113 AAPL 2011-12-31 6144000000.0 0.0864 9.933
114 AAPL 2011-09-30 5232000000.0 0.0735 8.1677
115 AAPL 2011-06-30 9483000000.0 0.0763 7.4198
116 AAPL 2011-03-31 13570000000.0 0.0611 6.3801
117 AAPL 2010-12-31 11851000000.0 0.0564 5.5731
[118 rows x 5 columns]
And creates data.csv
:
CLICK HERE to find out more related problems solutions.