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

如何从股票详情字典创建DataFrame及提取收盘价生成DataFrame

How to Create a DataFrame from Stock Data Dictionary & Extract Closing Prices

Let's walk through this clearly—your f() function returns a dictionary where the key is the stock ticker (BP), and the value is structured stock data including dates, open/high/low/close prices, and volume. Here's how to turn this into a pandas DataFrame, specifically focusing on extracting closing prices.

1. First, Create a Full DataFrame from the Dictionary

First, make sure you have pandas installed and imported. Then we'll pull the data, structure it properly, and convert it to a DataFrame:

import pandas as pd

# Get the data from your f() function
stock_data = f()

# Extract the BP stock data (since that's the key in your example)
bp_stock_data = stock_data['BP']

# Convert to a DataFrame, setting 'date' as the index for time-series functionality
full_df = pd.DataFrame(bp_stock_data).set_index('date')

# Optional: Verify the output
print(full_df.head())

This will give you a complete DataFrame with all the stock metrics (open, high, low, close, volume) indexed by date, which is perfect for time-series analysis.

2. Extract Only Closing Prices into a DataFrame

If you only need the closing prices, you can either slice the full DataFrame we just created, or directly extract the 'close' values during the DataFrame creation:

Option 1: Slice from the Full DataFrame

# Extract just the 'close' column and keep it as a DataFrame (not a Series)
close_price_df = full_df[['close']]

# Check the result
print(close_price_df.head())

Option 2: Directly Create from the Raw Dictionary

If you want to skip creating the full DataFrame, you can pull the 'date' and 'close' values directly:

# Extract dates and close prices from the BP data
dates = bp_stock_data['date']
close_prices = bp_stock_data['close']

# Create a DataFrame with these two columns, set date as index
close_price_df = pd.DataFrame({'close': close_prices}, index=dates)

Both methods will give you a clean DataFrame focused solely on the daily closing prices for BP, indexed by date.

Quick Note on Data Structure

Looking at your sample data, ensure that the values for each metric (open, close, etc.) are lists/arrays that align with the dates—pandas relies on matching lengths to create the DataFrame correctly. If your f() function returns the data in a row-wise format (each entry is a day's data), you might need to adjust slightly, but the above code works for the column-wise structure you provided.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 03:39:57