Files
AI-Stock-Trader/WebServer/AIPython/ai-predictor.py
T
2026-02-19 15:09:06 -08:00

66 lines
1.9 KiB
Python

import os
import json
import joblib
import numpy as np
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
import yfinance as yf
import features
import matplotlib
matplotlib.use("Agg")
def Predict(Symbol):
# Define paths (consistent with your previous script)
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
DATA_DIR = os.path.join(SCRIPT_DIR, "data")
MODEL_PATH = os.path.join(DATA_DIR, "model.keras")
# Pull 1 month of current data to make prediction against | for volatility 20
df = yf.download(Symbol, period="2mo", auto_adjust=True)
if not df.empty:
df = features.MakeFeatures(df, 1)
df = features.CleanDF(df)
print(Symbol)
# Drop our predictor
df.drop('Target_Close', axis=1, inplace=True)
# Lazy load this so it doesnt interfere with yfinance
from keras.models import load_model
# Load the model
reconstructed_model = load_model(MODEL_PATH)
# Verify it loaded correctly
reconstructed_model.summary()
# Load the scalers
feature_scaler = joblib.load(os.path.join(DATA_DIR, "feature_scaler.pkl"))
target_scaler = joblib.load(os.path.join(DATA_DIR, "target_scaler.pkl"))
# Scale the data
scaled_data = feature_scaler.transform(df)
# Predict
scaled_predictions = reconstructed_model.predict(scaled_data)
# Use the loaded target scaler to get back to % change
actual_prediction = target_scaler.inverse_transform(scaled_predictions)
# 'predictions' will be a 2D array, flatten it if you want a simple list
flat_predictions = actual_prediction.flatten().tolist()
print(f"Predicted Target_Close: {flat_predictions}")
movement_indicator = 0
if (np.mean(flat_predictions) > 0.01):
movement_indicator = 1
elif (np.mean(flat_predictions) < -0.01):
movement_indicator = -1
else:
movement_indicator = 0
return movement_indicator
if __name__ == "__main__":
Predict()