adpro commited on
Commit
b980261
·
verified ·
1 Parent(s): 427f91a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +65 -58
app.py CHANGED
@@ -1,4 +1,5 @@
1
- import gradio as gr
 
2
  from vnstock import Vnstock
3
  from datetime import datetime, timedelta
4
  import pandas as pd
@@ -8,11 +9,19 @@ import torch
8
  from torch_geometric.data import Data
9
 
10
  vn = Vnstock()
 
 
 
 
 
 
 
 
 
11
 
12
  # ============================
13
- # TECHNICAL INDICATORS
14
  # ============================
15
-
16
  def calc_RSI(series, period=14):
17
  delta = series.diff()
18
  gain = delta.clip(lower=0)
@@ -35,9 +44,8 @@ def calc_bollinger(series, window=20, num_std=2):
35
  return sma, sma + num_std * std, sma - num_std * std
36
 
37
  # ============================
38
- # GNN MODEL
39
  # ============================
40
-
41
  class StockGCN(torch.nn.Module):
42
  def __init__(self, num_features, hidden=16):
43
  super().__init__()
@@ -51,19 +59,19 @@ class StockGCN(torch.nn.Module):
51
  return self.conv2(x, edge)
52
 
53
  # ============================
54
- # API METHODS
55
  # ============================
56
-
57
- def api_history(symbol, start, end):
58
  try:
59
  if end < start:
60
- return {"error": "End date must be >= start date"}
61
 
62
  stock = vn.stock(symbol=symbol)
63
  df = stock.quote.history(start=start, end=end, interval="1D")
64
 
65
  if df is None or df.empty:
66
- return {"error": "No data"}
67
 
68
  if "time" in df.columns:
69
  df = df.rename(columns={"time": "Date"}).set_index("Date")
@@ -72,48 +80,62 @@ def api_history(symbol, start, end):
72
  df = df.rename(columns={"close": "Close"})
73
 
74
  df.index = df.index.astype(str)
75
-
76
  return {"symbol": symbol, "data": df.to_dict()}
77
-
78
  except Exception as e:
79
  return {"error": str(e)}
80
 
81
- def api_ta(symbol, start, end):
 
 
 
 
82
  try:
83
  if end < start:
84
- return {"error": "End date must be >= start date"}
85
 
86
  stock = vn.stock(symbol=symbol)
87
  df = stock.quote.history(start=start, end=end, interval="1D")
88
 
 
 
 
89
  df["RSI"] = calc_RSI(df["close"])
90
  df["MACD"], df["MACD_signal"], df["MACD_hist"] = calc_MACD(df["close"])
91
  df["BB_MID"], df["BB_UPPER"], df["BB_LOWER"] = calc_bollinger(df["close"])
92
 
93
  df = df.fillna(None)
94
  df.index = df.index.astype(str)
95
-
96
  return {"symbol": symbol, "indicators": df.to_dict()}
97
-
98
  except Exception as e:
99
  return {"error": str(e)}
100
 
101
- def api_gnn(symbol, days):
 
 
 
 
102
  try:
103
  end = datetime.today()
104
  start = end - timedelta(days=365)
105
 
106
  stock = vn.stock(symbol=symbol)
107
- df = stock.quote.history(start=start.strftime("%Y-%m-%d"),
108
- end=end.strftime("%Y-%m-%d"),
109
- interval="1D")
110
- df = df.rename(columns={"close": "Close"}).dropna()
 
111
 
 
 
 
 
112
  scaler = MinMaxScaler()
113
  df_scaled = scaler.fit_transform(df[["Close"]])
114
 
115
- edge_index = torch.tensor([[i, i+1] for i in range(len(df_scaled)-1)],
116
- dtype=torch.long).t()
 
 
117
 
118
  x = torch.tensor(df_scaled, dtype=torch.float)
119
  data_obj = Data(x=x, edge_index=edge_index)
@@ -128,7 +150,7 @@ def api_gnn(symbol, days):
128
  new_obj = Data(
129
  x=torch.cat([data_obj.x, last_value]),
130
  edge_index=torch.tensor(
131
- [[i, i+1] for i in range(len(data_obj.x))],
132
  dtype=torch.long
133
  ).t()
134
  )
@@ -136,9 +158,14 @@ def api_gnn(symbol, days):
136
  last_value = out[-1].view(1, 1)
137
  preds_scaled.append(last_value.item())
138
 
139
- preds_real = scaler.inverse_transform(np.array(preds_scaled).reshape(-1, 1)).flatten()
 
 
140
 
141
- dates = [(end + timedelta(days=i+1)).strftime("%Y-%m-%d") for i in range(days)]
 
 
 
142
 
143
  return {
144
  "symbol": symbol,
@@ -146,41 +173,21 @@ def api_gnn(symbol, days):
146
  "predictions": [
147
  {"date": d, "price": float(p)}
148
  for d, p in zip(dates, preds_real)
149
- ]
150
  }
151
-
152
  except Exception as e:
153
  return {"error": str(e)}
154
 
155
  # ============================
156
- # GRADIO APP (API ENABLED)
157
  # ============================
158
-
159
- with gr.Blocks() as app:
160
- gr.Markdown("# 📈 VNStock API (Gradio on HuggingFace)")
161
-
162
- with gr.Tab("History API"):
163
- sym = gr.Text(label="Symbol")
164
- start = gr.Text(label="Start (YYYY-MM-DD)")
165
- end = gr.Text(label="End (YYYY-MM-DD)")
166
- out = gr.JSON(label="Result")
167
- btn = gr.Button("Get History")
168
- btn.click(api_history, [sym, start, end], out).api_name = "api_history"
169
-
170
- with gr.Tab("Technical Analysis API"):
171
- sym2 = gr.Text(label="Symbol")
172
- start2 = gr.Text(label="Start (YYYY-MM-DD)")
173
- end2 = gr.Text(label="End (YYYY-MM-DD)")
174
- out2 = gr.JSON(label="Result")
175
- btn2 = gr.Button("Get Indicators")
176
- btn2.click(api_ta, [sym2, start2, end2], out2).api_name = "api_ta"
177
-
178
- with gr.Tab("GNN Prediction API"):
179
- sym3 = gr.Text(label="Symbol")
180
- days3 = gr.Number(label="Days to Predict", value=7)
181
- out3 = gr.JSON(label="Result")
182
- btn3 = gr.Button("Predict GNN")
183
- btn3.click(api_gnn, [sym3, days3], out3).api_name = "api_gnn"
184
-
185
- # 🚀 RUN ON HUGGINGFACE — KHÔNG share=True
186
- app.launch()
 
1
+ from fastapi import FastAPI
2
+ from fastapi.middleware.cors import CORSMiddleware
3
  from vnstock import Vnstock
4
  from datetime import datetime, timedelta
5
  import pandas as pd
 
9
  from torch_geometric.data import Data
10
 
11
  vn = Vnstock()
12
+ app = FastAPI(title="mFund VNStock API", version="1.0")
13
+
14
+ app.add_middleware(
15
+ CORSMiddleware,
16
+ allow_origins=["*"],
17
+ allow_credentials=True,
18
+ allow_methods=["*"],
19
+ allow_headers=["*"],
20
+ )
21
 
22
  # ============================
23
+ # Chỉ báo kỹ thuật
24
  # ============================
 
25
  def calc_RSI(series, period=14):
26
  delta = series.diff()
27
  gain = delta.clip(lower=0)
 
44
  return sma, sma + num_std * std, sma - num_std * std
45
 
46
  # ============================
47
+ # Mô hình GNN đơn giản
48
  # ============================
 
49
  class StockGCN(torch.nn.Module):
50
  def __init__(self, num_features, hidden=16):
51
  super().__init__()
 
59
  return self.conv2(x, edge)
60
 
61
  # ============================
62
+ # 1) GET /stock/history
63
  # ============================
64
+ @app.get("/stock/history")
65
+ def get_history(symbol: str, start: str, end: str):
66
  try:
67
  if end < start:
68
+ return {"error": "end must be >= start"}
69
 
70
  stock = vn.stock(symbol=symbol)
71
  df = stock.quote.history(start=start, end=end, interval="1D")
72
 
73
  if df is None or df.empty:
74
+ return {"error": "no data"}
75
 
76
  if "time" in df.columns:
77
  df = df.rename(columns={"time": "Date"}).set_index("Date")
 
80
  df = df.rename(columns={"close": "Close"})
81
 
82
  df.index = df.index.astype(str)
 
83
  return {"symbol": symbol, "data": df.to_dict()}
 
84
  except Exception as e:
85
  return {"error": str(e)}
86
 
87
+ # ============================
88
+ # 2) GET /stock/ta
89
+ # ============================
90
+ @app.get("/stock/ta")
91
+ def get_ta(symbol: str, start: str, end: str):
92
  try:
93
  if end < start:
94
+ return {"error": "end must be >= start"}
95
 
96
  stock = vn.stock(symbol=symbol)
97
  df = stock.quote.history(start=start, end=end, interval="1D")
98
 
99
+ if df is None or df.empty:
100
+ return {"error": "no data"}
101
+
102
  df["RSI"] = calc_RSI(df["close"])
103
  df["MACD"], df["MACD_signal"], df["MACD_hist"] = calc_MACD(df["close"])
104
  df["BB_MID"], df["BB_UPPER"], df["BB_LOWER"] = calc_bollinger(df["close"])
105
 
106
  df = df.fillna(None)
107
  df.index = df.index.astype(str)
 
108
  return {"symbol": symbol, "indicators": df.to_dict()}
 
109
  except Exception as e:
110
  return {"error": str(e)}
111
 
112
+ # ============================
113
+ # 3) GET /stock/gnn
114
+ # ============================
115
+ @app.get("/stock/gnn")
116
+ def get_gnn(symbol: str, days: int = 7):
117
  try:
118
  end = datetime.today()
119
  start = end - timedelta(days=365)
120
 
121
  stock = vn.stock(symbol=symbol)
122
+ df = stock.quote.history(
123
+ start=start.strftime("%Y-%m-%d"),
124
+ end=end.strftime("%Y-%m-%d"),
125
+ interval="1D"
126
+ )
127
 
128
+ if df is None or df.empty:
129
+ return {"error": "no data"}
130
+
131
+ df = df.rename(columns={"close": "Close"}).dropna()
132
  scaler = MinMaxScaler()
133
  df_scaled = scaler.fit_transform(df[["Close"]])
134
 
135
+ edge_index = torch.tensor(
136
+ [[i, i + 1] for i in range(len(df_scaled) - 1)],
137
+ dtype=torch.long
138
+ ).t()
139
 
140
  x = torch.tensor(df_scaled, dtype=torch.float)
141
  data_obj = Data(x=x, edge_index=edge_index)
 
150
  new_obj = Data(
151
  x=torch.cat([data_obj.x, last_value]),
152
  edge_index=torch.tensor(
153
+ [[i, i + 1] for i in range(len(data_obj.x))],
154
  dtype=torch.long
155
  ).t()
156
  )
 
158
  last_value = out[-1].view(1, 1)
159
  preds_scaled.append(last_value.item())
160
 
161
+ preds_real = scaler.inverse_transform(
162
+ np.array(preds_scaled).reshape(-1, 1)
163
+ ).flatten()
164
 
165
+ dates = [
166
+ (end + timedelta(days=i + 1)).strftime("%Y-%m-%d")
167
+ for i in range(days)
168
+ ]
169
 
170
  return {
171
  "symbol": symbol,
 
173
  "predictions": [
174
  {"date": d, "price": float(p)}
175
  for d, p in zip(dates, preds_real)
176
+ ],
177
  }
 
178
  except Exception as e:
179
  return {"error": str(e)}
180
 
181
  # ============================
182
+ # Root
183
  # ============================
184
+ @app.get("/")
185
+ def root():
186
+ return {
187
+ "message": "mFund VNStock FastAPI is running",
188
+ "endpoints": [
189
+ "/stock/history?symbol=FPT&start=2023-01-01&end=2023-12-31",
190
+ "/stock/ta?symbol=HPG&start=2023-01-01&end=2023-12-31",
191
+ "/stock/gnn?symbol=VNM&days=7",
192
+ ],
193
+ }