File size: 4,253 Bytes
7ddc554 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 |
{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"provenance": []
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
},
"language_info": {
"name": "python"
}
},
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "k2PNBliRg61b"
},
"outputs": [],
"source": [
"\n",
"# Install required packages\n",
"\n",
"!pip install --quiet yfinance joblib tensorflow huggingface_hub scikit-learn\n",
"\n",
"\n",
"# Import Libraries\n",
"\n",
"from huggingface_hub import hf_hub_download\n",
"import tensorflow as tf\n",
"import joblib\n",
"import numpy as np\n",
"import pandas as pd\n",
"import yfinance as yf\n",
"from sklearn.preprocessing import MinMaxScaler\n",
"\n",
"\n",
"# Hugging Face token\n",
"\n",
"HF_TOKEN = \"your_own_hf_token\" # Replace with your token if private\n",
"\n",
"\n",
"# Download LSTM model & scaler from Hugging Face Hub\n",
"\n",
"model_path = hf_hub_download(\n",
" repo_id=\"EsferSami/DataSynthis_ML_JobTask\",\n",
" filename=\"Apple-Stock-Price-Forecasting-LSTM-Model/apple_stock_lstm.h5\",\n",
" token=HF_TOKEN\n",
")\n",
"scaler_path = hf_hub_download(\n",
" repo_id=\"EsferSami/DataSynthis_ML_JobTask\",\n",
" filename=\"Apple-Stock-Price-Forecasting-LSTM-Model/scaler.joblib\",\n",
" token=HF_TOKEN\n",
")\n",
"\n",
"\n",
"# Load model & scaler\n",
"\n",
"model = tf.keras.models.load_model(model_path)\n",
"scaler = joblib.load(scaler_path)\n",
"print(\"LSTM model and scaler loaded successfully!\")\n",
"\n",
"\n",
"# Download recent AAPL data (last 3 months)\n",
"\n",
"data = yf.download(\"AAPL\", period=\"3mo\", auto_adjust=False)\n",
"recent_prices = data['Adj Close'].values.astype(float)\n",
"print(f\"Downloaded {len(recent_prices)} recent price points\")\n",
"\n",
"\n",
"# Prepare last 60 days for input\n",
"\n",
"last_60_days = recent_prices[-60:].reshape(-1, 1)\n",
"last_60_scaled = scaler.transform(last_60_days)\n",
"\n",
"\n",
"# 7-Day Forecast with daily change smoothing\n",
"\n",
"predictions = []\n",
"current_seq = last_60_scaled.copy()\n",
"last_price = last_60_days[-1][0]\n",
"\n",
"MAX_DAILY_CHANGE = 0.02 # ±2% daily change\n",
"\n",
"for day in range(7):\n",
" # Predict next day\n",
" input_data = current_seq.reshape(1, 60, 1)\n",
" pred_scaled = model.predict(input_data, verbose=0)\n",
" pred_price_raw = scaler.inverse_transform(pred_scaled)[0][0]\n",
"\n",
" # Smooth prediction to prevent extreme jumps\n",
" change = pred_price_raw - last_price\n",
" change = np.clip(change, -MAX_DAILY_CHANGE*last_price, MAX_DAILY_CHANGE*last_price)\n",
" anchored_price = last_price + change\n",
" predictions.append(anchored_price)\n",
"\n",
" # Update sequence for next step\n",
" pred_scaled_reshaped = scaler.transform(np.array([[anchored_price]]))\n",
" current_seq = np.append(current_seq[1:], pred_scaled_reshaped, axis=0)\n",
" last_price = anchored_price\n",
"\n",
"\n",
"# Prepare results dataframe\n",
"\n",
"prediction_dates = pd.date_range(start=data.index[-1] + pd.Timedelta(days=1), periods=7)\n",
"results_df = pd.DataFrame({\n",
" 'Date': prediction_dates,\n",
" 'Predicted_Price': np.round(predictions, 2)\n",
"})\n",
"\n",
"\n",
"# Display 7-Day Forecast\n",
"\n",
"print(\"\\nLSTM - 7-Day Forecast\")\n",
"print(\"=\"*50)\n",
"print(results_df.to_string(index=False))\n"
]
}
]
} |