【问题标题】:I have a dataframe table with a ticker column and a date column. I want to calculate the price of the ticker at the corresponding date我有一个带有代码列和日期列的数据框表。我想计算相应日期的股票价格
【发布时间】:2022-01-09 17:01:39
【问题描述】:

这里是指定为df的表格:

id ticker date
1 PLTR 2022-01-07
2 GME 2022-01-06
3 AMC 2022-01-06
4 GOOD 2022-01-07
5 GRAB 2022-01-07
6 ALL 2022-01-06
7 FOR 2022-01-06

我想要这样的东西:

id ticker date Price
1 PLTR 2022-01-07 $16.56
2 GME 2022-01-06 $131.03
3 AMC 2022-01-06 $22.46
4 GOOD 2022-01-07 $24.76
5 GRAB 2022-01-07 $6.81
6 ALL 2022-01-06 $122.40
7 FOR 2022-01-06 $21.26

我试过 df['Price'] = yf.download(df['ticker'],df['date'])['Close'] 使用雅虎财务工具但收到错误: AttributeError:“系列”对象没有属性“拆分”

我也尝试了 pandas_datareader(作为 web 导入),得到了同样的错误: df.assign(Price=web.DataReader(list(df.ticker('\n')), 'yahoo', list(df.date)))['Close']

任何建议/想法我做错了什么?

【问题讨论】:

  • 您编写代码的问题是d[f'ticker]df['date] 产生了一个熊猫系列对象。您需要逐行递增 df 以提取特定数据上某个项目的股票价格。
  • 您能否添加一些示例数据,所以您的问题是reproducible
  • 数据框正好是第一个表

标签: python pandas dataframe date


【解决方案1】:
import pandas as pd
import pandas_datareader.data as web

tickers = list(df.ticker)

prices = ( web.DataReader(tickers, data_source='yahoo', start=df.date.min().date(), end=df.date.max().date() )['Close']
   .reset_index()
   .melt(id_vars=['Date'])
   .rename(columns={'Symbols':'ticker', 'Date':'date'})
)

prices:
date ticker value
0 2022-01-06 00:00:00 PLTR 16.74
1 2022-01-07 00:00:00 PLTR 16.56
2 2022-01-06 00:00:00 GME 131.03
3 2022-01-07 00:00:00 GME 140.62
4 2022-01-06 00:00:00 AMC 22.46
5 2022-01-07 00:00:00 AMC 22.99
6 2022-01-06 00:00:00 GOOD 25.03
7 2022-01-07 00:00:00 GOOD 24.76
8 2022-01-06 00:00:00 GRAB 6.65
9 2022-01-07 00:00:00 GRAB 6.81
10 2022-01-06 00:00:00 ALL 122.4
11 2022-01-07 00:00:00 ALL 125.95
12 2022-01-06 00:00:00 FOR 21.26
13 2022-01-07 00:00:00 FOR 20.19

现在合并它们:

df.merge(prices, on=['ticker','date'], how='left')
id ticker date value
0 1 PLTR 2022-01-07 00:00:00 16.56
1 2 GME 2022-01-06 00:00:00 131.03
2 3 AMC 2022-01-06 00:00:00 22.46
3 4 GOOD 2022-01-07 00:00:00 24.76
4 5 GRAB 2022-01-07 00:00:00 6.81
5 6 ALL 2022-01-06 00:00:00 122.4
6 7 FOR 2022-01-06 00:00:00 21.26

【讨论】:

    猜你喜欢
    • 2019-06-18
    • 2021-01-26
    • 1970-01-01
    • 2021-11-18
    • 1970-01-01
    • 1970-01-01
    • 2018-04-02
    • 1970-01-01
    • 2019-04-10
    相关资源
    最近更新 更多