指数超出范围 python 股票分析

Index out of range python stock analysis

我正在制作一个股票价格预测模型,我得到了 1 年的历史价格作为 "database"。当我运行代码时,我得到了一个超出范围的列表索引,尝试使用行和列选择但它不起作用

def get_data(IndFut):
with open('IndFut.csv','r') as csvfile:
    csvFileReader = csv.reader(csvfile)
    next(csvFileReader)
    for row in csvFileReader:
        dates.append(int(row[0].split('/')[0]))
        prices.append(float(row[1]))

这是数据

    Day        Close    Open    High     Low   Volume
11/01/2018  79830   78590   79845   78555   
10/01/2018  78638   78850   79025   78510   57030
09/01/2018  79242   79750   79925   79100   67500
08/01/2018  79829   79730   79915   79055   57270

并出现以下错误:

prices.append(float(row[1]))

IndexError: list index out of range

如何处理?

我认为您需要拆分每一行以消除分号。

rows = [['11/01/2018;79830;78590;79845;78555;;']]

dates = []
prices = []

for row in rows:
    row = ''.join(rows[0]).split(';')
    dates.append(int(row[0].split('/')[0]))
    prices.append(float(row[1]))    

print(dates)
# [11]    

print(prices)
# [79830.0]

重写函数:

def get_data(IndFut):
    with open(IndFut,'r') as csvfile:
        csvFileReader = csv.reader(csvfile)

        next(csvFileReader)

        for row in csvFileReader:
            row = ''.join(rows[0]).split(';')
            dates.append(int(row[0].split('/')[0]))
            prices.append(float(row[1]))

我怀疑您的数据是用制表符分隔的,因此您需要这样指明,并且您可能需要删除空格。

def get_data(IndFut):
with open('IndFut.csv','r') as csvfile:
    csvFileReader = csv.reader(csvfile, delimiter='\t')
    next(csvFileReader)
    for row in csvFileReader:
        try:
            dates.append(int(row[0].split('/')[0]))
            prices.append(float(row[1]))
        except:
            print(f"failed to process row {row}")

[编辑] 不确定我明白为什么...但是试试这个;

def get_data(IndFut):
with open('IndFut.csv','r') as csvfile:
    csvFileReader = csv.reader(csvfile, delimiter='\t')
    next(csvFileReader)
    for row in csvFileReader:
        split_row = row[0].split(';')[:-1]
        try:
            dates.append(int(split_row[0].split('/')[0]))
            prices.append(float(split_row[1]))
        except:
            print(f"failed to process row {split_row}")