我想预测未来的股票价格,我试图创建计算函数,但当我运行下面的代码时,我发现了一个错误。我不确定我是否错过了()。你能给我点建议吗?
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
Gold_train_data = pd.read_csv('Gold Data Last Year.csv', index_col=False)
Gold_test_data = pd.read_csv('Gold Data Last Month.csv', index_col=False)
current_train_data = Gold_train_data
current_test_data = Gold_test_data
NUM_train_data = 266
NUM_test_data = 22
def load_stock_data(stock_name, num_data_points):
data = pd.read_csv(stock_name,
skiprows=0,
nrows=num_data_points,
usecols=['Price', 'Open', 'Vol.'])
final_prices = data['Price'].astype(str).str.replace(',','').astype(np.float)
opening_prices = data['Open'].astype(str).str.replace(',', '').astype(np.float)
volumes = data['Vol.'].str.strip('MK').astype(np.float)
return final_prices, opening_prices, volumes
def calculate_price_differences(final_prices, opening_prices):
price_differences = []
for d_i in range(len(final_prices) - 1):
price_difference = opening_prices[d_i + 1] - final_prices[d_i]
price_differences.append(price_difference)
return price_differences
print(load_stock_data(current_test_data, NUM_test_data))
上面是代码,下面是错误,如下所示:
Traceback (most recent call last):
Input In [6] in <cell line: 1>
print(load_stock_data(current_test_data, NUM_test_data))
Input In [4] in load_stock_data
data = pd.read_csv(stock_name,
File ~Anaconda3libsite-packagespandasutil_decorators.py:311 in wrapper
return func(*args, **kwargs)
File ~Anaconda3libsite-packagespandasioparsersreaders.py:680 in read_csv
return _read(filepath_or_buffer, kwds)
File ~Anaconda3libsite-packagespandasioparsersreaders.py:575 in _read
parser = TextFileReader(filepath_or_buffer, **kwds)
File ~Anaconda3libsite-packagespandasioparsersreaders.py:933 in __init__
self._engine = self._make_engine(f, self.engine)
File ~Anaconda3libsite-packagespandasioparsersreaders.py:1217 in _make_engine
self.handles = get_handle( # type: ignore[call-overload]
File ~Anaconda3libsite-packagespandasiocommon.py:661 in get_handle
if _is_binary_mode(path_or_buf, mode) and "b" not in mode:
File ~Anaconda3libsite-packagespandasiocommon.py:1128 in _is_binary_mode
return isinstance(handle, _get_binary_io_classes()) or "b" in getattr(
TypeError: argument of type 'method' is not iterable
问题在于函数调用
print(load_stock_data(current_test_data, NUM_test_data))
current_test_data
是您先前加载的pandas数据框。将变量传递给load_stock_data()
会导致函数尝试执行
data = pd.read_csv(current_test_data,
skiprows=0,
nrows=num_data_points,
usecols=['Price', 'Open', 'Vol.'])
注意,默认情况下,pd.read_csv()的第一个参数是csv文件的路径名。因此,当它认为current_test_data
是路径名,但它实际上是一个pandas.DataFrame时,会出现错误。
我认为你想做的事情可以通过使用
来实现。print(load_stock_data('Gold Data Last Month.csv', NUM_test_data))
。将路径名提供给函数调用,而不是数据框架本身。