camphong24032002 commited on
Commit
8315578
·
1 Parent(s): e565da6

feat: update macd data

Browse files
Files changed (3) hide show
  1. models/macd.py +5 -0
  2. routes/data.py +24 -0
  3. services/indicator.py +78 -0
models/macd.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ from pydantic import BaseModel
2
+
3
+
4
+ class MACDPayload(BaseModel):
5
+ symbol: str
routes/data.py CHANGED
@@ -2,6 +2,7 @@ from services.indicator import Indicator
2
  from models.ichimoku import IchimokuPayload
3
  from models.rsi import RSIPayload
4
  from models.price import PricePayload
 
5
  from fastapi import status, APIRouter
6
  from typing import Sequence
7
  import json
@@ -45,6 +46,15 @@ async def update_entire_rsi():
45
  Indicator.update_entire_rsi()
46
 
47
 
 
 
 
 
 
 
 
 
 
48
  @router.post(
49
  "/get_price",
50
  name="Get price",
@@ -74,6 +84,20 @@ async def get_rsi_data(payload: RSIPayload) -> Sequence[dict]:
74
  return json.loads(rsi_df.to_json(orient="records"))
75
 
76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
  @router.post(
78
  "/get_ichimoku",
79
  name="Get data of Ichimoku cloud",
 
2
  from models.ichimoku import IchimokuPayload
3
  from models.rsi import RSIPayload
4
  from models.price import PricePayload
5
+ from models.macd import MACDPayload
6
  from fastapi import status, APIRouter
7
  from typing import Sequence
8
  import json
 
46
  Indicator.update_entire_rsi()
47
 
48
 
49
+ @router.get(
50
+ "/update_entire_macd",
51
+ name="Update entire macd data",
52
+ status_code=status.HTTP_200_OK
53
+ )
54
+ async def update_entire_macd():
55
+ Indicator.update_entire_macd()
56
+
57
+
58
  @router.post(
59
  "/get_price",
60
  name="Get price",
 
84
  return json.loads(rsi_df.to_json(orient="records"))
85
 
86
 
87
+ @router.post(
88
+ "/get_macd",
89
+ name="Get data of MACD",
90
+ status_code=status.HTTP_200_OK
91
+ )
92
+ async def get_macd_data(payload: MACDPayload) -> Sequence[dict]:
93
+ macd_df = Indicator.get_macd(
94
+ payload.symbol
95
+ )
96
+ if macd_df is None:
97
+ return [{"message": "Error"}]
98
+ return json.loads(macd_df.to_json(orient="records"))
99
+
100
+
101
  @router.post(
102
  "/get_ichimoku",
103
  name="Get data of Ichimoku cloud",
services/indicator.py CHANGED
@@ -105,6 +105,7 @@ class Indicator:
105
  for value in data:
106
  lst_symbols.append(value["cell"][2].strip())
107
  if weekday < 5 and hour < 12:
 
108
  return
109
  end_date = datetime_now.date()
110
  delta = timedelta(days=300)
@@ -114,6 +115,7 @@ class Indicator:
114
  lst_time = []
115
  lst_values = []
116
  if len(lst_symbols) != 100:
 
117
  return
118
  for symbol in lst_symbols:
119
  df = longterm_ohlc_data(symbol,
@@ -201,6 +203,7 @@ class Indicator:
201
  "D",
202
  "stock").reset_index(drop=True)
203
  if tmp_df.shape[0] == 0:
 
204
  return
205
  last_date = str(tmp_df["time"])
206
  newest_record = \
@@ -237,10 +240,12 @@ class Indicator:
237
  for value in data:
238
  lst_symbols.append(value["cell"][2].strip())
239
  if weekday < 5 and hour < 12:
 
240
  return
241
  get_time = True
242
  lst_values = {}
243
  if len(lst_symbols) != 100:
 
244
  return
245
  cnt = 0
246
  for symbol in lst_symbols:
@@ -317,6 +322,79 @@ class Indicator:
317
  def stoch_rsi_smooth_d(stoch_rsi_k: pd.Series, d: int) -> pd.Series:
318
  return stoch_rsi_k.rolling(window=d).mean()
319
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
320
  @staticmethod
321
  def get_ichimoku_cloud(
322
  df: pd.DataFrame,
 
105
  for value in data:
106
  lst_symbols.append(value["cell"][2].strip())
107
  if weekday < 5 and hour < 12:
108
+ updating_price = False
109
  return
110
  end_date = datetime_now.date()
111
  delta = timedelta(days=300)
 
115
  lst_time = []
116
  lst_values = []
117
  if len(lst_symbols) != 100:
118
+ updating_price = False
119
  return
120
  for symbol in lst_symbols:
121
  df = longterm_ohlc_data(symbol,
 
203
  "D",
204
  "stock").reset_index(drop=True)
205
  if tmp_df.shape[0] == 0:
206
+ updating_rsi = False
207
  return
208
  last_date = str(tmp_df["time"])
209
  newest_record = \
 
240
  for value in data:
241
  lst_symbols.append(value["cell"][2].strip())
242
  if weekday < 5 and hour < 12:
243
+ updating_rsi = False
244
  return
245
  get_time = True
246
  lst_values = {}
247
  if len(lst_symbols) != 100:
248
+ updating_rsi = False
249
  return
250
  cnt = 0
251
  for symbol in lst_symbols:
 
322
  def stoch_rsi_smooth_d(stoch_rsi_k: pd.Series, d: int) -> pd.Series:
323
  return stoch_rsi_k.rolling(window=d).mean()
324
 
325
+ @staticmethod
326
+ def update_entire_macd() -> None:
327
+ global updating_macd
328
+ if updating_macd:
329
+ return
330
+ updating_macd = True
331
+ datetime_now = datetime.utcnow()
332
+ hour = datetime_now.hour
333
+ weekday = datetime_now.weekday()
334
+ try:
335
+ data = requests.get(VN100_URL).json()
336
+ data = data["rows"]
337
+ lst_symbols = []
338
+ for value in data:
339
+ lst_symbols.append(value["cell"][2].strip())
340
+ if weekday < 5 and hour < 12:
341
+ updating_macd = False
342
+ return
343
+ get_time = True
344
+ lst_values = {}
345
+ if len(lst_symbols) != 100:
346
+ updating_macd = False
347
+ return
348
+ cnt = 0
349
+ for symbol in lst_symbols:
350
+ cnt += 1
351
+ url = PREFIX + INDICATORS["MACD"] \
352
+ + f"?stockSymbol={symbol}&rangeSelector=3&fastPeriod=12&slowPeriod=26&signalPeriod=9"
353
+ data = requests.get(url).json()
354
+ rsi_df = pd.DataFrame(
355
+ data["SeriesColection"][0]["Points"]).tail(5)
356
+ if get_time:
357
+ lst_values["time"] = \
358
+ rsi_df["Time"].apply(lambda x:
359
+ Utility.ts_to_date(x/1000))
360
+ get_time = False
361
+ lst_values[symbol] = rsi_df["Value"].apply(lambda x: int(x[0]))
362
+ df = pd.DataFrame(lst_values)
363
+ records = df.to_dict(orient="records")
364
+ uri = os.environ.get("MONGODB_URI")
365
+ client = MongoClient(uri)
366
+ database = client.get_database("data")
367
+ collection = database.get_collection("macd")
368
+ if "macd" in database.list_collection_names():
369
+ collection.drop()
370
+ collection.insert_many(records)
371
+ print("Updated entire MACD")
372
+ updating_macd = False
373
+ except Exception as e:
374
+ print(f"Error: {e}")
375
+ updating_macd = False
376
+
377
+ @staticmethod
378
+ def get_macd(
379
+ symbol: str,
380
+ ) -> pd.DataFrame:
381
+ try:
382
+ symbol = symbol.upper()
383
+ uri = os.environ.get("MONGODB_URI")
384
+ client = MongoClient(uri)
385
+ database = client.get_database("data")
386
+ collection = database.get_collection("macd")
387
+ try:
388
+ records = list(collection.find())
389
+ except Exception as e:
390
+ print(f"Error: {e}")
391
+ record_df = pd.DataFrame(records).drop(columns=["_id"])
392
+ record_df = \
393
+ record_df[["time", symbol]].rename(columns={symbol: "macd"})
394
+ return record_df
395
+ except Exception:
396
+ return None
397
+
398
  @staticmethod
399
  def get_ichimoku_cloud(
400
  df: pd.DataFrame,