Spaces:
Sleeping
Sleeping
File size: 9,648 Bytes
b33ff8e ab7df0f 886d114 ab7df0f b33ff8e ab7df0f b33ff8e ab7df0f b33ff8e ab7df0f b33ff8e ab7df0f b33ff8e |
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 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 |
import yfinance as yf
from datetime import datetime, timedelta
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_absolute_error
from flask import Flask, request, render_template_string
# Create a Flask application instance
app = Flask(__name__)
# =============== Data Fetching ===============
def fetch_stock_data(symbol, period="5y"):
"""Fetch historical stock data from Yahoo Finance"""
stock = yf.Ticker(symbol)
data = stock.history(period=period)
data = data.sort_index(ascending=True)
return data
# =============== Technical Indicators ===============
def calculate_moving_averages(data):
data["50MA"] = data["Close"].rolling(window=50).mean()
data["200MA"] = data["Close"].rolling(window=200).mean()
return data
def determin_trend(data):
if (
data["50MA"].iloc[-1] > data["200MA"].iloc[-1]
and data["Close"].iloc[-1] > data["50MA"].iloc[-1]
):
trend = "UPTREND (bullish for next 1-3 months)"
elif (
data["50MA"].iloc[-1] < data["200MA"].iloc[-1]
and data["Close"].iloc[-1] < data["50MA"].iloc[-1]
):
trend = "DOWNTREND (bearish for next 1-3 months)"
else:
trend = "SIDEWAYS (uncertain)"
return trend
def calculate_RSI(data, window=14):
delta = data["Close"].diff()
gain = delta.where(delta > 0, 0)
loss = -delta.where(delta < 0, 0)
avg_gain = gain.rolling(window=window).mean()
avg_loss = loss.rolling(window=window).mean()
rs = avg_gain / avg_loss
data["RSI"] = 100 - (100 / (1 + rs))
return data
def calculate_MACD(data, fast=12, slow=26, signal=9):
data["EMA_fast"] = data["Close"].ewm(span=fast, adjust=False).mean()
data["EMA_slow"] = data["Close"].ewm(span=slow, adjust=False).mean()
data["MACD"] = data["EMA_fast"] - data["EMA_slow"]
data["MACD_signal"] = data["MACD"].ewm(span=signal, adjust=False).mean()
return data
# =============== Random Forest Forecast ===============
"""
This function uses a Random Forest ML model to learn from
historical stock indicators and predict stock prices for the next 30 days.
"""
def random_forest_forecast(data, days_ahead=30):
"""
Predict future stock prices using Random Forest Regressor
"""
df = data.copy()
# next-day close as target
df["Target"] = df["Close"].shift(-1)
# Drop last row with NaN target
df = df.dropna()
# Features (you can add more indicators here)
features = ["Close", "50MA", "200MA", "RSI", "MACD", "MACD_signal"]
# drop rows with NaN from indicators
df = df.dropna()
# Feature matrix and target vector
X = df[features]
y = df["Target"]
# Train/test split
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, shuffle=False
)
# Train model
model = RandomForestRegressor(n_estimators=200, random_state=42)
model.fit(X_train, y_train)
# Evaluate
y_pred = model.predict(X_test)
mae = mean_absolute_error(y_test, y_pred)
print(f"Random Forest MAE: {mae:.2f}")
# Forecast future price iteratively
last_known = X.iloc[-1].values.reshape(1, -1)
forecast_prices = []
for _ in range(days_ahead):
pred = model.predict(last_known)[0]
forecast_prices.append(pred)
# update only Close for simplicity
last_known[0, 0] = pred
return forecast_prices[-1], forecast_prices
# =============== Entry / Stoploss ===============
def calculate_entry_stoploss(data, trend, stoploss_percent=5):
entry_price = None
stop_loss = None
if (
trend.startswith("UPTREND")
and data["RSI"].iloc[-1] < 70
and data["MACD"].iloc[-1] > data["MACD_signal"].iloc[-1]
):
entry_price = data["Close"].iloc[-1]
stop_loss = entry_price * (1 - stoploss_percent / 100)
return entry_price, stop_loss
# =============== Flask Routes ===============
@app.route("/", methods=["GET", "POST"])
def index():
stocks = {
"Reliance Industries": "RELIANCE.NS",
"Infosys": "INFY.NS",
"TCS": "TCS.NS",
"HDFC Bank": "HDFCBANK.NS",
"Ola Electric": "OLAELEC.NS",
}
result = None
table_html = None
if request.method == "POST":
selected_symbol = request.form["symbol"]
data = fetch_stock_data(selected_symbol)
data = calculate_moving_averages(data)
data = calculate_RSI(data)
data = calculate_MACD(data)
trend = determin_trend(data)
# Random Forest Forecast
predicted_price, _ = random_forest_forecast(data)
# Entry & Stoploss
entry_price, stop_loss = calculate_entry_stoploss(data, trend)
current_price = data["Close"].iloc[-1]
price_difference = predicted_price - current_price
profit_or_loss = ((predicted_price - current_price) / current_price) * 100
table_html = (
data.tail(30)
.reset_index()
.to_html(classes="table table-striped table-bordered", index=False)
)
result = {
"symbol": selected_symbol,
"trend": trend,
"current_price": f"{current_price:.2f}",
"predicted_price": f"{predicted_price:.2f}",
"price_difference": f"{price_difference:.2f}",
"profit_or_loss": f"{profit_or_loss:.2f}%",
"entry_price": f"{entry_price:.2f}" if entry_price else "No Entry Signal",
"stop_loss": f"{stop_loss:.2f}" if stop_loss else "-",
"date_now": data.index[-1].date(),
"future_date": datetime.now().date() + timedelta(days=30),
}
return render_template_string(
"""
<html>
<head>
<title>Stock Predictor</title>
<link rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css">
<style>
body { padding: 30px; }
th, td { text-align: center; }
.result-card { margin-top: 40px; }
/* Loader overlay */
#loader-overlay {
display: none;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(255, 255, 255, 0.8);
z-index: 9999;
justify-content: center;
align-items: center;
flex-direction: column;
}
</style>
</head>
<body>
<div id="loader-overlay">
<div class="spinner-border text-primary" role="status" style="width: 4rem; height: 4rem;"></div>
<p class="mt-3 fw-bold text-primary">Predicting...</p>
</div>
<div class="container">
<h3 class="text-center mb-4">Stock Prediction Dashboard</h3>
<form method="POST" class="text-center mb-4" onsubmit="showLoader()">
<div class="row justify-content-center">
<div class="col-md-4">
<select name="symbol" class="form-select">
{% for name, sym in stocks.items() %}
<option value="{{ sym }}"
{% if result and result.symbol == sym %}selected{% endif %}>
{{ name }} ({{ sym }})
</option>
{% endfor %}
</select>
</div>
<div class="col-md-2">
<button type="submit" class="btn btn-primary w-100">Predict</button>
</div>
</div>
</form>
{% if result %}
<div class="card result-card shadow">
<div class="card-body">
<h5 class="card-title text-center">Report for {{ result.symbol }}</h5>
<p><b>Trend:</b> {{ result.trend }}</p>
<p><b>Current Price:</b> ₹{{ result.current_price }} ({{ result.date_now }})</p>
<p><b>Predicted Price (Next 30 Days):</b> ₹{{ result.predicted_price }} ({{ result.future_date }})</p>
<p><b>Price Difference:</b> ₹{{ result.price_difference }}</p>
<p><b>Expected Return:</b> {{ result.profit_or_loss }}</p>
<p><b>Entry Price:</b> {{ result.entry_price }}</p>
<p><b>Stop Loss:</b> {{ result.stop_loss }}</p>
</div>
</div>
<div class="mt-4">
<h5>Last 30 Days Data</h5>
{{ table_html | safe }}
</div>
{% endif %}
</div>
<script>
function showLoader() {
document.getElementById("loader-overlay").style.display = "flex";
}
</script>
</body>
</html>
""",
stocks=stocks,
result=result,
table_html=table_html,
)
# Run the app in debug mode
if __name__ == "__main__":
# Run on local host
# app.run(debug=True)
# Run using public IP
# app.run(host="0.0.0.0", port=5000, debug=True)
# Hugging Face uses port 7860 by default
app.run(host="0.0.0.0", port=7860)
|