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

请求协助:将指定URL的共同基金时序数据导入Pandas DataFrame

Pull Morningstar Mutual Fund Time Series into Pandas DataFrame

Hey there! Let's get that Morningstar mutual fund data into a Pandas DataFrame so you can dive into your statistical analysis and plotting work. Here's a working code implementation, plus some key thinking behind the approach:

Code Implementation

import requests
import pandas as pd

# Fixed the URL (added missing & between currencyId and type parameters)
target_url = "http://tools.morningstar.it/api/rest.svc/timeseries_price/jbyiq3rhyf?currencyId=EUR&type=Morningstar&frequency=daily&startDate=2008-04-01&priceType=&outputType=COMPACTJSON&id=F00000YU62]2]0]FOITA $$ALL&applyTrackRecordExtension=true"

try:
    # Fetch the data via HTTP GET request
    response = requests.get(target_url)
    response.raise_for_status()  # Raise error if request fails (e.g., 404, 500)
    
    # Parse the compact JSON response (it's a 2D array: [["date", price], ...])
    raw_time_series = response.json()
    
    # Convert to DataFrame with meaningful column names
    fund_df = pd.DataFrame(raw_time_series, columns=["Date", "Price (EUR)"])
    
    # Clean up date format and set as index (critical for time series work)
    fund_df["Date"] = pd.to_datetime(fund_df["Date"])
    fund_df.set_index("Date", inplace=True)
    
    # Verify the output with the first few rows
    print("Sample data:")
    print(fund_df.head())

except requests.exceptions.RequestException as req_err:
    print(f"Failed to fetch data: {req_err}")
except ValueError as json_err:
    print(f"Failed to parse JSON: {json_err}")

Implementation Breakdown

  • HTTP Request Handling: We use the requests library to send a GET request to the Morningstar API. Adding response.raise_for_status() ensures we catch any HTTP errors (like invalid URLs or server issues) early.
  • JSON Parsing: The API returns COMPACTJSON, which is a simplified 2D array structure. This maps directly to a Pandas DataFrame—we just need to assign column names to make the data readable.
  • Time Series Preparation: Converting the date string to a datetime type and setting it as the index is essential for time-series-specific operations (like resampling, rolling averages, or plotting with proper date axes).
  • Error Handling: Wrapping the code in try/except blocks prevents crashes from network issues or unexpected API response formats, making the script more robust.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:33:14