can you write an agent for silver price forecast python code
- User
can you write an agent for silver price forecast python code
Assistant
Silver Price Forecasting Agent in Python
Below is a Python implementation of an agent that can forecast silver prices using machine learning techniques. This agent includes data collection, preprocessing, model training, and prediction capabilities.
import numpy as np import pandas as pd import yfinance as yf from sklearn.preprocessing import MinMaxScaler from sklearn.model_selection import train_test_split from sklearn.metrics import mean_squared_error from tensorflow.keras.models import Sequential from tensorflow.keras.layers import LSTM, Dense, Dropout import matplotlib.pyplot as plt import joblib import os from datetime import datetime, timedelta class SilverPriceForecastAgent: def __init__(self, ticker='SI=F', lookback=60, forecast_days=30): """ Initialize the Silver Price Forecasting Agent Parameters: - ticker: Yahoo Finance ticker for silver futures (default 'SI=F') - lookback: Number of days to use for training (default 60) - forecast_days: Number of days to forecast ahead (default 30) """ self.ticker = ticker self.lookback = lookback self.forecast_days = forecast_days self.model = None self.scaler = MinMaxScaler(feature_range=(0, 1)) self.data = None self.model_path = 'silver_price_model.h5' self.scaler_path = 'silver_scaler.pkl' def fetch_data(self, start_date=None, end_date=None): """ Fetch historical silver price data from Yahoo Finance Parameters: - start_date: Start date for data (YYYY-MM-DD format) - end_date: End date for data (YYYY-MM-DD format) """ if start_date is None: start_date = (datetime.now() - timedelta(days=365*5)).strftime('%Y-%m-%d') if end_date is None: end_date = datetime.now().strftime('%Y-%m-%d') print(f"Fetching data for {self.ticker} from {start_date} to {end_date}") self.data = yf.download(self.ticker, start=start_date, end=end_date) self.data = self.data[['Close']] # We'll focus on closing prices if self.data.empty: raise ValueError("No data fetched. Please check the ticker symbol and date range.") return self.data def preprocess_data(self): """ Preprocess the data for training """ if self.data is None: raise ValueError("No data available. Please fetch data first.") # Scale the data self.data['Close'] = self.scaler.fit_transform(self.data[['Close']]) # Create sequences for LSTM X, y = [], [] for i in range(self.lookback, len(self.data) - self.forecast_days): X.append(self.data['Close'].values[i-self.lookback:i]) y.append(self.data['Close'].values[i:i+self.forecast_days]) X, y = np.array(X), np.array(y) # Split into train and test sets X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, shuffle=False ) return X_train, X_test, y_train, y_test def build_model(self, input_shape): """ Build an LSTM model for time series forecasting """ model = Sequential([ LSTM(50, return_sequences=True, input_shape=input_shape), Dropout(0.2), LSTM(50, return_sequences=False), Dropout(0.2), Dense(self.forecast_days) ]) model.compile(optimizer='adam', loss='mean_squared_error') return model def train_model(self, X_train, y_train, epochs=50, batch_size=32): """ Train the LSTM model """ if self.model is None: self.model = self.build_model((X_train.shape[1], 1)) history = self.model.fit( X_train, y_train, epochs=epochs, batch_size=batch_size, validation_split=0.1, verbose=1 ) # Save the model and scaler self.model.save(self.model_path) joblib.dump(self.scaler, self.scaler_path) return history def evaluate_model(self, X_test, y_test): """ Evaluate the model on test data """ if self.model is None: raise ValueError("Model not trained. Please train the model first.") predictions = self.model.predict(X_test) mse = mean_squared_error(y_test, predictions) print(f"Test Mean Squared Error: {mse:.4f}") return predictions def forecast(self, days=30): """ Forecast silver prices for the next 'days' days """ if self.model is None: raise ValueError("Model not trained. Please train the model first.") # Load the latest data self.fetch_data() # Prepare the input data last_sequence = self.data['Close'].values[-self.lookback:] last_sequence = last_sequence.reshape(1, self.lookback, 1) # Make prediction forecast = self.model.predict(last_sequence) forecast = self.scaler.inverse_transform(forecast.reshape(-1, 1)) # Create date range for forecast last_date = self.data.index[-1] forecast_dates = pd.date_range(start=last_date + timedelta(days=1), periods=days) # Create DataFrame with forecast forecast_df = pd.DataFrame({ 'Date': forecast_dates, 'Forecasted_Price': forecast.flatten() }) return forecast_df def plot_forecast(self, forecast_df): """ Plot the forecasted prices """ plt.figure(figsize=(12, 6)) plt.plot(forecast_df['Date'], forecast_df['Forecasted_Price'], label='Forecasted Price', color='orange') plt.title(f'{self.forecast_days}-Day Silver Price Forecast') plt.xlabel('Date') plt.ylabel('Price (USD)') plt.legend() plt.grid(True) plt.show() def load_model(self): """ Load a pre-trained model and scaler """ if os.path.exists(self.model_path) and os.path.exists(self.scaler_path): self.model = tf.keras.models.load_model(self.model_path) self.scaler = joblib.load(self.scaler_path) print("Model and scaler loaded successfully.") else: print("No saved model found. Please train a model first.") # Example usage if __name__ == "__main__": # Initialize the agent agent = SilverPriceForecastAgent(ticker='SI=F', lookback=60, forecast_days=30) # Fetch and preprocess data agent.fetch_data() X_train, X_test, y_train, y_test = agent.preprocess_data() # Train the model history = agent.train_model(X_train, y_train, epochs=50) # Evaluate the model predictions = agent.evaluate_model(X_test, y_test) # Make a forecast forecast = agent.forecast(days=30) print(forecast) # Plot the forecast agent.plot_forecast(forecast)Key Features of this Agent:
- Data Collection: Uses Yahoo Finance API to fetch historical silver price data
- Preprocessing: Scales data and creates sequences for LSTM training
- Model Architecture: Uses an LSTM neural network for time series forecasting
- Training: Implements training with validation and model saving
- Forecasting: Can predict future prices based on historical patterns
- Visualization: Includes plotting functionality for the forecast
Requirements:
- Python 3.6+
- Required packages: numpy, pandas, yfinance, scikit-learn, tensorflow, matplotlib
How to Use:
- Install the required packages
- Run the script to train a model and make forecasts
- The agent will save the trained model and scaler for future use
- You can modify parameters like lookback period and forecast days as needed
Notes:
- This is a basic implementation. For production use, you might want to add more features, error handling, and model tuning.
- The accuracy depends on the quality and amount of historical data available.
- Consider adding more technical indicators or external factors that might influence silver prices.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.