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

如何用Python结合yfinance对输入股票的TrailingPE求和并计算平均值

问题:计算股票列表中TrailingPE的总和与平均值

我正在学习Python,想练习基础金融分析。如何对从用户输入构建的股票列表中的TrailingPE(代码中的PEratio变量)求和并计算平均值?

以下是我的代码:

import yfinance as yf

#user input
list = input("Enter ticker(s): ")

#building a list
ticker_list = list.split(", ")
all_symbols  = " ".join(list)
all_symbols  = " ".join(ticker_list)
tickers = yf.Tickers(all_symbols)

#calling data
for ticker in ticker_list:
    price = tickers.tickers[ticker].info["currentPrice"]
    market_cap = tickers.tickers[ticker].info["marketCap"]
    PEratio = tickers.tickers[ticker].info["trailingPE"]
    FWPEratio = tickers.tickers[ticker].info["forwardPE"]
    print(ticker,"\nMarket cap:", market_cap,"\nShare Price:", price, "\nTrailingPE:", PEratio, "\nForward PE:", FWPEratio)

   
   #analysis: I would like to sum all the values for the PEratios and divide them by the list size to compute the average
  

    print(sum(PEratio["trailingPE"])/float(len(ticker_list))) #This isnt correct but is my thought process

补充说明:运行最后一行代码时出现如下错误:

Traceback (most recent call last):
  File "C:\Users\Sean\OneDrive\Programming\yfinance\multiples\test.py", line 24, in <module>
    print(sum(PEratio["trailingPE"])/float(len(ticker_list))) #This isnt correct but is my thought process
TypeError: 'float' object is not subscriptable

另外,当前代码会在每个股票下方单独打印结果,且是单个PE除以列表长度,而非总和除以列表长度。


解决方案

错误原因分析

  1. 类型错误:PEratio = tickers.tickers[ticker].info["trailingPE"]已经直接获取到了trailingPE的浮点数值,你再用PEratio["trailingPE"]去索引,相当于对float类型做字典操作,自然会报TypeError: 'float' object is not subscriptable。
  2. 逻辑错误:你在循环内部每次计算单个PE除以列表长度,这不是平均值的计算逻辑——平均值应该是所有PE的总和除以有效PE的数量(或者列表长度,视需求而定)。

修改后的代码

import yfinance as yf

# 用户输入
ticker_input = input("Enter ticker(s): ")

# 构建股票代码列表
ticker_list = ticker_input.split(", ")
all_symbols = " ".join(ticker_list)
tickers = yf.Tickers(all_symbols)

# 用于存储所有TrailingPE的列表
pe_values = []

# 获取并打印每个股票数据
for ticker in ticker_list:
    try:
        info = tickers.tickers[ticker].info
        price = info["currentPrice"]
        market_cap = info["marketCap"]
        PEratio = info["trailingPE"]
        FWPEratio = info["forwardPE"]
        
        print(f"{ticker}\nMarket cap: {market_cap}\nShare Price: {price}\nTrailingPE: {PEratio}\nForward PE: {FWPEratio}\n")
        
        # 将当前PE值加入列表
        pe_values.append(PEratio)
    except KeyError as e:
        print(f"{ticker} 缺失数据: {e}\n")

# 计算总和与平均值
if pe_values:
    total_pe = sum(pe_values)
    average_pe = total_pe / len(pe_values)
    print(f"所有股票TrailingPE总和: {total_pe:.2f}")
    print(f"所有股票TrailingPE平均值: {average_pe:.2f}")
else:
    print("没有获取到有效的TrailingPE数据")

关键改动说明

  • 新增pe_values空列表,用于循环中收集每个股票的TrailingPE数值。
  • 移除循环内的错误计算代码,改为循环结束后统一计算总和与平均值。
  • 添加try-except异常处理,避免某些股票缺失trailingPE或其他字段时导致程序崩溃。
  • 使用f-string优化打印格式,提升可读性。
  • 对输入变量重命名(原list改为ticker_input),避免覆盖Python内置的list类型。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 09:35:22