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

Python读取多只股票CSV文件及输入逻辑优化问题求助

股票组合开盘/收盘价相关性分析代码修正

问题说明

  • read_company()函数仅支持最多3只股票输入,需修改为允许输入3只及以上
  • read_stocks()函数读取CSV时出现UnboundLocalError,且无法正确提取多只股票的开盘/收盘价,需修复并传递对应数据

原有代码

from os import path
import csv

def read_information():
    company = read_company()
    open, close = read_stocks(open, close)

    return company, open, close **### needs to send company and its open and close values to a module that is in charge of the processing part ###**


def read_company():
    companies = []

    while len(companies) < 3: **### program needs to ask for 3 OR MORE companies ###**
        company = input("Enter at least three companies.")
        if company in companies:
            print("Company already entered. Enter a new company.")
        elif not path.exists(company + '.csv'):
            print(company + " does not exist. Enter a new company.")
        else:
            companies.append(company)
    return companies ### returns list of the 3 companies ###


def read_stocks(company): **### needs to read the stocks of the companies sent by previous module ###**
    stocks = []

    with open("Company" + company + ".csv", "r", newline=" ") as csvfile: ### must read list of 3 companies and extract open and close for each of them ###
        csvreader = csv.DictReader(csvfile, delimiter=",")
        for row in csvreader:
            stocks.append([row[1, "open"], row[4, "close"]])
    return open, close **### needs to send open and close to a module that is in charge of the processing part ###**


read_information()

报错信息

Traceback (most recent call last):
  File "/Users/....py", line 35, in <module>
    read_information()
  File "/Users/....py", line 6, in read_information
    open, close = read_stocks(open, close)
UnboundLocalError: local variable 'open' referenced before assignment

修正后的代码

from os import path
import csv

def read_information():
    companies = read_company()
    stock_data = read_stocks(companies)
    return companies, stock_data


def read_company():
    companies = []
    print("请输入至少3只股票代码,输入空行结束输入")
    while True:
        company = input("输入股票代码:").strip()
        # 空行则结束输入,且确保至少有3只
        if not company:
            if len(companies) >= 3:
                break
            else:
                print("必须输入至少3只股票,请继续输入")
                continue
        if company in companies:
            print("该股票已输入过,请输入新的")
        elif not path.exists(f"{company}.csv"):
            print(f"{company}.csv 文件不存在,请输入其他股票")
        else:
            companies.append(company)
    return companies


def read_stocks(companies):
    # 用字典存储每只股票的开盘价和收盘价,键为股票名,值为(开盘价列表, 收盘价列表)
    stock_data = {}
    for company in companies:
        opens = []
        closes = []
        # 修正文件名拼接,去掉多余的"Company"前缀
        with open(f"{company}.csv", "r", newline="") as csvfile:
            csvreader = csv.DictReader(csvfile)
            for row in csvreader:
                # 用列名直接取值,注意CSV列名的大小写(这里假设是小写,若实际是大写需调整)
                try:
                    open_price = float(row["open"])
                    close_price = float(row["close"])
                    opens.append(open_price)
                    closes.append(close_price)
                except KeyError:
                    print(f"{company}.csv 中缺少open或close列,请检查文件结构")
                    return None
                except ValueError:
                    print(f"{company}.csv 中存在非数值的价格数据,请检查")
                    return None
        stock_data[company] = (opens, closes)
    return stock_data


# 测试调用,后续可将数据传给处理模块
companies, stock_data = read_information()
print("已读取的股票:", companies)
print("每只股票的开盘/收盘价数据:", stock_data)

修复要点

  1. read_company()函数修复

    • 替换原有限循环为无限循环,允许用户输入空行结束输入,同时校验结束时至少有3只股票
    • 优化提示语为中文,提升易用性
    • 保留原有的输入去重和文件存在性校验逻辑
  2. read_stocks()函数及调用逻辑修复

    • 修正read_information()中的错误调用:将未定义的open/close参数改为传入读取到的companies列表
    • 修复文件名拼接错误:移除多余的"Company"前缀,直接匹配{company}.csv文件
    • 用字典存储每只股票的开盘/收盘价,确保股票名与数据一一对应
    • 正确使用DictReader列名取值(row["open"]而非row[1, "open"]),并转换为数值类型方便后续分析
    • 增加异常处理,捕获列缺失或数据格式错误的情况
    • 改用字典返回所有股票数据,替代原有的单独open/close变量,逻辑更清晰
  3. 变量命名规范

    • 避免使用Python内置函数名open作为变量名,改用opens、open_price等命名,避免冲突

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 15:40:28