-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
157 lines (124 loc) · 4.44 KB
/
Copy pathapp.py
File metadata and controls
157 lines (124 loc) · 4.44 KB
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
from flask import Flask, render_template, request
import yfinance as yf
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
app = Flask(__name__)
# ---------------- RSI FUNCTION ----------------
def calculate_RSI(series, period=14):
delta = series.diff()
gain = delta.clip(lower=0)
loss = -1 * delta.clip(upper=0)
avg_gain = gain.rolling(window=period, min_periods=period).mean()
avg_loss = loss.rolling(window=period, min_periods=period).mean()
rs = avg_gain / avg_loss
rsi = 100 - (100 / (1 + rs))
return rsi
# ---------------- INDICATORS ----------------
def calculate_indicators(df):
df["SMA20"] = df["Close"].rolling(20).mean()
df["SMA50"] = df["Close"].rolling(50).mean()
df["RSI"] = calculate_RSI(df["Close"])
df["RSI"].fillna(50, inplace=True)
return df
# ---------------- PREDICTION LOGIC ----------------
def predict_trend(df):
# Basic guards
if df is None or df.empty:
return "Insufficient data"
df_valid = df.dropna()
if df_valid.empty or len(df_valid) < 2:
return "Insufficient data"
last = df_valid.iloc[-1]
prev = df_valid.iloc[-2]
def _to_scalar(val):
# handle pd.Series, np.ndarray or single-value containers
if isinstance(val, (pd.Series, np.ndarray)):
try:
return float(val.item())
except Exception:
# fallback: take last element if possible
try:
return float(val.iloc[-1])
except Exception:
return None
try:
return float(val)
except Exception:
return None
rsi = _to_scalar(last.get("RSI"))
sma20 = _to_scalar(last.get("SMA20"))
sma50 = _to_scalar(last.get("SMA50"))
close = _to_scalar(last.get("Close"))
prev_close = _to_scalar(prev.get("Close"))
if None in (rsi, sma20, sma50, close, prev_close):
return "Insufficient data"
if rsi < 65 and sma20 > sma50 and close > prev_close:
return "UP (Bullish)"
elif rsi > 70 and sma20 < sma50 and close < prev_close:
return "DOWN (Bearish)"
elif sma20 > sma50:
return "Mild UP"
elif sma20 < sma50:
return "Mild DOWN"
else:
return "Sideways"
# ---------------- CHART WITH EXPLANATION ----------------
def create_plot(df, ticker, prediction):
sma20 = df["SMA20"].iloc[-1]
sma50 = df["SMA50"].iloc[-1]
rsi = df["RSI"].iloc[-1]
plt.figure(figsize=(10, 5))
plt.plot(df.index, df["Close"], label="Close Price")
plt.plot(df.index, df["SMA20"], label="SMA 20")
plt.plot(df.index, df["SMA50"], label="SMA 50")
explanation = (
f"Prediction: {prediction}\n"
f"RSI: {rsi:.2f}\n"
f"SMA20: {sma20:.2f}\n"
f"SMA50: {sma50:.2f}\n\n"
"Logic:\n"
"• SMA20 vs SMA50 → Trend\n"
"• RSI → Momentum\n"
"• Price change → Strength"
)
plt.text(
0.02, 0.95,
explanation,
transform=plt.gca().transAxes,
fontsize=9,
verticalalignment="top",
bbox=dict(boxstyle="round", facecolor="white", alpha=0.85)
)
plt.title(f"{ticker} Stock Trend Analysis")
plt.xlabel("Date")
plt.ylabel("Price")
plt.legend()
plt.grid(True)
plt.savefig("static/plot.png")
plt.close()
# ---------------- FLASK ROUTE ----------------
@app.route("/", methods=["GET", "POST"])
def index():
if request.method == "POST":
ticker = request.form["ticker"]
data = yf.download(ticker, period="6mo")
if data.empty:
return render_template("index.html", error="Invalid stock symbol")
df = calculate_indicators(data.copy())
df = df.dropna()
if df.empty or len(df) < 2:
return render_template("index.html", error="Insufficient data to calculate indicators")
prediction = predict_trend(df)
create_plot(df, ticker, prediction)
table = df.tail(5).reset_index()
table_html = table.to_html(index=False, classes="data-table")
return render_template(
"result.html",
ticker=ticker,
prediction=prediction,
table=table_html
)
return render_template("index.html")
if __name__ == "__main__":
app.run(debug=True)