def news_category(subscription_key):
    """NewsCategory.

    This will search category news for movie and TV entertainment with safe search then verify number of results and print out category, name, url, description, published time and name of provider of the first news result.
    """
    client = NewsSearchAPI(CognitiveServicesCredentials(subscription_key))

    try:
        news_result = client.news.category(category="Entertainment_MovieAndTV",
                                           market="en-us",
                                           safe_search="strict")
        print(
            "Search category news for movie and TV entertainment with safe search"
        )

        if news_result.value:
            first_news_result = news_result.value[0]
            print("News result count: {}".format(len(news_result.value)))
            print("First news category: {}".format(first_news_result.category))
            print("First news name: {}".format(first_news_result.name))
            print("First news url: {}".format(first_news_result.url))
            print("First news description: {}".format(
                first_news_result.description))
            print("First published time: {}".format(
                first_news_result.date_published))
            print("First news provider: {}".format(
                first_news_result.provider[0].name))
        else:
            print("Didn't see any news result data..")

    except Exception as err:
        print("Encountered exception. {}".format(err))
    def news(self, search_term="Election India"):
        #import pdb;pdb.set_trace()
        client = NewsSearchAPI(CognitiveServicesCredentials(subscription_key))

        news_result = client.news.search(query=search_term,
                                         market="en-us",
                                         count=10)
        # import pdb; pdb.set_trace()
        if news_result.value:
            print("Total estimated matches value: {}".format(
                news_result.total_estimated_matches))
            print("News result count: {}".format(len(
                news_result.value)).encode("utf-8"))
            result = []
            for first_news_result in news_result.value:
                result.append("Title: {}".format(
                    first_news_result.name).encode("utf-8"))
                result.append("URL: {}".format(
                    first_news_result.url).encode("utf-8"))
                result.append("Description: {}".format(
                    first_news_result.description).encode("utf-8"))
                # print("Published time: {}".format(first_news_result.date_published).encode("utf-8"))
                # print("News provider: {}".format(first_news_result.provider[0].name).encode("utf-8"))
                # print('\n\n\n\n')
            return result
        else:
            print("Didn't see any news result data..")
def news_search_with_filtering(subscription_key):
    """NewsSearchWithFilters.

    This will search most recent news for (Artificial Intelligence) with freshness and sortBy parameters then verify number of results and print out totalEstimatedMatches, name, url, description, published time and name of provider of the first news result.
    """
    client = NewsSearchAPI(CognitiveServicesCredentials(subscription_key))

    try:
        news_result = client.news.search(query="Artificial Intelligence",
                                         market="en-us",
                                         freshness="Week",
                                         sort_by="Date")
        print(
            "Search most recent news for query \"Artificial Intelligence\" with freshness and sortBy"
        )

        if news_result.value:
            first_news_result = news_result.value[0]
            print("News result count: {}".format(len(news_result.value)))
            print("First news name: {}".format(first_news_result.name))
            print("First news url: {}".format(first_news_result.url))
            print("First news description: {}".format(
                first_news_result.description))
            print("First published time: {}".format(
                first_news_result.date_published))
            print("First news provider: {}".format(
                first_news_result.provider[0].name))
        else:
            print("Didn't see any news result data..")

    except Exception as err:
        print("Encountered exception. {}".format(err))
def news_search(subscription_key):
    """NewsSearch.

    This will search news for (Quantum  Computing) with market and count parameters then verify number of results and print out totalEstimatedMatches, name, url, description, published time and name of provider of the first news result
    """
    client = NewsSearchAPI(CognitiveServicesCredentials(subscription_key))

    try:
        news_result = client.news.search(query="Quantum Computing",
                                         market="en-us",
                                         count=10)
        print(
            "Search news for query \"Quantum Computing\" with market and count"
        )

        if news_result.value:
            first_news_result = news_result.value[0]
            print("Total estimated matches value: {}".format(
                news_result.total_estimated_matches))
            print("News result count: {}".format(len(news_result.value)))
            print("First news name: {}".format(first_news_result.name))
            print("First news url: {}".format(first_news_result.url))
            print("First news description: {}".format(
                first_news_result.description))
            print("First published time: {}".format(
                first_news_result.date_published))
            print("First news provider: {}".format(
                first_news_result.provider[0].name))
        else:
            print("Didn't see any news result data..")

    except Exception as err:
        print("Encountered exception. {}".format(err))
Ejemplo n.º 5
0
def get_news_articles(headline):

    subscription_key = "9b539b9076e242f6a8318a980fdc6f88"
    search_term = "Trump Has 95% Approval Rating"

    client = NewsSearchAPI(CognitiveServicesCredentials(subscription_key))
    news_result = client.news.search(query=search_term,
                                     market="en-us",
                                     count=3)

    #if news_result.value:
    #    first_news_result = news_result.value[0]
    #    print("Total estimated matches value: {}".format(
    #        news_result.total_estimated_matches))
    #    print("News result count: {}".format(len(news_result.value)))
    #    print("First news name: {}".format(first_news_result.name))
    #    print("First news url: {}".format(first_news_result.url))
    #    print("First news description: {}".format(first_news_result.description))
    #    print("First published time: {}".format(first_news_result.date_published))
    #    print("First news provider: {}".format(first_news_result.provider[0].name))
    #else:
    #    print("Didn't see any news result data..")

    headlines = {}
    if news_result.value:
        for i in range(len(news_result.value)):
            headlines['headline' + str(i)] = [
                news_result.value[i].name, news_result.value[i].url
            ]
    my_json = json.dumps(headlines)
    print(my_json)
def news_trending(subscription_key):
    """NewsTrending.

    This will search news trending topics in Bing then verify number of results and print out name, text of query, webSearchUrl, newsSearchUrl and image Url of the first news result.
    """
    client = NewsSearchAPI(CognitiveServicesCredentials(subscription_key))

    try:
        trending_topics = client.news.trending(market="en-us")
        print("Search news trending topics in Bing")

        if trending_topics.value:
            first_topic = trending_topics.value[0]
            print("News result count: {}".format(len(trending_topics.value)))
            print("First topic name: {}".format(first_topic.name))
            print("First topic query: {}".format(first_topic.query.text))
            print("First topic image url: {}".format(first_topic.image.url))
            print("First topic webSearchUrl: {}".format(
                first_topic.web_search_url))
            print("First topic newsSearchUrl: {}".format(
                first_topic.news_search_url))
        else:
            print("Didn't see any topics result data..")

    except Exception as err:
        print("Encountered exception. {}".format(err))
Ejemplo n.º 7
0
def news(search_term=None):

    try:
        subscription_key = "a05456788ad8447d8039b0e1d75f012a"

        if search_term == None:
            save_speech('newsspeak')
            speech = speech2text()
            search_term = check(speech)

        client = NewsSearchAPI(CognitiveServicesCredentials(subscription_key))
        news_result = client.news.search(query=search_term,
                                         market="en-us",
                                         count=10,
                                         freshness='Week')
        closer = False

        if news_result.value:
            for k in news_result.value:
                modular_speech(k.name)

                while True:
                    if keyboard.is_pressed('a'):
                        break

                    if keyboard.is_pressed('s'):
                        modular_speech(k.description)
                        sleep(1)
                        break

                    if keyboard.is_pressed('d'):
                        closer = True
                        break

                    if keyboard.is_pressed('q'):
                        speak_label('goodbye')
                        quit()

                if closer == True:
                    break

                else:
                    pass

        else:
            save_speech("nonews")

    except Exception:
        pass
def test(path):
    subscription_key = "9b539b9076e242f6a8318a980fdc6f88"
    search_term = "Trump Has 95% Approval Rating"

    client = NewsSearchAPI(CognitiveServicesCredentials(subscription_key))
    news_result = client.news.search(query=search_term,
                                     market="en-us",
                                     count=3)

    headlines = {}
    if news_result.value:
        for i in range(len(news_result.value)):
            headlines['headline' + str(i)] = [
                news_result.value[i].name, news_result.value[i].url
            ]
    my_json = json.dumps(headlines)
    return my_json
Ejemplo n.º 9
0
    def news_candidate(self, search_term="Indian Election"):
        #import pdb;pdb.set_trace()
        client = NewsSearchAPI(CognitiveServicesCredentials(subscription_key))

        news_result = client.news.search(query=search_term,
                                         market="en-us",
                                         count=3)
        # import pdb; pdb.set_trace()
        if news_result.value:
            print("Total estimated matches value: {}".format(
                news_result.total_estimated_matches))
            print("News result count: {}".format(len(
                news_result.value)).encode("utf-8"))
            result = []
            for first_news_result in news_result.value:
                if len(first_news_result.name) > 100:
                    a = first_news_result.name[:100] + "..."
                else:
                    a = first_news_result.name
                # subresult.append("{}".format(first_news_result.name))
                # subresult.append("{}".format(first_news_result.url))
                result.append(a)

                #result.append("{}".format(first_news_result.description))
                # print("Published time: {}".format(first_news_result.date_published).encode("utf-8"))
                # print("News provider: {}".format(first_news_result.provider[0].name).encode("utf-8"))
                # print('\n\n\n\n')
            # import pdb; pdb.set_trace()
            if len(result) < 3:
                while len(result) < 3:
                    result.append("No more news...")
                # result=['No more news...','No more news...','No more news...']
            return result[0], result[1], result[2]
        else:
            print("Didn't see any news result data..")
            return ['No news found...']


# obj=NewsSearch()
# print(obj.news("dawood ibrahim criminal records"))
Ejemplo n.º 10
0
Archivo: bing.py Proyecto: lucerax/XRef
def bingResult(keywords, curLink):
    subscription_key = "18d92d49457f44869027dcd6145d4b11"
    search_term = ""
    for word in keywords:
        search_term += word + " "
    print("SEARCHTERM:", search_term)

    client = NewsSearchAPI(CognitiveServicesCredentials(subscription_key))

    news_result = client.news.search(query=search_term,
                                     market="en-us",
                                     count=9)
    count = 7
    i = 1

    newsInfo = {"title": [], "provider": [], "description": [], "URL": []}

    while i < min(count, len(news_result.value)):
        if news_result.value[i].url not in curLink:
            print("index:", i)
            cur_news_result = news_result.value[i]
            newsInfo["title"].append(cur_news_result.name)
            newsInfo["provider"].append(cur_news_result.provider[0].name)
            newsInfo["description"].append(cur_news_result.description)
            newsInfo["URL"].append(cur_news_result.url)
            """
            ("num", i, "news url: {}".format(first_news_result.url)),
            ("num", i, "news description: {}".format(first_news_result.description)),
            ("num", i, "published time: {}".format(first_news_result.date_published)),
            ("num", i, "news provider: {}".format(first_news_result.provider[0].name))})
            """
        else:
            count += 1

        i += 1

    return newsInfo
Ejemplo n.º 11
0
def analysis(request):
    if request.method == 'GET':
        form = request.GET
        ticker = form.get("Ticker", "0")
        co = Conames.objects.get(Co_name=ticker).Co_name
        index = Conames.objects.get(Co_name=ticker).pk
        Y = Conames.objects.only('ticker').get(pk=index).ticker
        X = Conames.objects.only('tick').get(pk=index).tick
        tick = X.upper()
        start = dt.datetime(2017, 1, 1)
        end = date.today()
        df = web.DataReader(Y, 'yahoo', start, end)
        close = df['Close']
        high = df['High']
        low = df['Low']
        volume = df['Volume']
        p = close[-1]
        p1 = close[-2]
        diff = ((p - p1) / p1) * 100
        d = "%.2f" % diff
        if diff > 0:
            diff_green = "+" + d + "%"
        else:
            diff_green = ""

        if diff < 0:
            diff_red = d + "%"
        else:
            diff_red = ""

        price = "%.2f" % p

        def rs():
            r = ta.rsi(close, n=14, fillna=False)
            rsi = (r[-1])
            if 15.1 <= rsi <= 30:
                status = "Buy"
            elif rsi <= 15:
                status = "Strong Buy"
            elif 84.9 <= rsi >= 70:
                status = "Sell"
            elif rsi >= 85:
                status = "Strong Sell"
            else:
                status = "Hold"
            return status

        def ao():
            ao = ta.ao(high, low, s=5, len=34, fillna=False)
            AO = ao[-1]
            A = (ao[-10:])
            if 0 >= AO >= -0.5:

                def order():  # For ascending
                    for i in range(len(A) - 1):
                        if A[i] - A[i + 1] > 0:
                            return False
                        return True

                if order():
                    status1 = "Buy"
                else:
                    status1 = "Sell"

            elif 0 <= AO <= 0.5:

                def order():  # For descending
                    for i in range(len(A) - 1):
                        if A[i] - A[i + 1] < 0:
                            return False
                        return True

                if order():
                    status1 = "Sell"
                else:
                    status1 = "Buy"

            elif AO <= -1:
                status1 = "Buy"
            elif AO >= 1:
                status1 = "Sell"
            else:
                status1 = "Hold"
            return status1

        def mf():
            mfi = ta.money_flow_index(high,
                                      low,
                                      close,
                                      volume,
                                      n=14,
                                      fillna=False)
            MFI = mean(mfi[-7:])
            if MFI <= 20:
                status2 = "Buy"
            elif MFI <= 30:
                status2 = "Buy"
            elif MFI >= 80:
                status2 = "Sell"
            elif MFI >= 70:
                status2 = "Sell"
            else:
                status2 = "Hold"
            return status2

        def so():
            so = ta.stoch(high, low, close, n=14, fillna=False)
            SO = (so[-1])
            if SO <= 20:
                status3 = "Buy"
            elif SO <= 30:
                status3 = "Buy"
            elif SO >= 80:
                status3 = "Sell"
            elif SO >= 70:
                status3 = "Sell"
            else:
                status3 = "Hold"
            return status3

        def s_o():
            sos = ta.stoch_signal(high, low, close, n=14, d_n=3, fillna=False)
            SOS = (sos[-1])
            if SOS <= 20:
                status4 = "Buy"
            elif SOS <= 30:
                status4 = "Buy"
            elif SOS >= 80:
                status4 = "Sell"
            elif SOS >= 70:
                status4 = "Sell"
            else:
                status4 = "Hold"
            return status4

        def tsi():
            tsi = ta.tsi(close, r=25, s=13, fillna=False)
            TSI = tsi[-1]
            if TSI >= 20:
                status5 = "Buy"
            elif 5 <= TSI <= 20:
                status5 = "Buy"
            elif TSI <= 5:
                status5 = "Hold"
            elif -20 <= TSI <= -5:
                status5 = "Sell"
            elif TSI >= -20:
                status5 = "Sell"
            return status5

        def u_o():
            uo = ta.uo(high,
                       low,
                       close,
                       s=7,
                       m=14,
                       len=28,
                       ws=4.0,
                       wm=2.0,
                       wl=1.0,
                       fillna=False)
            UO = uo[-1]
            if UO <= 10:
                status6 = "Buy"
            elif 10.1 <= UO <= 30:
                status6 = "Buy"
            elif 70 <= UO <= 90:
                status6 = "Sell"
            elif UO >= 90:
                status6 = "Sell"
            else:
                status6 = "Hold"
            return status6

        def w_r():
            wr = ta.wr(high, low, close, lbp=14, fillna=False)
            WR = wr[-1]
            if 0 >= WR >= 20:
                status7 = "Sell"
            elif -80 <= WR:
                status7 = "Buy"
            else:
                status7 = "Hold"
            return status7

        def cm():
            cmf = ta.chaikin_money_flow(high,
                                        low,
                                        close,
                                        volume,
                                        n=20,
                                        fillna=False)
            CMF = cmf[-1]

            if CMF > 1.5:
                vol_status_cmf = "Buy"
            elif 0 <= CMF <= 1.5:
                vol_status_cmf = "Buy"
            elif CMF == 0:
                vol_status_cmf = "Hold"
            elif -1.5 <= CMF <= 0:
                vol_status_cmf = "Sell"
            else:
                vol_status_cmf = "Sell"
            return vol_status_cmf

        def em():
            emv = ta.ease_of_movement(high,
                                      low,
                                      close,
                                      volume,
                                      n=20,
                                      fillna=False)
            EMV = emv[-1]
            if EMV >= 1.5:
                vol_status_emv = "Buy"
            elif -1.5 <= EMV <= 1.5:
                vol_status_emv = "Hold"
            else:
                vol_status_emv = "Sell"
            return vol_status_emv

        def f_i():
            fi = ta.force_index(close, volume, n=2, fillna=False)
            FI = fi[-1]
            if FI >= 0:
                vol_status_fi = "Buy"
            elif FI <= 0:
                vol_status_fi = "Sell"
            else:
                vol_status_fi = "Hold"
            return vol_status_fi

        def nv():
            nvi = ta.negative_volume_index(close, volume, fillna=False)
            ema255 = ta.ema_indicator(close, n=255, fillna=False)
            NVI = nvi[-1]
            E = ema255[-1]
            if NVI > E:
                vol_status_nvi = "Buy"
            elif NVI < E:
                vol_status_nvi = "Sell"
            else:
                vol_status_nvi = "Hold"
            return vol_status_nvi

        def ob():
            obv = ta.on_balance_volume(close, volume, fillna=False)
            OBV = obv[-10:]

            def order():  # For ascending
                for i in range(len(OBV) - 1):
                    if OBV[i] - OBV[i + 1] > 0:
                        return False
                    return True

            if order():
                vol_status_obv = "Buy"
            else:
                vol_status_obv = "Buy"
            return vol_status_obv

        def adi():
            add = ta.acc_dist_index(high, low, close, volume, fillna=False)
            a = add[-1]
            ad = add[-7:]

            if a <= 1000:

                def order():  # For ascending
                    for i in range(len(ad) - 1):
                        if ad[i] - ad[i + 1] > 0:
                            return False
                        return True

                if order():
                    vol_status_add = "Buy"
                else:
                    vol_status_add = "Sell"

            else:
                vol_status_add = "No signal"

            return vol_status_add

        def at():
            atr = ta.average_true_range(high, low, close, n=14, fillna=False)

            if atr[-1] >= 1.5 + mean(atr[-10:]):
                vot_status_atr = "Buy"
            elif atr[-1] <= mean(atr[-10:] - 1.5):
                vot_status_atr = "Sell"
            else:
                vot_status_atr = "Hold"
            return vot_status_atr

        def bb():
            bbhb = ta.bollinger_hband(close, n=20, ndev=2, fillna=False)
            bbhb_ind = ta.bollinger_hband_indicator(close,
                                                    n=20,
                                                    ndev=2,
                                                    fillna=False)
            bblb = ta.bollinger_lband(close, n=20, ndev=2, fillna=False)
            bblb_ind = ta.bollinger_lband_indicator(close,
                                                    n=20,
                                                    ndev=2,
                                                    fillna=False)
            bbmavg = ta.bollinger_mavg(close, n=20, fillna=False)
            sub = bbhb[-1] - close[-1]
            sub2 = close[-1] - bblb[-1]

            if sub > sub2:
                vot_status_bb = "Buy"
            elif sub < sub2:
                vot_status_bb = "Sell"
            else:
                vot_status_bb = "Hold"
            return vot_status_bb

        def dch():
            dch = ta.donchian_channel_hband(close, n=20, fillna=False)
            dchi = ta.donchian_channel_hband_indicator(close,
                                                       n=20,
                                                       fillna=False)
            dcl = ta.donchian_channel_lband(close, n=20, fillna=False)
            dcli = ta.donchian_channel_lband_indicator(close,
                                                       n=20,
                                                       fillna=False)

            if close[-1] == dch[-1]:
                vot_status_dc = "Strong Sell"
            elif dch[-1] > close[-1] > dch[-1] - 2:
                vot_status_dc = "Sell"
            elif dcl[-1] == close[-1]:
                vot_status_dc = "Strong Buy"
            elif dcl[-1] < close[-1] <= dcl[-1] + 2:
                vot_status_dc = "Buy"
            else:
                vot_status_dc = "Hold"
            return vot_status_dc

        def adx():
            adx = ta.adx(high, low, close, n=14, fillna=False)
            adxn = ta.adx_neg(high, low, close, n=14, fillna=False)
            adxp = ta.adx_pos(high, low, close, n=14, fillna=False)

            if adxp[-1] > adxn[-1]:
                trn_adx_status = " Buy"
            elif adxp[-1] < adxn[-1]:
                trn_adx_status = " Sell"
            else:
                trn_adx_status = " Hold"
            return trn_adx_status

        def ai():
            aid = ta.aroon_down(close, n=25, fillna=False)
            aiu = ta.aroon_up(close, n=25, fillna=False)
            if aiu[-1] > aid[-1]:
                trn_ai_status = "Buy"
            elif aiu[-1] < aid[-1]:
                trn_ai_status = "Sell"
            else:
                trn_ai_status = "Hold"
            return trn_ai_status

        def c():
            cci = ta.cci(high, low, close, n=20, c=0.015, fillna=False)
            cc = cci[-1]

            if 0 <= cc <= 50:
                trn_cci_status = "Buy"
            elif 50.1 <= cc <= 100:
                trn_cci_status = "Hold"
            elif 100.1 <= cc:
                trn_cci_status = "Sell"
            elif -50 <= cc <= 0:
                trn_cci_status = "Sell"
            elif -100 <= cc <= -50.1:
                trn_cci_status = "Hold"
            else:
                trn_cci_status = "Buy"
            return trn_cci_status

        def dpo():
            d = ta.dpo(close, n=20, fillna=False)
            do = d[-1]
            if do >= 0:
                trn_dpo_status = "Buy"
            elif do <= 0:
                trn_dpo_status = "Sell"
            else:
                trn_dpo_status = "Hold"
            return trn_dpo_status

        def ema():
            em = ta.ema_indicator(close, n=12, fillna=False)
            e = em[-7:]
            if em[-1] < close[-1]:

                def order():  # For ascending
                    for i in range(len(e) - 1):
                        if e[i] - e[i + 1] > 0:
                            return False
                        return True

                if order():
                    trn_ema_status = "Sell"
                else:
                    trn_ema_status = "Buy"
                return trn_ema_status
            elif em[-1] > close[-1]:

                def order():  # For ascending
                    for i in range(len(e) - 1):
                        if e[i] - e[i + 1] > 0:
                            return False
                        return True

                if order():
                    trn_ema_status = "Buy"
                else:
                    trn_ema_status = "Sell"
                return trn_ema_status

        def ich():
            ica = ta.ichimoku_a(high,
                                low,
                                n1=9,
                                n2=26,
                                visual=False,
                                fillna=False)
            icb = ta.ichimoku_b(high,
                                low,
                                n2=26,
                                n3=52,
                                visual=False,
                                fillna=False)

            if ica[-1] > icb[-1]:
                trn_ich_status = "Buy"
            elif ica[-1] < icb[-1]:
                trn_ich_status = "Sell"
            else:
                trn_ich_status = "Hold"
            return trn_ich_status

        def kst():
            kst = ta.kst(close,
                         r1=10,
                         r2=15,
                         r3=20,
                         r4=30,
                         n1=10,
                         n2=10,
                         n3=10,
                         n4=15,
                         fillna=False)
            kst_sig = ta.kst_sig(close,
                                 r1=10,
                                 r2=15,
                                 r3=20,
                                 r4=30,
                                 n1=10,
                                 n2=10,
                                 n3=10,
                                 n4=15,
                                 nsig=9,
                                 fillna=False)
            if kst[-1] < kst_sig[-1]:
                trn_kst_status = "Sell"
            elif kst[-1] > kst_sig[-1]:
                trn_kst_status = "Buy"
            else:
                trn_kst_status = "Hold"
            return trn_kst_status

        def macd():
            macd = ta.macd(close, n_fast=12, n_slow=26, fillna=False)
            macd_sig = ta.macd_signal(close,
                                      n_fast=12,
                                      n_slow=26,
                                      n_sign=9,
                                      fillna=False)
            if macd[-1] > macd_sig[-1]:
                trn_macd_status = "Buy"
            elif macd[-1] < macd_sig[-1]:
                trn_macd_status = "Sell"
            else:
                trn_macd_status = "Hold"
            return trn_macd_status

        subscription_key = "d225b3f12aab446aa34af931359edbe0"
        search_term = ticker

        client = NewsSearchAPI(CognitiveServicesCredentials(subscription_key))
        news_result = client.news.search(query=search_term, market="en-US")

        if news_result.value:

            first_news_result = news_result.value[0]
            data = format(first_news_result.description)

            sec_news_result = news_result.value[1]
            data1 = format(sec_news_result.description)

            third_news_result = news_result.value[2]
            data2 = format(third_news_result.description)

            fourth_news_result = news_result.value[3]
            data3 = format(fourth_news_result.description)
            # print("news name: {}".format(first_news_result.name))
            #
            # print("news description: {}".format(first_news_result.description))

        else:
            HttpResponse("NIL")

        # --------------------------------------------

        TEXT_ANALYTICS_SUBSCRIPTION_KEY = '4d1d3697dc8548b59163e2592b22beb7'
        subscription_key = TEXT_ANALYTICS_SUBSCRIPTION_KEY

        TEXT_ANALYTICS_ENDPOINT = 'https://analytics4sentiment.cognitiveservices.azure.com/'
        endpoint = TEXT_ANALYTICS_ENDPOINT

        credentials = CognitiveServicesCredentials(subscription_key)
        text_analytics_client = TextAnalyticsClient(endpoint=endpoint,
                                                    credentials=credentials)

        client = text_analytics_client

        documents = [
            {
                "id": "1",
                "language": "en",
                "text": data
            },
            {
                "id": "2",
                "language": "en",
                "text": data1
            },
            {
                "id": "3",
                "language": "en",
                "text": data2
            },
            {
                "id": "4 ",
                "language": "en",
                "text": data3
            },
        ]

        # print(documents)
        response = client.sentiment(documents=documents)
        res = []
        for document in response.documents:
            res.append(float(format(document.score)))

        res_mean = (sum(res) / 4) * 100
        if res_mean > 60:
            final_sentiment_buy = "%.1f" % res_mean + "% Positive"
        else:
            final_sentiment_buy = ""

        if res_mean < 40:
            final_sentiment_sell = "%.1f" % res_mean + "% Positive"
        else:
            final_sentiment_sell = ""

        if 40 <= res_mean <= 60:
            final_sentiment_hold = "%.1f" % res_mean + "% Positive"
        else:
            final_sentiment_hold = ""

    def final_signal():
        global path, data, data1, data2, data3
        tech_signals = [
            rs(),
            ao(),
            mf(),
            so(),
            s_o(),
            tsi(),
            u_o(),
            w_r(),
            cm(),
            em(),
            f_i(),
            nv(),
            ob(),
            adi(),
            at(),
            bb(),
            dch(),
            adx(),
            ai(),
            c(),
            dpo(),
            ema(),
            ich(),
            kst(),
            macd(),
        ]
        buy = tech_signals.count("Buy")
        hold = tech_signals.count("Hold")
        tech_score = ((buy * 4) + (hold * 2)) / 2
        news_score = res_mean / 2
        final_score = tech_score + news_score

        if final_score >= 80:
            path = 'bsh_user/Strong [email protected]'
            signal = 'Strong Buy'
        elif 55 <= final_score < 80:
            path = 'bsh_user/[email protected]'
            signal = 'Buy'
        elif 45 <= final_score < 55:
            path = 'bsh_user/[email protected]'
            signal = 'Hold'
        elif 10 < final_score < 45:
            path = 'bsh_user/[email protected]'
            signal = 'Sell'
        elif final_score <= 10:
            path = 'bsh_user/Strong [email protected]'
            signal = 'Strong Sell'
        return path

    def signal():
        global signal
        tech_signals = [
            rs(),
            ao(),
            mf(),
            so(),
            s_o(),
            tsi(),
            u_o(),
            w_r(),
            cm(),
            em(),
            f_i(),
            nv(),
            ob(),
            adi(),
            at(),
            bb(),
            dch(),
            adx(),
            ai(),
            c(),
            dpo(),
            ema(),
            ich(),
            kst(),
            macd(),
        ]
        buy = tech_signals.count("Buy")
        hold = tech_signals.count("Hold")
        tech_score = ((buy * 4) + (hold * 2)) / 2
        news_score = res_mean / 2
        final_score = tech_score + news_score
        if final_score >= 80:
            signal = 'Strong Buy'
        elif 55 <= final_score < 80:
            signal = 'Buy'
        elif 45 <= final_score < 55:
            signal = 'Hold'
        elif 10 < final_score < 45:
            signal = 'Sell'
        elif final_score <= 10:
            signal = 'Strong Sell'

        return signal

    dfn = web.DataReader("^NSEI", 'yahoo', start, end)

    closen = dfn['Close']
    pricen1 = closen[-1]
    pricen2 = closen[-2]
    pdiffn = ((pricen1 - pricen2) / pricen2) * 100
    diffn = "%.2f" % pdiffn
    price_nifty = "%.2f" % pricen1
    if pdiffn > 0:
        diffn_green = "+" + diffn + "%"
    else:
        diffn_green = ""

    if pdiffn < 0:
        diffn_red = diffn + "%"
    else:
        diffn_red = ""

    dfs = web.DataReader("^BSESN", 'yahoo', start, end)
    closes = dfs['Close']
    prices1 = closes[-1]
    prices2 = closes[-2]
    pdiffs = ((prices1 - prices2) / prices2) * 100
    diffs = "%.2f" % pdiffs
    price_sensex = "%.2f" % prices1
    if pdiffs >= 0:
        diffs_green = "+" + diffs + "%"
    else:
        diffs_green = ""

    if pdiffs <= 0:
        diffs_red = diffs + "%"
    else:
        diffs_red = ""

    dfnb = web.DataReader("VAKRANGEE.NS", 'yahoo', start, end)
    closenb = dfnb['Close']
    pricenb1 = closenb[-1]
    pricenb2 = closenb[-2]
    pdiffnb = ((pricenb1 - pricenb2) / pricenb2) * 100
    diffnb = "%.2f" % pdiffnb
    if pdiffnb > 0:
        diffnb_green = "+" + diffnb + "%"
    else:
        diffnb_green = ""

    if pdiffnb < 0:
        diffnb_red = diffnb + "%"
    else:
        diffnb_red = ""
    price_nb = "%.2f" % pricenb1

    return render(
        request, 'bsh_user/analysis.html', {
            'x': tick,
            'ticker': ticker,
            "diff_green": diff_green,
            'diff_red': diff_red,
            'price': price,
            'price_nifty': price_nifty,
            'diffn_green': diffn_green,
            'diffn_red': diffn_red,
            'price_sensex': price_sensex,
            'diffs_red': diffs_red,
            'diffs_green': diffs_green,
            'price_nb': price_nb,
            'diffnb_green': diffnb_green,
            'diffnb_red': diffnb_red,
            'name': "Vakrangee Ltd.",
            "news_buy": final_sentiment_buy,
            "news_sell": final_sentiment_sell,
            "news_hold": final_sentiment_hold,
            'mom_rsi': rs(),
            'mom_ao': ao(),
            'mom_mf': mf(),
            'mom_so': so(),
            'mom_sos': s_o(),
            'mom_tsi': tsi(),
            'mom_uo': u_o(),
            'mom_wr': w_r(),
            'vol_cm': cm(),
            'vol_em': em(),
            'vol_fi': f_i(),
            'vol_nv': nv(),
            'vol_ob': ob(),
            'vol_adi': adi(),
            'vot_atr': at(),
            'vot_bb': bb(),
            'vot_dch': dch(),
            'trn_adx': adx(),
            'trn_ai': ai(),
            'trn_cci': c(),
            'trn_dpo': dpo(),
            'trn_ema': ema(),
            'trn_ich': ich(),
            'trn_kst': kst(),
            'trn_macd': macd(),
            'score': final_signal(),
            'signal': signal()
        })
Ejemplo n.º 12
0
def homepage(request):
    global x, rows, signal
    start = dt.datetime(2017, 1, 1)
    end = date.today()
    dfn = web.DataReader("^NSEI", 'yahoo', start, end)

    closen = dfn['Close']
    pricen1 = closen[-1]
    pricen2 = closen[-2]
    pdiffn = ((pricen1 - pricen2) / pricen2) * 100
    diffn = "%.2f" % pdiffn
    price_nifty = "%.2f" % pricen1
    if pdiffn > 0:
        diffn_green = "+" + diffn + "%"
    else:
        diffn_green = ""

    if pdiffn < 0:
        diffn_red = diffn + "%"
    else:
        diffn_red = ""

    dfs = web.DataReader("^BSESN", 'yahoo', start, end)
    closes = dfs['Close']
    prices1 = closes[-1]
    prices2 = closes[-2]
    pdiffs = ((prices1 - prices2) / prices2) * 100
    diffs = "%.2f" % pdiffs
    price_sensex = "%.2f" % prices1
    if pdiffs >= 0:
        diffs_green = "+" + diffs + "%"
    else:
        diffs_green = ""

    if pdiffs <= 0:
        diffs_red = diffs + "%"
    else:
        diffs_red = ""

    dfnb = web.DataReader("^NSEBANK", 'yahoo', start, end)
    closenb = dfnb['Close']
    pricenb1 = closenb[-1]
    pricenb2 = closenb[-2]
    pdiffnb = ((pricenb1 - pricenb2) / pricenb2) * 100
    diffnb = "%.2f" % pdiffnb
    if pdiffnb > 0:
        diffnb_green = "+" + diffnb + "%"
    else:
        diffnb_green = ""

    if pdiffnb < 0:
        diffnb_red = diffnb + "%"
    else:
        diffnb_red = ""
    price_nb = "%.2f" % pricenb1

    dfbm = web.DataReader("BSE-MIDCAP.BO", 'yahoo', start, end)
    closebm = dfbm['Close']
    pricebm1 = closebm[-1]
    pricebm2 = closebm[-2]
    pdiffbm = ((pricebm1 - pricebm2) / pricebm2) * 100
    diffbm = "%.2f" % pdiffbm
    if pdiffbm > 0:
        diffbm_green = "+" + diffbm + "%"
    else:
        diffbm_green = ""

    if pdiffbm < 0:
        diffbm_red = diffbm + "%"
    else:
        diffbm_red = ""
    price_bm = "%.2f" % pricebm1
    tickers = ['LT.BO', 'ITC.NS', 'RELIANCE.NS', 'WIPRO.BO', 'TCS.NS']
    stocks = ["Larsen & Toubro", "ITC Limited", "Reliance Industries", "Wipro", "TATA Consultancy Services"]
    closeps = []
    x = []
    price_diff_green = []
    price_diff_red = []
    hpbar = []
    signal = []
    for ticker in tickers:
        start = dt.datetime(2019, 1, 1)
        end = date.today()
        df = web.DataReader(ticker, 'yahoo', start, end)
        close = df['Close']
        price_diff = ((close[-1] - close[-2]) / close[-2]) * 100
        if price_diff > 0:
            price_diff_green.append("+" + "%.2f" % price_diff + "%")
        else:
            price_diff_green.append("")

        if price_diff < 0:
            price_diff_red.append("%.2f" % price_diff + "%")
        else:
            price_diff_red.append("")
        closeps.append("%.2f" % close[-1])
        x.append(Homepage_db.objects.only('hco_logo').get(htic_name=ticker).hco_logo)
        subscription_key = "d225b3f12aab446aa34af931359edbe0"
        search_term = ticker

        client = NewsSearchAPI(CognitiveServicesCredentials(subscription_key))
        news_result = client.news.search(query=search_term, market="en-us", count=10)

        if news_result.value:

            first_news_result = news_result.value[0]
            data = format(first_news_result.description)



            # print("news name: {}".format(first_news_result.name))
            #
            # print("news description: {}".format(first_news_result.description))


        else:
            HttpResponse("NIL")

        # --------------------------------------------

        TEXT_ANALYTICS_SUBSCRIPTION_KEY = '4d1d3697dc8548b59163e2592b22beb7'
        subscription_key = TEXT_ANALYTICS_SUBSCRIPTION_KEY

        TEXT_ANALYTICS_ENDPOINT = 'https://analytics4sentiment.cognitiveservices.azure.com/'
        endpoint = TEXT_ANALYTICS_ENDPOINT

        credentials = CognitiveServicesCredentials(subscription_key)
        text_analytics_client = TextAnalyticsClient(
            endpoint=endpoint, credentials=credentials)

        client = text_analytics_client

        documents = [
            {"id": "1", "language": "en", "text": data},
                   
        ]

        response = client.sentiment(documents=documents)
        res = []
        for document in response.documents:
            res.append(float(format(document.score)))

        res_mean = (sum(res) * 100)

        if res_mean > 80:
            hpbar.append("StrongBuy_hpbar.svg")
            signal.append("Strong Buy")
        elif 80 > res_mean > 60:
            hpbar.append("Buy_hpbar.svg")
            signal.append("Buy")
        elif 60 > res_mean > 35:
            hpbar.append("Hold_hpbar.svg")
            signal.append("Hold")
        elif 20 > res_mean > 35:
            hpbar.append("Sell_hpbar.svg")
            signal.append("Sell")
        else:
            hpbar.append("StrongSell_hpbar.svg")
            signal.append("Strong Sell")

    rows = zip(x, closeps, price_diff_green, price_diff_red, hpbar, signal, stocks)

    return render(request, 'homepage/homepage.html',
                  {"rows": rows, 'price_nifty': price_nifty, 'diffn_green': diffn_green, 'diffn_red': diffn_red,
                   'price_sensex': price_sensex,
                   'diffs_red': diffs_red, 'diffs_green': diffs_green, 'price_nb': price_nb,
                   'diffnb_green': diffnb_green,
                   'diffnb_red': diffnb_red, 'price_bm': price_bm, 'diffbm_green': diffbm_green,
                   'diffbm_red': diffbm_red})
from newspaper import Article
import pandas as pd
import datetime
import glob
import nltk

nltk.download('gutenberg')

from pprint import pprint
from nltk.tokenize.punkt import PunktSentenceTokenizer, PunktTrainer
from nltk.corpus import gutenberg

subscription_key = "8a4ebe4976ee4e24935b3a1ae0a56cfb"
search_term = "Canada Elections"

client = NewsSearchAPI(CognitiveServicesCredentials(subscription_key))


def Create_news_df(news_result):
    news_df = pd.DataFrame(columns=[
        "Headline", "URL", "Category", "Description", "Date_published",
        "Provider"
    ])
    for i in range(len(news_result.value)):
        if news_result.value:
            news = news_result.value[i]
            new_dict = dict()
            new_dict = {
                "Headline": news.name,
                "URL": news.url,
                "Category": news.category,
Ejemplo n.º 14
0
import threading
import time
from collections import deque
from datetime import datetime

from azure.cognitiveservices.search.newssearch import NewsSearchAPI
from django.conf import settings
from msrest.authentication import CognitiveServicesCredentials

log = logging.getLogger(__name__)

# Process-safe queue for queries to be requested to Bing API.
query_queue = multiprocessing.Manager().Queue()

# Bing API client which takes care of the authentication via the API KEY
client = NewsSearchAPI(CognitiveServicesCredentials(settings.AZURE_API_KEY))


def start():
    """
    Spawns the infinite loop dispatcher process that will consume the query queue

    Calls also the initial queue filler to have some data to play with
    """

    proc = multiprocessing.Process(target=dispatcher)
    proc.start()

    time.sleep(1)
    if not proc.is_alive():
        log.error("Problem starting fetcher process")
Ejemplo n.º 15
0
                                  n_fast=12,
                                  n_slow=26,
                                  n_sign=9,
                                  fillna=False)
        if macd[-1] > macd_sig[-1]:
            trn_macd_status = "Buy"
        elif macd[-1] < macd_sig[-1]:
            trn_macd_status = "Sell"
        else:
            trn_macd_status = "Hold"
        return trn_macd_status

    subscription_key = "d225b3f12aab446aa34af931359edbe0"
    search_term = tickers
    date = 2018, 1, 1
    client = NewsSearchAPI(CognitiveServicesCredentials(subscription_key))
    news_result = client.news.search(query=search_term)

    if news_result.value:
        first_news_result = news_result.value[2]
        data = format(first_news_result.description)

        sec_news_result = news_result.value[3]
        data1 = format(sec_news_result.description)

        third_news_result = news_result.value[4]
        data2 = format(third_news_result.description)

        # print("news name: {}".format(first_news_result.name))
        #
        # print("news description: {}".format(first_news_result.description))