可以保存计算值在数据框架中导致计算值

发布于 2025-02-12 15:23:44 字数 794 浏览 0 评论 0原文

我正在构建一个数据框架,其中包含来自Yahoo Finance的交易数据。

当我尝试计算每个股票的循环返回时,只有最后一个结果保存在数据框架中,而其余的股票则为NAN。

我认为,除最后一张股票外,每个股票都覆盖了计算的回报,但不知道发生这种情况的原因是什么。

这是我的代码:

  1. 来自Yahoo Finance的加载数据:
trading_df = pd.DataFrame()

for stock in test_stocks:
    st = web.DataReader(stock, 'yahoo', start, end)
    st['Symbol'] = stock
    trading_df = trading_df.append(st)
  1. 计算返回:

for stock in test_stocks:
    trading_df['Return'] = trading_df[trading_df['Symbol'] == stock]['Adj Close'].pct_change(1)
  1. 结果:

“渲染数据”

预先感谢。

I'm building a dataframe which contains trading data from Yahoo Finance.

When I'm trying to compute Return using for loop for each stock, only the last result is saved in dataframe, while rest of the stocks are Nan.

I assume that computed returns are overwrite for every stock except the last one, but have no idea what is the reason for that occurrence.

Here's my code:

  1. Load data from Yahoo Finance:
trading_df = pd.DataFrame()

for stock in test_stocks:
    st = web.DataReader(stock, 'yahoo', start, end)
    st['Symbol'] = stock
    trading_df = trading_df.append(st)
  1. Computing Return:

for stock in test_stocks:
    trading_df['Return'] = trading_df[trading_df['Symbol'] == stock]['Adj Close'].pct_change(1)
  1. The result:

Rendered data

Thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

相守太难 2025-02-19 15:23:44

分配值时,您需要切片框架

trading_df.loc[trading_df['Symbol'] == stock, 'Return'] = trading_df[trading_df['Symbol'] == stock]['Adj Close'].pct_change(1)

You need to slice the dataframe when assigning values

trading_df.loc[trading_df['Symbol'] == stock, 'Return'] = trading_df[trading_df['Symbol'] == stock]['Adj Close'].pct_change(1)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文