Files
AI-Stock-Trader/WebServer/AIPython/aipredictor.py
T

91 lines
2.8 KiB
Python

from datetime import datetime, timedelta
import os
import sys
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():
# Get the Symbol from ARGV
Symbol = sys.argv[1]
# get the number of days ago to run the simulation for
DaysBack = int(sys.argv[2])
print(f"Days back: {DaysBack}")
# calculate the time offsets
end_date = datetime.now() - timedelta(days=DaysBack)
start_date = end_date - timedelta(days=70)
# convert to string formats
start_str = start_date.strftime('%Y-%m-%d')
end_str = end_date.strftime('%Y-%m-%d')
print(f"Start Date: {start_str}")
print(f"End Date: {end_str}")
# 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, start=start_str, end=end_str, auto_adjust=True, progress=False)
if not df.empty:
# Remove the horizontal ticker column
df.columns = df.columns.get_level_values(0)
# Add in the Vertical ticker column
df['Ticker'] = Symbol
# Make the feature set
df = features.MakeFeatures(df)
# 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.reshape(-1, 1)).flatten()
# 'predictions' will be a 2D array, flatten it if you want a simple list
flat_predictions = actual_prediction
# Get the overall trend to pull predictions from
predictionTrend = 0
with open("Target_Close_Average.txt", "r") as f:
predictionTrend = float(f.read().strip())
# Set the movement indicator
movement_indicator = 0
averagePrediction = np.mean(flat_predictions) + predictionTrend
# Return to C# via stdout
print(f"---RESULT_START---")
print(averagePrediction)
print(f"---RESULT_END---")
if __name__ == "__main__":
Predict()