In code code add a line for predicting the closing price for tomorrow: import numpy as…
- User
In code code add a line for predicting the closing price for tomorrow:
import numpy as np import pandas as pd import matplotlib.pyplot as plt import yfinance as yf from sklearn.preprocessing import MinMaxScaler from sklearn.metrics import accuracy_score, f1_score from keras.models import Sequential from keras.layers import Dense, LSTM, Dropout
def calculate_atr(data, period): data[‘H-L’] = data[‘High’] - data[‘Low’] data[‘H-PC’] = abs(data[‘High’] - data[‘Close’].shift(1)) data[‘L-PC’] = abs(data[‘Low’] - data[‘Close’].shift(1)) data[‘TR’] = data[[‘H-L’, ‘H-PC’, ‘L-PC’]].max(axis=1) data[‘ATR’] = data[‘TR’].rolling(window=period).mean() return data
def calculate_super_trend(data, period, multiplier): data = calculate_atr(data, period) data[‘Upper Basic’] = (data[‘High’] + data[‘Low’]) / 2 + multiplier * data[‘ATR’] data[‘Lower Basic’] = (data[‘High’] + data[‘Low’]) / 2 - multiplier * data[‘ATR’] data[‘Upper Band’] = data.apply( lambda x: x[‘Upper Basic’] if x[‘Close’] > x[‘Upper Basic’] else x[‘Lower Basic’], axis=1) data[‘Lower Band’] = data.apply( lambda x: x[‘Lower Basic’] if x[‘Close’] < x[‘Lower Basic’] else x[‘Upper Basic’], axis=1)
data[‘Super Trend’] = np.nan for i in range(period, len(data)): if data[‘Close’][i] <= data[‘Upper Band’][i - 1]: data[‘Super Trend’].iat[i] = data[‘Upper Band’][i] elif data[‘Close’][i] > data[‘Upper Band’][i]: data[‘Super Trend’].iat[i] = data[‘Lower Band’][i]
return data.dropna()
def load_preprocess_data(ticker, start_date, end_date, window_size, period=14, multiplier=3): stock_data = yf.download(ticker, start=start_date, end=end_date) stock_data.columns = stock_data.columns.astype(str) print(stock_data.columns) stock_data_with_super_trend = calculate_super_trend(stock_data, period, multiplier)
columns_to_use = stock_data_with_super_trend[[‘Open’, ‘High’, ‘Low’, ‘Close’, ‘Super Trend’]].values scaler = MinMaxScaler(feature_range=(0, 1)) data_normalized = scaler.fit_transform(columns_to_use)
X, y = [], [] for i in range(window_size, len(data_normalized)): X.append(data_normalized[i - window_size:i]) y.append(data_normalized[i, 3]) # Use Close prices directly as labels
train_len = int(0.8 * len(X)) X_train, y_train = np.array(X[:train_len]), np.array(y[:train_len]) X_test, y_test = np.array(X[train_len:]), np.array(y[train_len:])
return X_train, y_train, X_test, y_test
def create_lstm_model(input_shape): model = Sequential() model.add(LSTM(units=50, return_sequences=True, input_shape=input_shape)) model.add(LSTM(units=50, return_sequences=True)) model.add(LSTM(units=50)) model.add(Dense(units=1, activation=‘linear’)) # Change activation function to ‘linear’
model.compile(optimizer=‘adam’, loss=‘mean_squared_error’, metrics=[‘accuracy’]) # Change loss to ‘mean_squared_error’ return model
def train_model(model, X_train, y_train, batch_size, epochs): history = model.fit(X_train, y_train, batch_size=batch_size, epochs=epochs, verbose=1) return model, history
- Assistant
Add a line for predicting the closing price for tomorrow
next_day_input = np.array([X_test[-1, 1:, :]]) # Use the last window data from X_test and exclude the first element tomorrow_pred = model.predict(next_day_input) tomorrow_pred_inverse = scaler.inverse_transform(np.column_stack((np.zeros(tomorrow_pred.shape), tomorrow_pred)))[:, 1] # Inverse transform for Close prices
print(f"Predicted closing price for tomorrow: {tomorrow_pred_inverse[0]}")
- User
- Assistant
Predict the closing price for the upcoming 5 days and plot them
upcoming_days = 5 predictions = []
for i in range(upcoming_days): next_day_input = np.array([X_test[-1, 1:, :]]) # Use the last window data from X_test and exclude the first element next_day_pred = model.predict(next_day_input) predictions.append(next_day_pred[0, 0])
new_row = np.column_stack((next_day_input[0, 1:, 3], next_day_input[0, 1:, 4], next_day_pred)) # Create a new row with the predicted value X_test = np.append(X_test, [new_row], axis=0) # Append the new row to X_test
predictions = np.array(predictions).reshape(-1, 1) predictions_inverse = scaler.inverse_transform(np.column_stack((np.zeros(predictions.shape), predictions)))[:, 1] # Inverse transform for Close prices
Plot the upcoming 5 days predictions
plt.figure(figsize=(14, 6)) plt.plot(predictions_inverse, marker="o", label='Predicted') plt.xlabel('Days') plt.ylabel('Close Price') plt.title('NIFTY Stock Price Prediction for Upcoming 5 Days') plt.legend() plt.show()
- User
- Assistant
- User
In above code im getting error:
KeyError Traceback (most recent call last) /usr/local/lib/python3.10/dist-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance) 3801 try: -> 3802 return self._engine.get_loc(casted_key) 3803 except KeyError as err:
7 frames pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
KeyError: 'High'
The above exception was the direct cause of the following exception:
KeyError Traceback (most recent call last) /usr/local/lib/python3.10/dist-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance) 3802 return self._engine.get_loc(casted_key) 3803 except KeyError as err: -> 3804 raise KeyError(key) from err 3805 except TypeError: 3806 # If we have a listlike key, _check_indexing_error will raise
KeyError: 'High'
- Assistant
Sorry for the confusion. I see the issue now. The given error is happening because the stock_data columns names are not being converted to lowercase correctly. I will fix this by properly converting the column names to lowercase.
Please replace the following line in the
load_preprocess_datafunction:stock_data.columns = stock_data.columns.str.lower()with:
stock_data.columns = [col.lower() for col in stock_data.columns]The updated
load_preprocess_datafunction should now look like this:def load_preprocess_data(ticker, start_date, end_date, window_size, period=14, multiplier=3): stock_data = yf.download(ticker, start=start_date, end=end_date) stock_data.columns = [col.lower() for col in stock_data.columns] stock_data_with_super_trend = calculate_super_trend(stock_data, period, multiplier) columns_to_use = stock_data_with_super_trend[['Open', 'High', 'Low', 'Close', 'Super Trend']].values scaler = MinMaxScaler(feature_range=(0, 1)) data_normalized = scaler.fit_transform(columns_to_use) X, y = [], [] for i in range(window_size, len(data_normalized)): X.append(data_normalized[i - window_size:i]) y.append(data_normalized[i, 3]) # Use Close prices directly as labels train_len = int(0.8 * len(X)) X_train, y_train = np.array(X[:train_len]), np.array(y[:train_len]) X_test, y_test = np.array(X[train_len:]), np.array(y[train_len:]) return X_train, y_train, X_test, y_test - User
- Assistant
I apologize for the confusion. The error is occurring because the column names in the dataframe are not formatted correctly. To fix this issue, we need to change the column names to match the keys used in the functions. Here are the changes you should make in the
load_preprocess_data()function:Replace this line:
stock_data.columns = [col.lower() for col in stock_data.columns]With the following lines:
stock_data.rename(columns={"Close": "Close", "High": "High", "Low": "Low", "Open": "Open"}, inplace=True)The updated
load_preprocess_datafunction should now look like this:def load_preprocess_data(ticker, start_date, end_date, window_size, period=14, multiplier=3): stock_data = yf.download(ticker, start=start_date, end=end_date) stock_data.rename(columns={"Close": "Close", "High": "High", "Low": "Low", "Open": "Open"}, inplace=True) stock_data_with_super_trend = calculate_super_trend(stock_data, period, multiplier) columns_to_use = stock_data_with_super_trend[['Open', 'High', 'Low', 'Close', 'Super Trend']].values scaler = MinMaxScaler(feature_range=(0, 1)) data_normalized = scaler.fit_transform
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.