adpro commited on
Commit
d40eb94
·
verified ·
1 Parent(s): f8a636f

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +178 -0
app.py ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from vnstock import Vnstock
3
+ from datetime import datetime, timedelta
4
+ import pandas as pd
5
+ import numpy as np
6
+ from sklearn.linear_model import LinearRegression
7
+ from sklearn.preprocessing import MinMaxScaler
8
+ import torch
9
+ from torch_geometric.data import Data
10
+
11
+ vn = Vnstock()
12
+
13
+ # ============================
14
+ # TECHNICAL INDICATORS
15
+ # ============================
16
+ def calc_RSI(series, period=14):
17
+ delta = series.diff()
18
+ gain = delta.clip(lower=0)
19
+ loss = -delta.clip(upper=0)
20
+
21
+ avg_gain = gain.rolling(period).mean()
22
+ avg_loss = loss.rolling(period).mean()
23
+
24
+ RS = avg_gain / avg_loss
25
+ RSI = 100 - (100 / (1 + RS))
26
+ return RSI
27
+
28
+ def calc_MACD(series, fast=12, slow=26, signal=9):
29
+ ema_fast = series.ewm(span=fast, adjust=False).mean()
30
+ ema_slow = series.ewm(span=slow, adjust=False).mean()
31
+ macd = ema_fast - ema_slow
32
+ signal_line = macd.ewm(span=signal, adjust=False).mean()
33
+ hist = macd - signal_line
34
+ return macd, signal_line, hist
35
+
36
+ def calc_bollinger(series, window=20, num_std=2):
37
+ sma = series.rolling(window).mean()
38
+ std = series.rolling(window).std()
39
+ upper = sma + num_std * std
40
+ lower = sma - num_std * std
41
+ return sma, upper, lower
42
+
43
+ # ============================
44
+ # GNN MODEL
45
+ # ============================
46
+ class StockGCN(torch.nn.Module):
47
+ def __init__(self, num_features, hidden=16):
48
+ super().__init__()
49
+ from torch_geometric.nn import GCNConv
50
+ self.conv1 = GCNConv(num_features, hidden)
51
+ self.conv2 = GCNConv(hidden, 1)
52
+
53
+ def forward(self, data):
54
+ x, edge = data.x, data.edge_index
55
+ x = torch.relu(self.conv1(x, edge))
56
+ x = self.conv2(x, edge)
57
+ return x
58
+
59
+ # ============================
60
+ # API IMPLEMENTATION
61
+ # ============================
62
+
63
+ def api_history(symbol, start, end):
64
+ try:
65
+ stock = vn.stock(symbol=symbol)
66
+ df = stock.quote.history(start=start, end=end, interval="1D")
67
+
68
+ if "close" in df.columns:
69
+ df = df.rename(columns={"close": "Close"})
70
+ if "time" in df.columns:
71
+ df = df.rename(columns={"time": "Date"}).set_index("Date")
72
+
73
+ return df.to_dict()
74
+ except Exception as e:
75
+ return {"error": str(e)}
76
+
77
+ def api_ta(symbol, start, end):
78
+ try:
79
+ stock = vn.stock(symbol=symbol)
80
+ df = stock.quote.history(start=start, end=end, interval="1D")
81
+
82
+ df["RSI"] = calc_RSI(df["close"])
83
+ df["MACD"], df["MACD_signal"], df["MACD_hist"] = calc_MACD(df["close"])
84
+ df["BB_MID"], df["BB_UPPER"], df["BB_LOWER"] = calc_bollinger(df["close"])
85
+
86
+ return df.fillna(None).to_dict()
87
+ except Exception as e:
88
+ return {"error": str(e)}
89
+
90
+ def api_gnn(symbol, days):
91
+ try:
92
+ end = datetime.today()
93
+ start = end - timedelta(days=365)
94
+
95
+ stock = vn.stock(symbol=symbol)
96
+ df = stock.quote.history(start=start.strftime("%Y-%m-%d"),
97
+ end=end.strftime("%Y-%m-%d"),
98
+ interval="1D")
99
+ df = df.rename(columns={"close": "Close"})
100
+ df = df[["Close"]].dropna()
101
+
102
+ scaler = MinMaxScaler()
103
+ scaled = scaler.fit_transform(df.values)
104
+ df_scaled = pd.DataFrame(scaled, index=df.index, columns=["Close"])
105
+
106
+ # build graph chain
107
+ edge_index = torch.tensor([[i, i+1] for i in range(len(df_scaled)-1)],
108
+ dtype=torch.long).t().contiguous()
109
+
110
+ x = torch.tensor(df_scaled.values, dtype=torch.float)
111
+ data_obj = Data(x=x, edge_index=edge_index)
112
+
113
+ model = StockGCN(num_features=1)
114
+ model.eval()
115
+
116
+ preds_scaled = []
117
+ last_value = torch.tensor([[df_scaled.values[-1][0]]], dtype=torch.float)
118
+
119
+ for _ in range(days):
120
+ new_data = Data(
121
+ x=torch.cat([data_obj.x, last_value]),
122
+ edge_index=torch.tensor(
123
+ [[i, i+1] for i in range(len(data_obj.x))],
124
+ dtype=torch.long
125
+ ).t().contiguous()
126
+ )
127
+ out = model(new_data)
128
+ last_value = out[-1].view(1, 1)
129
+ preds_scaled.append(last_value.item())
130
+
131
+ preds_real = scaler.inverse_transform(
132
+ np.array(preds_scaled).reshape(-1, 1)
133
+ ).flatten()
134
+
135
+ dates = [(end + timedelta(days=i+1)).strftime("%Y-%m-%d") for i in range(days)]
136
+
137
+ return {
138
+ "symbol": symbol,
139
+ "today_close": float(df["Close"].iloc[-1]),
140
+ "predictions": [
141
+ {"date": d, "price": float(p)}
142
+ for d, p in zip(dates, preds_real)
143
+ ]
144
+ }
145
+ except Exception as e:
146
+ return {"error": str(e)}
147
+
148
+ # ============================
149
+ # GRADIO ROUTES
150
+ # ============================
151
+
152
+ with gr.Blocks() as app:
153
+ gr.Markdown("# 📈 VNStock API (Gradio on HuggingFace)")
154
+
155
+ with gr.Tab("History API"):
156
+ sym = gr.Text(label="Symbol")
157
+ start = gr.Text(label="Start")
158
+ end = gr.Text(label="End")
159
+ out = gr.JSON(label="Result")
160
+ btn = gr.Button("Get History")
161
+ btn.click(api_history, [sym, start, end], out)
162
+
163
+ with gr.Tab("Technical Analysis API"):
164
+ sym2 = gr.Text(label="Symbol")
165
+ start2 = gr.Text(label="Start")
166
+ end2 = gr.Text(label="End")
167
+ out2 = gr.JSON(label="Result")
168
+ btn2 = gr.Button("Get Indicators")
169
+ btn2.click(api_ta, [sym2, start2, end2], out2)
170
+
171
+ with gr.Tab("GNN Prediction API"):
172
+ sym3 = gr.Text(label="Symbol")
173
+ days3 = gr.Number(label="Days to Predict", value=7)
174
+ out3 = gr.JSON(label="Result")
175
+ btn3 = gr.Button("Predict GNN")
176
+ btn3.click(api_gnn, [sym3, days3], out3)
177
+
178
+ app.launch()