如何解决超出范围的索引

时间:2019-11-05 02:13:53

标签: python

我正在尝试从两个CSV文件中获取测试数据。但是,每当我放置一个测试用例时,例如:

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

我得到:

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

我尝试将文件更改为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

错误:

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

我应该得到的东西:

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

我不知道问题是否是因为它没有读取我的数据。

1 个答案:

答案 0 :(得分:0)

您不应该做project.test_data()吗?

还是from project import test_data