File size: 19,547 Bytes
884dad1
 
 
 
e565da6
048da70
e565da6
e96d69f
048da70
240c46b
 
884dad1
 
 
 
 
 
 
 
 
 
 
e565da6
 
 
884dad1
 
 
 
 
 
be1eeae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
884dad1
e565da6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
be1eeae
 
e565da6
8315578
e565da6
 
 
 
 
 
 
 
 
8315578
e565da6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5c36aa4
 
 
e565da6
 
5c36aa4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e565da6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8315578
e565da6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
be1eeae
 
e565da6
8315578
e565da6
 
 
 
8315578
e565da6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
884dad1
 
 
 
 
 
 
 
048da70
e96d69f
 
 
 
 
5c36aa4
e96d69f
 
 
 
 
 
 
 
 
 
 
5c36aa4
 
 
 
884dad1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8315578
 
 
 
 
 
 
 
 
 
be1eeae
 
8315578
 
 
 
 
 
 
 
 
 
 
 
41875de
8315578
 
41875de
8315578
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5c36aa4
8315578
 
 
 
5c36aa4
 
 
 
8315578
884dad1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e96d69f
 
 
884dad1
 
 
 
 
 
 
 
 
 
 
 
 
 
fcc079b
884dad1
 
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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
import requests
from datetime import datetime, timedelta
import pandas as pd
import numpy as np
from vnstock import longterm_ohlc_data
from pymongo import MongoClient, ASCENDING, DESCENDING
from utils.config import DATE_FORMAT, VN100_URL
from .utils import Utility
import os
# from dotenv import load_dotenv
# load_dotenv()

PREFIX = "https://www.hsx.vn/Modules/Chart/StaticChart/"
TIME = {"1m": 2, "3m": 3, "6m": 4, "1y": 5, "2y": 6, "5y": 7}
INDICATORS = {
    "EMA": "GetEmaChart",
    "MACD": "GetMacdChart",
    "RSI": "GetRsiChart",
    "Momentum": "GetMomentumChart",
    "Williams %R": "GetWilliamChart",
    "BollingerBand": "GetBollingerBandChart",
}
updating_price = False
updating_rsi = False
updating_macd = False


class Indicator:
    def __init__(self) -> None:
        pass

    @staticmethod
    def get_vn100(source: str = "database") -> dict:
        try:
            lst_symbols = []
            if source == "database":
                uri = os.environ.get("MONGODB_URI")
                client = MongoClient(uri)
                database = client.get_database("data")
                collection = database.get_collection("rsi")
                newest_record = collection.find_one()
                lst_symbols = list(newest_record["value"].keys())
            elif source == "hsx":
                data = requests.get(VN100_URL).json()
                data = data["rows"]
                for value in data:
                    lst_symbols.append(value["cell"][2].strip())
            return {"symbols": lst_symbols}
        except Exception as e:
            return {"message": f"Caught error {e}"}

    @staticmethod
    def update_daily_price() -> None:
        global updating_price
        if updating_price:
            return
        updating_price = True
        datetime_now = datetime.utcnow()
        hour = datetime_now.hour
        weekday = datetime_now.weekday()
        start_date = datetime_now.date()
        delta = timedelta(days=1)
        end_date = start_date + delta
        start_date = start_date.strftime(DATE_FORMAT)
        end_date = end_date.strftime(DATE_FORMAT)
        try:
            if weekday < 5 and hour >= 12:
                uri = os.environ.get("MONGODB_URI")
                client = MongoClient(uri)
                database = client.get_database("data")
                collection = database.get_collection("price")
                tmp_df = longterm_ohlc_data("MBB",
                                            start_date,
                                            end_date,
                                            "D",
                                            "stock").reset_index(drop=True)
                if tmp_df.shape[0] == 0:
                    updating_price = False
                    return
                last_date = str(tmp_df["time"])
                newest_record = \
                    collection.find_one(sort=[("_id", DESCENDING)])
                if newest_record["time"] != last_date:
                    lst_symbols = list(newest_record["value"].keys())
                    record = {}
                    record["time"] = last_date
                    values = []
                    for symbol in lst_symbols:
                        df = longterm_ohlc_data(symbol,
                                                start_date,
                                                end_date,
                                                resolution="D",
                                                type="stock"
                                                ).reset_index(drop=True)
                        df[["open", "high", "low", "close"]] = \
                            df[["open", "high", "low", "close"]] * 1000
                        # convert open, high, low, close to int
                        df[["open", "high", "low", "close"]] = \
                            df[["open", "high", "low", "close"]].astype(int)
                        df = df[["ticker", "open",
                                "high", "low", "close"]].iloc[-1]
                        values.append(df.to_dict())
                    record["value"] = values
                collection.insert_one(record)
                collection.find_one_and_delete({}, sort=[("_id", ASCENDING)])
                print("Updated price")
                updating_price = False
        except Exception as e:
            print(f"Error: {e}")
            updating_price = False

    @staticmethod
    def update_entire_price() -> None:
        global updating_price
        if updating_price:
            return
        updating_price = True
        datetime_now = datetime.utcnow()
        hour = datetime_now.hour
        weekday = datetime_now.weekday()
        try:
            symbol_dict = Indicator.get_vn100(source="hsx")
            lst_symbols = symbol_dict["symbols"]
            if weekday < 5 and hour < 12:
                updating_price = False
                return
            end_date = datetime_now.date()
            delta = timedelta(days=300)
            start_date = end_date - delta
            start_date = start_date.strftime(DATE_FORMAT)
            end_date = end_date.strftime(DATE_FORMAT)
            lst_time = []
            lst_values = []
            if len(lst_symbols) != 100:
                updating_price = False
                return
            for symbol in lst_symbols:
                df = longterm_ohlc_data(symbol,
                                        start_date,
                                        end_date,
                                        resolution="D",
                                        type="stock"
                                        ).reset_index(drop=True).tail(150)
                lst_time = list(df["time"])
                df[["open", "high", "low", "close"]] = \
                    df[["open", "high", "low", "close"]] * 1000
                # convert open, high, low, close to int
                df[["open", "high", "low", "close"]] = \
                    df[["open", "high", "low", "close"]].astype(int)
                df = df[["ticker", "open", "high", "low", "close"]]
                lst_values.append(df.to_dict(orient="records"))
            records = []
            for i in range(len(lst_time)):
                record = {}
                record["time"] = lst_time[i]
                values = []
                for symbol_index in range(100):
                    values.append(lst_values[symbol_index][i])
                record["value"] = values
                records.append(record)
            uri = os.environ.get("MONGODB_URI")
            client = MongoClient(uri)
            database = client.get_database("data")
            collection = database.get_collection("price")
            if "price" in database.list_collection_names():
                collection.drop()
            collection.insert_many(records)
            print("Updated entire price")
            updating_price = False
        except Exception as e:
            print(f"Error: {e}")
            updating_price = False

    @staticmethod
    def get_price(symbol: str,
                  count_back: int = 150,
                  source: str = "database") -> pd.DataFrame:
        try:
            symbol = symbol.upper()
            if source == "database":
                uri = os.environ.get("MONGODB_URI")
                client = MongoClient(uri)
                database = client.get_database("data")
                collection = database.get_collection("price")
                result = list(collection.find())
                tmp_df = pd.DataFrame(result[0]["value"])
                lst_symbols = tmp_df["ticker"].values
                if symbol not in lst_symbols:
                    return pd.DataFrame(
                        [{"message": "The symbol is not existed"}]
                        )
                symbol_index = np.argwhere(lst_symbols == symbol)[0][0]
                lst_values = []
                for record in result:
                    value = record["value"][symbol_index]
                    value["time"] = record["time"]
                    lst_values.append(value)
                return pd.DataFrame(lst_values)
            elif source == "vnstock":
                datetime_now = datetime.utcnow()
                end_date = datetime_now.date()
                delta = timedelta(days=count_back)
                start_date = end_date - delta
                start_date = start_date.strftime(DATE_FORMAT)
                end_date = end_date.strftime(DATE_FORMAT)
                df = longterm_ohlc_data(symbol,
                                        start_date,
                                        end_date,
                                        resolution="D",
                                        type="stock"
                                        ).reset_index(drop=True)
                df[["open", "high", "low", "close"]] = \
                    df[["open", "high", "low", "close"]] * 1000
                # convert open, high, low, close to int
                df[["open", "high", "low", "close"]] = \
                    df[["open", "high", "low", "close"]].astype(int)
                return df[["time", "ticker", "open", "high", "low", "close"]]
        except Exception as e:
            return pd.DataFrame(
                [{"message": f"Caught error {e}"}]
                )

    @staticmethod
    def update_daily_rsi() -> None:
        global updating_rsi
        if updating_rsi:
            return
        updating_rsi = True
        datetime_now = datetime.utcnow()
        hour = datetime_now.hour
        weekday = datetime_now.weekday()
        start_date = datetime_now.date()
        delta = timedelta(days=1)
        end_date = start_date + delta
        start_date = start_date.strftime(DATE_FORMAT)
        end_date = end_date.strftime(DATE_FORMAT)
        try:
            if weekday < 5 and hour >= 12:
                uri = os.environ.get("MONGODB_URI")
                client = MongoClient(uri)
                database = client.get_database("data")
                collection = database.get_collection("price")
                tmp_df = longterm_ohlc_data("MBB",
                                            start_date,
                                            end_date,
                                            "D",
                                            "stock").reset_index(drop=True)
                if tmp_df.shape[0] == 0:
                    updating_rsi = False
                    return
                last_date = str(tmp_df["time"])
                newest_record = \
                    collection.find_one(sort=[("_id", DESCENDING)])
                if newest_record["time"] != last_date:
                    lst_symbols = list(newest_record["value"].keys())
                    record = {}
                    record["time"] = last_date
                    str_symbols = ','.join(lst_symbols)
                    data = requests.get('https://apipubaws.tcbs.com.vn/stock-insight/v1/stock/second-tc-price?tickers={}'.format(str_symbols)).json()
                    for i in data["data"]:
                        record[i["t"]] = i["rsi"]
                collection.insert_one(record)
                collection.find_one_and_delete({}, sort=[("_id", ASCENDING)])
                print("Updated daily rsi")
                updating_rsi = False
        except Exception as e:
            print(f"Error: {e}")
            updating_rsi = False

    @staticmethod
    def update_entire_rsi() -> None:
        global updating_rsi
        if updating_rsi:
            return
        updating_rsi = True
        datetime_now = datetime.utcnow()
        hour = datetime_now.hour
        weekday = datetime_now.weekday()
        try:
            symbol_dict = Indicator.get_vn100(source="hsx")
            lst_symbols = symbol_dict["symbols"]
            if weekday < 5 and hour < 12:
                updating_rsi = False
                return
            get_time = True
            lst_values = {}
            if len(lst_symbols) != 100:
                updating_rsi = False
                return
            cnt = 0
            for symbol in lst_symbols:
                cnt += 1
                url = PREFIX + INDICATORS["RSI"] \
                    + f"?stockSymbol={symbol}&rangeSelector=3&periods=14"
                data = requests.get(url).json()
                rsi_df = pd.DataFrame(data["SeriesColection"][0]["Points"])
                if get_time:
                    lst_values["time"] = \
                        rsi_df["Time"].apply(lambda x:
                                             Utility.ts_to_date(x/1000))
                    get_time = False
                lst_values[symbol] = rsi_df["Value"].apply(lambda x: x[0])
            df = pd.DataFrame(lst_values)
            records = df.to_dict(orient="records")
            uri = os.environ.get("MONGODB_URI")
            client = MongoClient(uri)
            database = client.get_database("data")
            collection = database.get_collection("rsi")
            if "rsi" in database.list_collection_names():
                collection.drop()
            collection.insert_many(records)
            print("Updated entire RSI")
            updating_rsi = False
        except Exception as e:
            print(f"Error: {e}")
            updating_rsi = False

    @staticmethod
    def get_rsi(
        symbol: str,
        periods: int = 14,
        smooth_k: int = 3,
        smooth_d: int = 3,
    ) -> pd.DataFrame:
        try:
            symbol = symbol.upper()
            uri = os.environ.get("MONGODB_URI")
            client = MongoClient(uri)
            database = client.get_database("data")
            collection = database.get_collection("rsi")
            records = list(collection.find())
            record_df = pd.DataFrame(records).drop(columns=["_id"])
            record_df = \
                record_df[["time", symbol]].rename(columns={symbol: "rsi"})
            record_df["stoch_rsi"] = \
                Indicator.stoch_rsi(record_df["rsi"], periods)
            record_df["stoch_rsi_smooth_k"] = \
                Indicator.stoch_rsi_smooth_k(record_df["stoch_rsi"], smooth_k)
            record_df["stoch_rsi_smooth_d"] = Indicator.stoch_rsi_smooth_d(
                record_df["stoch_rsi_smooth_k"], smooth_d
            )
            return record_df
        except Exception as e:
            return pd.DataFrame(
                [{"message": f"Caught error {e}"}]
                )

    @staticmethod
    def stoch_rsi(rsi: pd.Series, periods: int = 14) -> pd.Series:
        ma, mi = (
            rsi.rolling(window=periods).max(),
            rsi.rolling(window=periods).min(),
        )
        return (rsi - mi) * 100 / (ma - mi)

    @staticmethod
    def stoch_rsi_smooth_k(stoch_rsi: pd.Series, k: int) -> pd.Series:
        return stoch_rsi.rolling(window=k).mean()

    @staticmethod
    def stoch_rsi_smooth_d(stoch_rsi_k: pd.Series, d: int) -> pd.Series:
        return stoch_rsi_k.rolling(window=d).mean()

    @staticmethod
    def update_entire_macd() -> None:
        global updating_macd
        if updating_macd:
            return
        updating_macd = True
        datetime_now = datetime.utcnow()
        hour = datetime_now.hour
        weekday = datetime_now.weekday()
        try:
            symbol_dict = Indicator.get_vn100(source="hsx")
            lst_symbols = symbol_dict["symbols"]
            if weekday < 5 and hour < 12:
                updating_macd = False
                return
            get_time = True
            lst_values = {}
            if len(lst_symbols) != 100:
                updating_macd = False
                return
            cnt = 0
            for symbol in lst_symbols:
                cnt += 1
                url = PREFIX + INDICATORS["MACD"] \
                    + f"?stockSymbol={symbol}&rangeSelector=4&fastPeriod=12&slowPeriod=26&signalPeriod=9"
                data = requests.get(url).json()
                rsi_df = pd.DataFrame(
                    data["SeriesColection"][0]["Points"]).tail(20)
                if get_time:
                    lst_values["time"] = \
                        rsi_df["Time"].apply(lambda x:
                                             Utility.ts_to_date(x/1000))
                    get_time = False
                lst_values[symbol] = rsi_df["Value"].apply(lambda x: int(x[0]))
            df = pd.DataFrame(lst_values)
            records = df.to_dict(orient="records")
            uri = os.environ.get("MONGODB_URI")
            client = MongoClient(uri)
            database = client.get_database("data")
            collection = database.get_collection("macd")
            if "macd" in database.list_collection_names():
                collection.drop()
            collection.insert_many(records)
            print("Updated entire MACD")
            updating_macd = False
        except Exception as e:
            print(f"Error: {e}")
            updating_macd = False

    @staticmethod
    def get_macd(
        symbol: str,
    ) -> pd.DataFrame:
        try:
            symbol = symbol.upper()
            uri = os.environ.get("MONGODB_URI")
            client = MongoClient(uri)
            database = client.get_database("data")
            collection = database.get_collection("macd")
            records = list(collection.find())
            record_df = pd.DataFrame(records).drop(columns=["_id"])
            record_df = \
                record_df[["time", symbol]].rename(columns={symbol: "macd"})
            return record_df
        except Exception as e:
            return pd.DataFrame(
                [{"message": f"Caught error {e}"}]
                )

    @staticmethod
    def get_ichimoku_cloud(
        df: pd.DataFrame,
        conversion_period=9,
        base_period=26,
        span_b_period=52,
        displacement=26,
    ) -> pd.DataFrame:
        space_displacement = np.full(displacement, np.nan)
        tenkan_sen = (
            df["high"].rolling(window=conversion_period).max()
            + df["low"].rolling(window=conversion_period).min()
        ) / 2
        kijun_sen = (
            df["high"].rolling(window=base_period).max()
            + df["low"].rolling(window=base_period).min()
        ) / 2
        senkou_span_a = (tenkan_sen + kijun_sen) / 2
        senkou_span_b = (
            df["high"].rolling(window=span_b_period).max()
            + df["low"].rolling(window=span_b_period).min()
        ) / 2
        chikou_span = df["close"].shift(-displacement)

        last_date = datetime.strptime(df["time"].iloc[-1], DATE_FORMAT)
        lst_date = Utility.generate_dates(last_date, displacement)
        time = np.concatenate((df["time"], lst_date))
        tenkan_sen = np.concatenate((tenkan_sen, space_displacement))
        kijun_sen = np.concatenate((kijun_sen, space_displacement))
        senkou_span_a = np.concatenate((space_displacement, senkou_span_a))
        senkou_span_b = np.concatenate((space_displacement, senkou_span_b))
        chikou_span = np.concatenate((chikou_span, space_displacement))

        data_dict = {
            "time": time,
            "tenkan_sen": tenkan_sen,
            "kijun_sen": kijun_sen,
            "senkou_span_a": senkou_span_a,
            "senkou_span_b": senkou_span_b,
            "chikou_span": chikou_span,
            "tenkan_kijun": tenkan_sen - kijun_sen,
            "kumo_cloud": senkou_span_a - senkou_span_b
        }
        return pd.DataFrame(data_dict)