### 3. Add Technical Indicators (Optional)
You can use technical analysis indicators, like moving averages, to help the AI model make more informed decisions.
python
import talib as ta
# Adding a 50-period moving average to the dataset
stock_data['SMA50'] = ta.SMA(stock_data['Close'], timeperiod=50)
stock_data['SMA200'] = ta.SMA(stock_data['Close'], timeperiod=200)
### 4. Prepare the Data
You’ll need to prepare the data by creating features (e.g., moving averages, volume) and labels (whether the stock price will go up or down).
python
# Calculate the target: 1 if the stock price increased the next day, 0 otherwise
stock_data['Target'] = (stock_data['Close'].shift(-1) > stock_data['Close']).astype(int)
# Drop rows with NaN values
stock_data.dropna(inplace=True)
# Select features and labels
features = ['Close', 'SMA50', 'SMA200']
X = stock_data[features]
y = stock_data['Target']
### 5. Train the Machine Learning Model
Now you can use a machine learning algorithm to train the model. We’ll use a Random Forest classifier as an example.
python
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
# Split data into training and test sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Train a Random Forest model
model = RandomForestClassifier(n_estimators=100, random_state=42)
model.fit(X_train, y_train)
# Make predictions
y_pred = model.predict(X_test)
# Evaluate the model
accuracy = accuracy_score(y_test, y_pred)
print(f"Accuracy: {accuracy:.2f}")