camphong24032002 commited on
Commit
e96d69f
·
1 Parent(s): cc8a14b

Convert date to estimated date

Browse files
Files changed (2) hide show
  1. services/indicator.py +59 -55
  2. services/utils.py +16 -3
services/indicator.py CHANGED
@@ -5,6 +5,7 @@ import numpy as np
5
  from vnstock import longterm_ohlc_data, stock_historical_data, price_board
6
  from pymongo import MongoClient, ASCENDING, DESCENDING
7
  from utils.config import DATE_FORMAT
 
8
  import os
9
  # from dotenv import load_dotenv
10
  # load_dotenv()
@@ -27,7 +28,7 @@ class Indicator:
27
 
28
  @staticmethod
29
  def get_price(symbol: str,
30
- count_back: int = 100,
31
  symbol_type: str = "stock",) -> pd.DataFrame:
32
  resolution = "D"
33
  end_date = datetime.now()
@@ -51,58 +52,61 @@ class Indicator:
51
  smooth_k: int = 3,
52
  smooth_d: int = 3,
53
  ) -> pd.DataFrame:
54
- symbol = symbol.upper()
55
- uri = os.environ.get("MONGODB_URI")
56
- client = MongoClient(uri)
57
- database = client.get_database("data")
58
- collection = database.get_collection("rsi")
59
- datetime_now = datetime.utcnow()
60
- hour = datetime_now.hour
61
- weekday = datetime_now.weekday()
62
- error = False
63
- if weekday < 5 and hour >= 12: # Check if data is updated
64
- newest_record = collection.find_one(sort=[("_id", DESCENDING)])
65
- delta = timedelta(days=20)
66
- start_date = datetime_now - delta
67
- start_date = start_date.strftime(DATE_FORMAT)
68
- end_date = datetime_now.strftime(DATE_FORMAT)
69
- tmp_df = stock_historical_data("MBB", start_date, end_date)
70
- last_date = str(tmp_df["time"].iloc[-1])
71
- if newest_record["time"] != last_date:
72
- try:
73
- lst_symbols = list(newest_record.keys())[2:]
74
- record = {}
75
- record["time"] = last_date
76
- for s in lst_symbols:
77
- url = PREFIX + INDICATORS["RSI"] + f"?stockSymbol={s}&rangeSelector=2&periods={periods}"
78
- data = requests.get(url).json()
79
- lst_rsi = data["SeriesColection"][0]["Points"]
80
- record[s] = lst_rsi[-1]["Value"][0]
81
- collection.find_one_and_delete({}, sort=[("_id", ASCENDING)])
82
- collection.insert_one(record)
83
- print("Updated data")
84
- except Exception:
85
- error = True
86
  try:
87
- records = list(collection.find())
88
- except Exception as e:
89
- print(f"Error: {e}")
90
- print("load successfully")
91
- record_df = pd.DataFrame(records).drop(columns=["_id"])
92
- record_df = \
93
- record_df[["time", symbol]].rename(columns={symbol: "rsi"})
94
- if error:
95
- new_df = price_board(symbol)
96
- value = [last_date, new_df["RSI"][0]]
97
- record_df.loc[len(record_df)] = value
98
- record_df["stoch_rsi"] = \
99
- Indicator.stoch_rsi(record_df["rsi"], periods)
100
- record_df["stoch_rsi_smooth_k"] = \
101
- Indicator.stoch_rsi_smooth_k(record_df["stoch_rsi"], smooth_k)
102
- record_df["stoch_rsi_smooth_d"] = Indicator.stoch_rsi_smooth_d(
103
- record_df["stoch_rsi_smooth_k"], smooth_d
104
- )
105
- return record_df
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
106
 
107
  @staticmethod
108
  def stoch_rsi(rsi: pd.Series, periods: int = 14) -> pd.Series:
@@ -144,9 +148,9 @@ class Indicator:
144
  ) / 2
145
  chikou_span = df["close"].shift(-displacement)
146
 
147
- date_displacement = np.array(
148
- list(map(str, np.arange(1, displacement+1))))
149
- time = np.concatenate((df["time"], date_displacement))
150
  tenkan_sen = np.concatenate((tenkan_sen, space_displacement))
151
  kijun_sen = np.concatenate((kijun_sen, space_displacement))
152
  senkou_span_a = np.concatenate((space_displacement, senkou_span_a))
 
5
  from vnstock import longterm_ohlc_data, stock_historical_data, price_board
6
  from pymongo import MongoClient, ASCENDING, DESCENDING
7
  from utils.config import DATE_FORMAT
8
+ from .utils import Utility
9
  import os
10
  # from dotenv import load_dotenv
11
  # load_dotenv()
 
28
 
29
  @staticmethod
30
  def get_price(symbol: str,
31
+ count_back: int = 200,
32
  symbol_type: str = "stock",) -> pd.DataFrame:
33
  resolution = "D"
34
  end_date = datetime.now()
 
52
  smooth_k: int = 3,
53
  smooth_d: int = 3,
54
  ) -> pd.DataFrame:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
  try:
56
+ symbol = symbol.upper()
57
+ uri = os.environ.get("MONGODB_URI")
58
+ client = MongoClient(uri)
59
+ database = client.get_database("data")
60
+ collection = database.get_collection("rsi")
61
+ datetime_now = datetime.utcnow()
62
+ hour = datetime_now.hour
63
+ weekday = datetime_now.weekday()
64
+ error = False
65
+ if weekday < 5 and hour >= 12: # Check if data is updated
66
+ newest_record = collection.find_one(sort=[("_id", DESCENDING)])
67
+ delta = timedelta(days=20)
68
+ start_date = datetime_now - delta
69
+ start_date = start_date.strftime(DATE_FORMAT)
70
+ end_date = datetime_now.strftime(DATE_FORMAT)
71
+ tmp_df = stock_historical_data(symbol, start_date, end_date)
72
+ last_date = str(tmp_df["time"].iloc[-1])
73
+ if newest_record["time"] != last_date:
74
+ try:
75
+ lst_symbols = list(newest_record.keys())[2:]
76
+ record = {}
77
+ record["time"] = last_date
78
+ for s in lst_symbols:
79
+ url = PREFIX + INDICATORS["RSI"] + f"?stockSymbol={s}&rangeSelector=2&periods={periods}"
80
+ data = requests.get(url).json()
81
+ lst_rsi = data["SeriesColection"][0]["Points"]
82
+ record[s] = lst_rsi[-1]["Value"][0]
83
+ collection.find_one_and_delete({}, sort=[("_id", ASCENDING)])
84
+ collection.insert_one(record)
85
+ print("Updated data")
86
+ except Exception:
87
+ error = True
88
+ try:
89
+ records = list(collection.find())
90
+ except Exception as e:
91
+ print(f"Error: {e}")
92
+ print("load successfully")
93
+ record_df = pd.DataFrame(records).drop(columns=["_id"])
94
+ record_df = \
95
+ record_df[["time", symbol]].rename(columns={symbol: "rsi"})
96
+ if error:
97
+ new_df = price_board(symbol)
98
+ value = [last_date, new_df["RSI"][0]]
99
+ record_df.loc[len(record_df)] = value
100
+ record_df["stoch_rsi"] = \
101
+ Indicator.stoch_rsi(record_df["rsi"], periods)
102
+ record_df["stoch_rsi_smooth_k"] = \
103
+ Indicator.stoch_rsi_smooth_k(record_df["stoch_rsi"], smooth_k)
104
+ record_df["stoch_rsi_smooth_d"] = Indicator.stoch_rsi_smooth_d(
105
+ record_df["stoch_rsi_smooth_k"], smooth_d
106
+ )
107
+ return record_df
108
+ except Exception:
109
+ return None
110
 
111
  @staticmethod
112
  def stoch_rsi(rsi: pd.Series, periods: int = 14) -> pd.Series:
 
148
  ) / 2
149
  chikou_span = df["close"].shift(-displacement)
150
 
151
+ last_date = datetime.strptime(df["time"].iloc[-1], DATE_FORMAT)
152
+ lst_date = Utility.generate_dates(last_date, displacement)
153
+ time = np.concatenate((df["time"], lst_date))
154
  tenkan_sen = np.concatenate((tenkan_sen, space_displacement))
155
  kijun_sen = np.concatenate((kijun_sen, space_displacement))
156
  senkou_span_a = np.concatenate((space_displacement, senkou_span_a))
services/utils.py CHANGED
@@ -1,4 +1,4 @@
1
- from datetime import datetime
2
  from utils.config import DATE_FORMAT
3
 
4
 
@@ -6,9 +6,22 @@ class Utility:
6
  def __init__(self) -> None: pass
7
 
8
  @staticmethod
9
- def ts_to_date(ts, format=DATE_FORMAT) -> str:
10
  return datetime.fromtimestamp(ts).strftime(format)
11
 
12
  @staticmethod
13
- def date_to_ts(date, format=DATE_FORMAT) -> int:
14
  return int(datetime.timestamp(datetime.strptime(date, format)))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import datetime, timedelta
2
  from utils.config import DATE_FORMAT
3
 
4
 
 
6
  def __init__(self) -> None: pass
7
 
8
  @staticmethod
9
+ def ts_to_date(ts: int, format=DATE_FORMAT) -> str:
10
  return datetime.fromtimestamp(ts).strftime(format)
11
 
12
  @staticmethod
13
+ def date_to_ts(date: str, format=DATE_FORMAT) -> int:
14
  return int(datetime.timestamp(datetime.strptime(date, format)))
15
+
16
+ @staticmethod
17
+ def generate_dates(start_date: datetime.date,
18
+ num_days: int,
19
+ format=DATE_FORMAT):
20
+ lst_date = []
21
+ current_date = start_date
22
+ for i in range(num_days):
23
+ current_date += timedelta(days=1)
24
+ while current_date.weekday() >= 5:
25
+ current_date += timedelta(days=1)
26
+ lst_date.append(current_date.strftime(format))
27
+ return lst_date