簡體   English   中英

如何修復超出范圍的索引

[英]How to fix out of range index

我正在嘗試從兩個 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

我不知道問題是否是因為它沒有讀取我的數據。

你不應該做project.test_data()嗎?

還是from project import test_data

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM