Python脚本问题:Morningstar财务比率导出至Excel失败
Hey there, fellow Python newbie! Let's break down those two headaches you're facing with downloading and writing Morningstar financial key ratios: converting the kr_ratios data to a format XlsxWriter can handle, and accessing the names of its sub-lists.
1. First: Figure Out What kr_ratios Actually Is
The good-morning module probably returns custom objects (not plain Python lists or dictionaries) for the ratios, which is why XlsxWriter can’t process them directly. Start by debugging to see the exact structure:
# Test with one stock first (don’t jump into the CSV loop yet!) print(type(kr_ratios)) # Tells you if it’s a list, custom class, etc. if isinstance(kr_ratios, list) and len(kr_ratios) > 0: print(dir(kr_ratios[0])) # Shows all attributes/methods of the first ratio item
This will reveal things like name, value, or group_name attributes you can use to extract data.
2. Convert kr_ratios to Native Python Types
Once you know the object’s attributes, turn the data into a list of dictionaries (super easy to work with for Excel):
Example Conversion (adjust based on your actual attributes):
# If each ratio has 'name' and 'value' attributes formatted_ratios = [] for ratio in kr_ratios: formatted_ratios.append({ "Ratio Name": ratio.name, "Value": ratio.value }) # If ratios are grouped (e.g., Profitability, Liquidity), capture group names too: # formatted_groups = [] # for group in kr_ratios: # group_data = { # "Group Name": group.group_name, # Replace with your actual group attribute # "Ratios": [{"Name": r.name, "Value": r.value} for r in group.ratios] # } # formatted_groups.append(group_data)
3. Write Formatted Data to Excel with XlsxWriter
Now that you have plain Python data, writing to Excel is a breeze:
import xlsxwriter # Create workbook and worksheet workbook = xlsxwriter.Workbook("morningstar_ratios.xlsx") worksheet = workbook.add_worksheet("Key Ratios") # Write header row header = ["Ratio Name", "Value"] worksheet.write_row(0, 0, header) # Write data rows for row_num, ratio in enumerate(formatted_ratios, start=1): worksheet.write(row_num, 0, ratio["Ratio Name"]) worksheet.write(row_num, 1, ratio["Value"]) # Close the workbook to save changes workbook.close()
4. Accessing Sub-List/Group Names
If kr_ratios is split into categories (like different ratio groups), use the group attribute you found earlier. For example:
# Loop through groups to get their names and inner ratios for group in kr_ratios: print(f"--- {group.group_name} ---") # Swap with your actual group name attribute for ratio in group.ratios: print(f"{ratio.name}: {ratio.value}")
Quick Newbie Tip
Test with one stock first (instead of looping through your entire CSV) to work out the kinks. Once that works, scale up to processing all stocks from greekstocks.csv.
内容的提问来源于stack exchange,提问作者AlexandrosB

