我在 Google Colab 中使用此代码:
import pandas as pd
import yfinance as yf
import talib as ta
data = yf.download("GOOG")
data['RSI'] = ta.RSI(data["Close"], timeperiod=10)
这是输出:
[*********************100%***********************] 1 of 1 completed
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-3-e3c5cad38926> in <cell line: 6>()
4
5 data = yf.download("GOOG")
----> 6 data['RSI'] = ta.RSI(data["Close"], timeperiod=10)
/usr/local/lib/python3.10/dist-packages/talib/__init__.py in wrapper(*args, **kwargs)
25
26 if index is None:
---> 27 return func(*args, **kwargs)
28
29 # Use Series' float64 values if pandas, else use values as passed
TypeError: Argument 'real' has incorrect type (expected numpy.ndarray, got DataFrame)
我的代码有什么问题?我以前用过ta-lib。但现在我无法使用它。为什么?
我已将
.flatten()
添加到从 data["Close"].values
获得的 numpy数组中。这可确保数组严格为一维,即使其最初形状为 (n, 1) 或不是简单一维数组的任何其他形状。这应该通过向
ta.RSI
函数提供预期的输入格式来解决“尺寸错误”错误。
import pandas as pd
import yfinance as yf
import talib as ta
import numpy as np # Import numpy
data = yf.download("GOOG")
# Convert the Pandas Series to a NumPy array and ensure it's 1-dimensional before passing it to ta.RSI
# Use .values to get the underlying NumPy array and flatten to ensure it's 1D
data['RSI'] = ta.RSI(data["Close"].values.flatten(), timeperiod=10)
# [*********************100%***********************] 1 of 1 completed
RSI 输出图:
import matplotlib.pyplot as plt
data['RSI'].plot(figsize=(20,8),marker='x', label='RSI', alpha=0.5)
plt.legend()
plt.title('Relative Strength Index (RSI)')
plt.show()