**已关闭。**此问题需要调试详细信息。它目前不接受答案。
**想要改进此问题?**更新问题,使其位于堆栈溢出主题上。
昨天关门了。
改进这个问题
所以一个月前我开始做一个项目,试图利用历史数据预测未来的股价。项目进展顺利,我决定稍作休息,升级我的电脑。好吧,我试着在完成电脑后检查我的代码,但现在我遇到了一系列关于从yahoo finance api提取数据的错误。我的朋友正在做同一个项目,他说他在代码中没有遇到任何问题,所以我认为我的代码环境有问题。我不知道该怎么做,因为我对编码还很陌生,但如果我在下面发布代码,我希望有人能帮助我:
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import pandas_datareader as web
import datetime as dt
from sklearn.preprocessing import MinMaxScaler
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, LSTM
from tensorflow.python.ops.gen_math_ops import mod_eager_fallback
# Load Data
symbols = 'NIO'
start = dt.datetime(2012,1,1)
end = dt.datetime(2020,1,1)
data = web.DataReader(symbols, 'yahoo', start, end)
# Prepare Data
scaler = MinMaxScaler(feature_range=(0,1))
scaled_data = scaler.fit_transform(data['Close'].values.reshape(-1,1))
prediction_days = 60
x_train = []
y_train = []
for x in range(prediction_days, len(scaled_data)):
x_train.append(scaled_data[x-prediction_days:x, 0])
y_train.append(scaled_data[x, 0])
x_train, y_train = np.array(x_train), np.array(y_train)
x_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], 1))
# Build the Model
model = Sequential()
model.add(LSTM(units=50, return_sequences=True, input_shape=(x_train.shape[1], 1)))
model.add(Dropout(0.2))
model.add(LSTM(units=50, return_sequences=True))
model.add(Dropout(0.2))
model.add(LSTM(units=50))
model.add(Dropout(0.2))
model.add(Dense(units=1)) # Prediction of the next Closing Price
model.compile(optimizer='adam', loss='mean_squared_error')
model.fit(x_train, y_train, epochs=25, batch_size=32)
# We can use model.save('model name with .h5 or .tf depending on whether saving to tensorflow saved model or HDF5')
''' Test The Model Accuracy on Existing Data '''
# Load Test Data
test_start = dt.datetime(2020,1,1)
test_end = dt.datetime.now()
test_data = web.DataReader(symbols, 'yahoo', test_start, test_end)
closing_prices = test_data['Close'].values
total_dataset = pd.concat((data['Close'], test_data['Close']), axis=0)
model_inputs = total_dataset[len(total_dataset) - len(test_data) - prediction_days:].values
model_inputs = model_inputs.reshape(-1,1)
model_inputs = scaler.transform(model_inputs)
# Make Predictions on Test Data
x_test = []
for x in range(prediction_days, len(model_inputs)):
x_test.append(model_inputs[x-prediction_days:x, 0])
x_test = np.array(x_test)
x_test = np.reshape(x_test, (x_test.shape[0], x_test.shape[1], 1))
predicted_prices = model.predict(x_test)
predicted_prices = scaler.inverse_transform(predicted_prices)
# Plot The Test Predictions
plt.plot(closing_prices, color='black', label=f'Actual {symbols} Price')
plt.plot(predicted_prices, color='red', label=f'Predicted {symbols} Price')
plt.title(f'{symbols} Share Price')
plt.xlabel('Time')
plt.ylabel(f'{symbols} Share Price')
plt.legend()
plt.show()
# Predicting The Next Market Open
real_data = [model_inputs[len(model_inputs) + 1 - prediction_days:len(model_inputs + 1), 0]]
real_data = np.array(real_data)
real_data = np.reshape(real_data, (real_data.shape[0], real_data.shape[1], 1))
prediction = model.predict(real_data)
prediction = scaler.inverse_transform(prediction)
print(f'Prediction: {prediction}')
以下是我尝试运行上述操作时得到的错误代码:
RemoteDataError Traceback (most recent call
RemoteDataError Traceback (most recent call last)
d:\Documents\Coding\laplaces_daemon\OneDayPredictor.py in
17 end = dt.datetime(2020,1,1)
18
---> 19 data = web.DataReader(symbols, 'yahoo', start, end)
20
21 # Prepare Data
~\AppData\Local\Programs\Python\Python39\lib\site-packages\pandas\util\_decorators.py in wrapper(*args,**kwargs)
197 else:
198 kwargs[new_arg_name] = new_arg_value
--> 199 return func(*args,**kwargs)
200
201 return cast(F, wrapper)
~\AppData\Local\Programs\Python\Python39\lib\site-packages\pandas_datareader\data.py in DataReader(name, data_source, start, end, retry_count, pause, session, api_key)
374
375 if data_source == "yahoo":
--> 376 return YahooDailyReader(
377 symbols=name,
378 start=start,
~\AppData\Local\Programs\Python\Python39\lib\site-packages\pandas_datareader\base.py in read(self)
251 # If a single symbol, (e.g., 'GOOG')
252 if isinstance(self.symbols, (string_types, int)):
--> 253 df = self._read_one_data(self.url, params=self._get_params(self.symbols))
254 # Or multiple symbols, (e.g., ['GOOG', 'AAPL', 'MSFT'])
255 elif isinstance(self.symbols, DataFrame):
~\AppData\Local\Programs\Python\Python39\lib\site-packages\pandas_datareader\yahoo\daily.py in _read_one_data(self, url, params)
151 url = url.format(symbol)
152
--> 153 resp = self._get_response(url, params=params)
154 ptrn = r"root\.App\.main = (.*?);\n}\(this\)\);"
155 try:
~\AppData\Local\Programs\Python\Python39\lib\site-packages\pandas_datareader\base.py in _get_response(self, url, params, headers)
179 msg += "\nResponse Text:\n{0}".format(last_response_text)
180
--> 181 raise RemoteDataError(msg)
182
183 def _get_crumb(self, *args):
RemoteDataError: Unable to read URL: https://finance.yahoo.com/quote/NIO/history?period1=1325408400&period2=1577955599&interval=1d&frequency=1d&filter=history
Response Text:
b'<!DOCTYPE html>\n <html lang="en-us"><head>\n <meta http-equiv="content-type" content="text/html; charset=UTF-8">\n <meta charset="utf-8">\n <title>Yahoo</title>\n <meta name="viewport" content="width=device-width,initial-scale=1,minimal-ui">\n <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">\n <style>\n html {\n height: 100%;\n }\n body {\n background: #fafafc url(https://s.yimg.com/nn/img/sad-panda-201402200631.png) 50% 50%;\n background-size: cover;\n height: 100%;\n text-align: center;\n font: 300 18px "helvetica neue", helvetica, verdana, tahoma, arial, sans-serif;\n }\n table {\n height: 100%;\n width: 100%;\n table-layout: fixed;\n border-collapse: collapse;\n border-spacing: 0;\n border: none;\n }\n h1 {\n font-size: 42px;\n font-weight: 400;\n color: #400090;\n }\n p {\n color: #1A1A1A;\n }\n #message-1 {\n font-weight: bold;\n margin: 0;\n }\n #message-2 {\n display: inline-block;\n *display: inline;\n zoom: 1;\n max-width: 17em;\n _width: 17em;\n }\n </style>\n <script>\n document.write(\'<img src="//geo.yahoo.com/b?s=1197757129&t=\'+new Date().getTime()+\'&src=aws&err_url=\'+encodeURIComponent(document.URL)+\'&err=%<pssc>&test=\'+encodeURIComponent(\'%<{Bucket}cqh[:200]>\')+\'" width="0px" height="0px"/>\');var beacon = new Image();beacon.src="//bcn.fp.yahoo.com/p?s=1197757129&t="+new Date().getTime()+"&src=aws&err_url="+encodeURIComponent(document.URL)+"&err=%<pssc>&test="+encodeURIComponent(\'%<{Bucket}cqh[:200]>\');\n </script>\n </head>\n <body>\n <!-- status code : 404 -->\n <!-- Not Found on Server -->\n <table>\n <tbody><tr>\n <td>\n <img src="https://s.yimg.com/rz/p/yahoo_frontpage_en-US_s_f_p_205x58_frontpage.png" alt="Yahoo Logo">\n <h1 style="margin-top:20px;">Will be right back...</h1>\n <p id="message-1">Thank you for your patience.</p>\n <p id="message-2">Our engineers are working quickly to resolve the issue.</p>\n </td>\n </tr>\n </tbody></table>\n </body></html>'last)
d:\Documents\Coding\laplaces_daemon\OneDayPredictor.py in
17 end = dt.datetime(2020,1,1)
18
---> 19 data = web.DataReader(symbols, 'yahoo', start, end)
20
21 # Prepare Data
~\AppData\Local\Programs\Python\Python39\lib\site-packages\pandas\util\_decorators.py in wrapper(*args,**kwargs)
197 else:
198 kwargs[new_arg_name] = new_arg_value
--> 199 return func(*args,**kwargs)
200
201 return cast(F, wrapper)
~\AppData\Local\Programs\Python\Python39\lib\site-packages\pandas_datareader\data.py in DataReader(name, data_source, start, end, retry_count, pause, session, api_key)
374
375 if data_source == "yahoo":
--> 376 return YahooDailyReader(
377 symbols=name,
378 start=start,
~\AppData\Local\Programs\Python\Python39\lib\site-packages\pandas_datareader\base.py in read(self)
251 # If a single symbol, (e.g., 'GOOG')
252 if isinstance(self.symbols, (string_types, int)):
--> 253 df = self._read_one_data(self.url, params=self._get_params(self.symbols))
254 # Or multiple symbols, (e.g., ['GOOG', 'AAPL', 'MSFT'])
255 elif isinstance(self.symbols, DataFrame):
~\AppData\Local\Programs\Python\Python39\lib\site-packages\pandas_datareader\yahoo\daily.py in _read_one_data(self, url, params)
151 url = url.format(symbol)
152
--> 153 resp = self._get_response(url, params=params)
154 ptrn = r"root\.App\.main = (.*?);\n}\(this\)\);"
155 try:
~\AppData\Local\Programs\Python\Python39\lib\site-packages\pandas_datareader\base.py in _get_response(self, url, params, headers)
179 msg += "\nResponse Text:\n{0}".format(last_response_text)
180
--> 181 raise RemoteDataError(msg)
182
183 def _get_crumb(self, *args):
RemoteDataError: Unable to read URL: https://finance.yahoo.com/quote/NIO/history?period1=1325408400&period2=1577955599&interval=1d&frequency=1d&filter=history
Response Text:
b'<!DOCTYPE html>\n <html lang="en-us"><head>\n <meta http-equiv="content-type" content="text/html; charset=UTF-8">\n <meta charset="utf-8">\n <title>Yahoo</title>\n <meta name="viewport" content="width=device-width,initial-scale=1,minimal-ui">\n <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">\n <style>\n html {\n height: 100%;\n }\n body {\n background: #fafafc url(https://s.yimg.com/nn/img/sad-panda-201402200631.png) 50% 50%;\n background-size: cover;\n height: 100%;\n text-align: center;\n font: 300 18px "helvetica neue", helvetica, verdana, tahoma, arial, sans-serif;\n }\n table {\n height: 100%;\n width: 100%;\n table-layout: fixed;\n border-collapse: collapse;\n border-spacing: 0;\n border: none;\n }\n h1 {\n font-size: 42px;\n font-weight: 400;\n color: #400090;\n }\n p {\n color: #1A1A1A;\n }\n #message-1 {\n font-weight: bold;\n margin: 0;\n }\n #message-2 {\n display: inline-block;\n *display: inline;\n zoom: 1;\n max-width: 17em;\n _width: 17em;\n }\n </style>\n <script>\n document.write(\'<img src="//geo.yahoo.com/b?s=1197757129&t=\'+new Date().getTime()+\'&src=aws&err_url=\'+encodeURIComponent(document.URL)+\'&err=%<pssc>&test=\'+encodeURIComponent(\'%<{Bucket}cqh[:200]>\')+\'" width="0px" height="0px"/>\');var beacon = new Image();beacon.src="//bcn.fp.yahoo.com/p?s=1197757129&t="+new Date().getTime()+"&src=aws&err_url="+encodeURIComponent(document.URL)+"&err=%<pssc>&test="+encodeURIComponent(\'%<{Bucket}cqh[:200]>\');\n </script>\n </head>\n <body>\n <!-- status code : 404 -->\n <!-- Not Found on Server -->\n <table>\n <tbody><tr>\n <td>\n <img src="https://s.yimg.com/rz/p/yahoo_frontpage_en-US_s_f_p_205x58_frontpage.png" alt="Yahoo Logo">\n <h1 style="margin-top:20px;">Will be right back...</h1>\n <p id="message-1">Thank you for your patience.</p>\n <p id="message-2">Our engineers are working quickly to resolve the issue.</p>\n </td>\n </tr>\n </tbody></table>\n </body></html>'
暂无答案!
目前还没有任何答案,快来回答吧!