简体   繁体   English

如何修复超出范围的索引

[英]How to fix out of range index

I am trying to get test data from two CSV files.我正在尝试从两个 CSV 文件中获取测试数据。 However whenever I put a test case in for example:但是,每当我放入一个测试用例时,例如:

val = Test_data("AAPL.csv", "close", 25)
    print (val)

I get:我得到:

Open.append(temp[1])
IndexError: list index out of range

I have tried changing the file to read , readlines , and readline .我尝试将文件更改为readreadlinesreadline

def main():
    pass

if __name__ == '__main__':
    main()


def test_data(filename, col, day):
    """A test function to query the data you loaded into your program.

        Args:
            filename: A string for the filename containing the stock data,
                      in CSV format.

            col: A string of either "date", "open", "high", "low", "close",
                 "volume", or "adj_close" for the column of stock market data to
                 look into.

                 The string arguments MUST be LOWERCASE!

            day: An integer reflecting the absolute number of the day in the
                 data to look up, e.g. day 1, 15, or 1200 is row 1, 15, or 1200
                 in the file.

        Returns:
            A value selected for the stock on some particular day, in some
            column col. The returned value *must* be of the appropriate type,
            such as float, int or str.
        """
    Date = list()
    Open = list()
    High = list()
    Low = list()
    Close = list()
    AdjClose = list()
    Volume = list()

    file = open(filename, "r")
    x= file.read()

    for line in x:
        temp = line.split(",")
        Date.append(temp[0])
        Open.append(temp[1])
        High.append(temp[2])
        Low.append(temp[3])
        Close.append(temp[4])
        AdjClose.append(temp[5])
        Volume.append(temp[6])

    if col == 'Date':
        return Date[day - 1]
    elif col == 'Open':
        return Open[day - 1]
    elif col == 'High':
        return High[day - 1]
    elif col == 'Low':
        return Low[day - 1]
    elif col == 'Close':
        return Close[day - 1]
    elif col == 'Adj close':
        return AdjClose[day - 1]
    elif col == 'Volume':
        return Volume[day - 1]




def transact(funds, stocks, qty, price, buy=False, sell=False):
    """A bookkeeping function to help make stock transactions.

          Args:
              funds: An account balance, a float; it is a value of how much money you have,
                     currently.

              stocks: An int, representing the number of stock you currently own.

              qty: An int, representing how many stock you wish to buy or sell.

              price: An float reflecting a price of a single stock.

              buy: This option parameter, if set to true, will initiate a buy.

              sell: This option parameter, if set to true, will initiate a sell.

          Returns:
              Two values *must* be returned. The first (a float) is the new
              account balance (funds) as the transaction is completed. The second
              is the number of stock now owned (an int) after the transaction is
              complete.

              Error condition #1: If the `buy` and `sell` keyword parameters are both set to true,
              or both false. You *must* print an error message, and then return
              the `funds` and `stocks` parameters unaltered. This is an ambiguous
              transaction request!

              Error condition #2: If you buy, or sell without enough funds or
              stocks to sell, respectively.  You *must* print an error message,
              and then return the `funds` and `stocks` parameters unaltered. This
              is an ambiguous transaction request!

       """
    if buy == sell:
        # print("Ambigious transaction! Can't determine whether to buy or sell. No action performed.")
        return funds, stocks
    elif buy and funds >= qty * price:
        funds -= qty * price
        stocks += qty
        # print("Insufficient funds")
        return funds, stocks
    elif sell and stocks >= qty:
        funds += qty * price
        stocks -= qty
        # print("Insufficient stock")
        return funds, stocks

Error:错误:

import project
cash_balance = 1000
stocks_owned = 25
price = test_data("AAPL.csv", "close", 42)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
NameError: name 'test_data' is not defined

What Im supposed to get:我应该得到什么:

>>> cash_balance = 1000
>>> stocks_owned = 25
>>> price = test_data("AAPL.csv", "close", 42)
>>> price
4.357143

I don't know if the problem is because it is not reading my data.我不知道问题是否是因为它没有读取我的数据。

Aren't you supposed to do project.test_data() ?你不应该做project.test_data()吗?

Or from project import test_data ?还是from project import test_data

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM