File size: 4,129 Bytes
919ec8d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from distutils.command.sdist import sdist
from numpy import tri
import pandas as pd
import json, requests
import slack, time
from datetime import datetime
# from bs4 import BeautifulSoup
from config import *
def get_yahoo_finance_quote(symbol):
    # Get the symbol quote from yahoo finance, we are using Beautiful Soup for scraping
    URL = f"https://finance.yahoo.com/quote/{symbol}"
    headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.61 Safari/537.36'}
    page = requests.get(URL, headers = headers)
    soup = BeautifulSoup(page.text, "html.parser")
    price = soup.find('div',{'class':'D(ib) Mend(20px)'}).find_all('fin-streamer')[0].text
    return float(price.replace(",",""))
def get_cnbc_data(symbol):
    ticker = symbol.replace(" ","")
    if ticker == "NASDAQ":
        ticker = "NDX"
    elif ticker == "NIFTY50":
        ticker = ".NSEI"
    # Get the symbol quote from yahoo finance, we are using Beautiful Soup for scraping
    df = pd.DataFrame(requests.get(f"https://ts-api.cnbc.com/harmony/app/charts/1Y.json?symbol={ticker}").json()["barData"]["priceBars"])
    # df_1D = pd.DataFrame(requests.get(f"https://ts-api.cnbc.com/harmony/app/charts/1D.json?symbol={ticker}").json()["barData"]["priceBars"])
    df["datetime"] = pd.to_datetime(df['tradeTimeinMills'],unit='ms')
    df["close"] = df["close"].astype(float)
    # df_1D["close"] = df_1D["close"].astype(float)
    df.set_index("datetime",inplace = True)
    dma200 = (df["close"].rolling(200).mean()).iloc[-1]
    close = (df["close"].iloc[-1])
    return dma200, close

client = slack.WebClient(token = SLACK_TOKEN)

while True:
    df = pd.read_csv('watchlist.csv')
    df.set_index("Symbol",inplace = True)
    # df_crypto = pd.DataFrame(json.loads(requests.get("https://ftx.com/api/markets").text)["result"])
    # df_crypto = df_crypto[df_crypto["quoteCurrency"].isin(["USD","USDT"])]
    # df_crypto.set_index("name",inplace = True)

    if len(df)>0:
        req_df_price = df[df["status"] == "Pending"]
        req_df_dma = df[df["dma_status"] == "Pending"]
        for symbol in req_df_price.index:
            if symbol in ["SPX","US 2Y","US 5Y","US 10Y","US 30Y","HYG","LQD","NASDAQ","VIX","NIFTY50"]:
                dma200, ltp= get_cnbc_data(symbol)
            # else:
            #     ltp = df_crypto.loc[symbol]["last"]
            trigger_level = req_df_price.loc[symbol]["Trigger"]
            triggered = 0
            
            if req_df_price.loc[symbol]["view_type"] == "Above":
                if trigger_level<=ltp:
                    triggered = 1
            elif req_df_price.loc[symbol]["view_type"] == "Below":
                if trigger_level>=ltp:
                    triggered = 1
            
            if triggered == 1:
                df.at[symbol,"status"] = "Triggered"
                client.chat_postMessage(channel = f"#{df.loc[symbol]['alert_type'].lower()}_signal", 
                                text = f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')} {symbol} is {df.loc[symbol]['view_type']} {trigger_level} at {ltp}")
        for symbol in req_df_dma.index: 
            dma_check = req_df_dma.loc[symbol]["dma200"]
            if dma_check == False:
                continue
            triggered_dma200 = 0
            dma200, ltp= get_cnbc_data(symbol)
            print(dma200)
            if req_df_dma.loc[symbol]["dma200_view_type"] == "Above":
                if dma200<=ltp:
                    triggered_dma200 = 1
            elif req_df_dma.loc[symbol]["dma200_view_type"] == "Below":
                if dma200>=ltp:
                    triggered_dma200 = 1

            if triggered_dma200 == 1:
                df.at[symbol,"dma_status"] = "Triggered"
                client.chat_postMessage(channel = f"#{df.loc[symbol]['alert_type'].lower()}_signal", 
                                text = f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')} {symbol} is {df.loc[symbol]['dma200_view_type']} DMA200 at {ltp}")
        df.to_csv("watchlist.csv")
    # Recheck again after 60 minutes
    time.sleep(60*60)