import tensorflow as tf import warnings warnings.filterwarnings('ignore')…
- User
import tensorflow as tf import warnings warnings.filterwarnings('ignore') tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)
import pandas as pd import numpy as np import yfinance as yf from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor from statsmodels.tsa.statespace.sarimax import SARIMAX from tensorflow.keras.models import Sequential from tensorflow.keras.layers import LSTM, Dense from sklearn.metrics import mean_squared_error from sklearn.preprocessing import StandardScaler from sklearn.model_selection import TimeSeriesSplit from sklearn.linear_model import LinearRegression import matplotlib.pyplot as plt
Load the stock data from Yahoo Finance
stock_data = yf.download('AAPL', period='2y')
Preprocess the data
stock_data['Date'] = pd.to_datetime(stock_data.index) stock_data.set_index('Date', inplace=True)
Create features
stock_data['MA5'] = stock_data['Close'].rolling(window=5).mean() stock_data['MA20'] = stock_data['Close'].rolling(window=20).mean() stock_data['RSI'] = calculate_rsi(stock_data['Close']) # You need to implement this function stock_data.dropna(inplace=True)
features = ['Open', 'High', 'Low', 'Close', 'Volume', 'MA5', 'MA20', 'RSI'] target = 'Close'
Normalize the data
scaler = StandardScaler() stock_data_scaled = pd.DataFrame(scaler.fit_transform(stock_data[features]), columns=features, index=stock_data.index)
Split the data
train_size = int(0.8 * len(stock_data_scaled)) train_data, test_data = stock_data_scaled[:train_size], stock_data_scaled[train_size:]
Time series cross-validation
tscv = TimeSeriesSplit(n_splits=5)
Define models
model1 = RandomForestRegressor(n_estimators=100, random_state=42) model2 = SARIMAX(train_data[target], order=(1, 1, 1), seasonal_order=(1, 1, 1, 12)) model3 = GradientBoostingRegressor(n_estimators=100, random_state=42)
LSTM model
def create_lstm_model(input_shape): model = Sequential() model.add(LSTM(50, return_sequences=True, input_shape=input_shape)) model.add(LSTM(50)) model.add(Dense(1)) model.compile(loss='mean_squared_error', optimizer='adam') return model
Function to create sequences
def create_sequences(data, seq_length): xs = [] ys = [] for i in range(len(data) - seq_length): x = data[i:(i + seq_length)] y = data[i + seq_length] xs.append(x) ys.append(y) return np.array(xs), np.array(ys)
Prepare data for LSTM
seq_length = 10 X_lstm, y_lstm = create_sequences(train_data[features].values, seq_length) model4 = create_lstm_model((seq_length, len(features)))
Train models
model1.fit(train_data[features], train_data[target]) model2_fit = model2.fit(disp=False) model3.fit(train_data[features], train_data[target]) model4.fit(X_lstm, y_lstm, epochs=50, batch_size=32, verbose=0)
Assistant
The error you're encountering,
ModuleNotFoundError: No module named 'PIL', is due to the absence of the Python Imaging Library (PIL) or its fork, Pillow, in your Python environment. Pillow is a widely used library for handling image files in Python and is necessary for some of the functionality used by Matplotlib, which you're using for plotting.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.