You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python实现从Myfxbook API返回数据中筛选指定字段并分品种保存至TXT文件

Hey there! Great job fetching the community outlook data from the Myfxbook API already. Let's refine your approach to create those individual TXT files for each trading pair—you actually don't need that string conversion step, since working directly with the original list of dictionaries is way cleaner and easier.

Solution

Here's a straightforward way to extract the name, shortVolume, and longVolume fields and generate separate TXT files for each symbol:

Complete Code Snippet

# Assuming you already have Outlook_data from your API request (the list of symbols)
for symbol in Outlook_data:
    # Pull the required fields from the symbol dictionary
    symbol_name = symbol['name']
    short_volume = symbol['shortVolume']
    long_volume = symbol['longVolume']
    
    # Create a filename using the symbol's name (e.g., EURUSD.txt)
    filename = f"{symbol_name}.txt"
    
    # Write the data to the file using a context manager (ensures proper file handling)
    with open(filename, 'w') as output_file:
        output_file.write(f"Trading Symbol: {symbol_name}\n")
        output_file.write(f"Short Volume: {short_volume}\n")
        output_file.write(f"Long Volume: {long_volume}\n")

Breakdown of the Code

  • Loop through symbols: We iterate over each dictionary in your Outlook_data list—each dictionary holds all the data for a single trading pair.
  • Extract fields: Using direct key access (like symbol['name']), we grab exactly the values we need without having to parse strings (which avoids potential errors).
  • Generate files: The filename is built using the symbol's name, so each pair gets its own unique TXT file. The with statement takes care of opening and closing the file safely, even if something goes wrong.
  • Readable output: Each file contains clearly labeled lines so the data is easy to read at a glance.

Optional: Robust Error Handling

If you want to make the code more resilient (in case the API ever returns missing keys), use the get() method with default values. This prevents the code from crashing if a field is missing:

for symbol in Outlook_data:
    # Use get() to provide fallback values if keys are missing
    symbol_name = symbol.get('name', 'Unknown_Symbol')
    short_volume = symbol.get('shortVolume', 0.0)
    long_volume = symbol.get('longVolume', 0.0)
    
    filename = f"{symbol_name}.txt"
    with open(filename, 'w') as output_file:
        output_file.write(f"Trading Symbol: {symbol_name}\n")
        output_file.write(f"Short Volume: {short_volume}\n")
        output_file.write(f"Long Volume: {long_volume}\n")

内容的提问来源于stack exchange,提问作者Strahinja

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 18:17:36