yahoofinancials icon indicating copy to clipboard operation
yahoofinancials copied to clipboard

Converting to xlsx from json?

Open andreastasia opened this issue 5 years ago • 2 comments

Hi everyone,

I am a very beginner in Python. I am using this package but I'd love to save the outputs in xlsx format (for a better reading). I saved the JSON outputs in files but the conversion using pandas or online converter is ugly.

What I would to do is to have an Excel file with per every row I have the different tickers and the columns are the different metrics, as below:

image

Is possibile to do in some ways?

Thank you! Andrea

andreastasia avatar Jan 28 '20 12:01 andreastasia

`from yahoofinancials import YahooFinancials

ticker = ['INC.MI', 'BSS.MI'] yahoo_financials = YahooFinancials(ticker)

keystatistics = yahoo_financials.get_key_statistics_data()

import json with open('data.json', 'w', encoding='utf-8') as f: json.dump(keystatistics, f, ensure_ascii=False, indent=4)`

This is my code, if it can help you.

andreastasia avatar Jan 28 '20 12:01 andreastasia

Instead of doing a json.dump(), you probably need to write a CSV file, then Excel can import the CSV. Something like:

headings = []
for t, d in keystatistics.items():
  headings.extend(d.keys())
headings = list(set(headings))
with open('data.csv', 'w', encoding='utf-8') as f:
  f.write('"ticker","%s"\n' % ('","'.join(headings),))
  for t, d in keystatistics.items():
    f.write('"%s"' % t)
    for h in headings:
      f.write(',"%s"' % (d.get(h) or '',))
    f.write('\n')

sylvandb avatar Mar 07 '20 03:03 sylvandb

@andreastasia you can also leverage the XlsxWriter package for this.

https://pypi.org/project/XlsxWriter/

JECSand avatar Jan 15 '23 19:01 JECSand