请求协助:将指定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
requestslibrary to send a GET request to the Morningstar API. Addingresponse.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
datetimetype 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
相关产品推荐
相关产品推荐

