How to scrap Zacks Rank signal in Python





If you trade in the US market or follow market analysis you probably heard about Zacks Rank system provided by Zacks Investment Group.
This ranking system is based on fundamental conditions of the company which revise frequently. the Zacks analysts revise their analysis based on most recent information about each company, and at the end Zacks rank each company in five different level.
1- Strong Buy
2- Buy
3- Hold
4- Sell
5- Strong Sell
You should be noted that based on Zacks, these are not recommendation for buying or selling the equities, rather these are the analysis of companies fundamental usually based on a benchmark like SP500 index.
In other words, for instance if a company has Zacks Rank 3 or Hold, that means its returns is foretasted to be aligned with the SP500 return. For the Zacks Rank 4 or Sell the projection is it under-perform the benchmark and so on.
Zacks claim these analysis is the 1 to 3 months projection and can be revised anytime based on the new information.
You can visit any company's Rank by visiting Zacks.com and searching company's rank for free.
Although the most valuable analysis is the report for the companies which is a premium feature and you can access to them by subscribing to their website.
If you just want to use its free ranks or cannot afford the subscription fee you will be confronted with a huge amount of companies that searching their ticker is time consuming. Imagine there is  just over 500 tickers in SP500 index. The following code solved this problem. It can scrap all the ranks and save them into a .csv file.
I should warn you never trade just based on these ranks specially when you don't have access to the full report of each company. But it would give you a good sense about the company's condition if you have your own trading strategy and just want to get a confirmation from other sources.

workingdirectory = 'define your working directory here this is the place where the file will be saved'
import pandas as pd
import urllib.request
import datetime as dt
import os
os.chdir(workingdirectory)
# This funtion scrap each Symbol page and extract the Zacks Rank
def Zacks_Rank(Symbol):
 
    # Wait for 2 seconds
    #time.sleep(2)
    url = 'https://quote-feed.zacks.com/index?t='+Symbol
    downloaded_data  = urllib.request.urlopen(url)
    data = downloaded_data.read()
    data_str = data.decode()
    Z_Rank =["Strong Buy","Buy","Hold","Sell","Strong Sell"]
    def between(value, a, b): # extracting FUNCTION TO open ,low,high,volume from data
        # Find and validate before-part.
        pos_a = value.find(a) # return the first character index or -1= Not exist
        if pos_a == -1: return ""
        # Find and validate after part.
        pos_b = value.rfind(b)
        if pos_b == -1: return ""
        # Return middle part.
        adjusted_pos_a = pos_a + len(a)
        if adjusted_pos_a >= pos_b: return ""
        return value[adjusted_pos_a:pos_b]
    for Rank in Z_Rank:
       #data_str.find(Rank)# az tooye list Z_Rank doone doone check kon va yeki ra dar str_data
       # peyda kon ;; faghat index harf aval ro retrun mikond
       if(data_str.find(Rank) != -1):
           return Rank #data_str[res:res+len(Rank)]#

# this function put each ticker in its rank list and return the result
def Market_Rank(Symbols):
    Strong_Buy=[]
    Buy=[]
    Hold=[]
    Sell=[]
    Strong_Sell=[]
    for symbol in Symbols:
        Rank = Zacks_Rank(symbol)#
        if(Rank == 'Strong Buy'):
            Strong_Buy.append(symbol)
        elif(Rank == 'Buy'):
            Buy.append(symbol)
        elif(Rank == 'Hold'):
            Hold.append(symbol)
        elif(Rank == 'Sell'):
            Sell.append(symbol)
        elif(Rank == 'Strong Sell'):
            Strong_Sell.append(symbol)
   
    Result = {'Strong_Buy':Strong_Buy,'Buy':Buy,'Hold':Hold,'Sell':Sell,'Strong_Sell':Strong_Sell}
    return Result

# please make your watch list here
SP500=["A",… ,"ZTS"]

# Executing the code Here then print the result for each rank
if(True):
    result = Market_Rank(SP500)
    print('Strong Buy are:\n')
    print(result['Strong_Buy'])
    print('===================================')
    print('Buy are:\n')
    print(result['Buy'])
    print('===================================')
    print('HOLD are:\n')
 #   print(result['Hold'])
    print('===================================')
    print('SELL are:\n')
    print(result['Sell'])
    print('===================================')
    print('STRONG SELL are:\n')
    print(result['Strong_Sell'])
    # append the result into data frame :: different key sizes so it should produce NAN values
    dict_df = pd.DataFrame({ key:pd.Series(value) for key, value in result.items() })
    today = dt.datetime.today().strftime('%Y-%m-%d')
# save the file into the working directory with dated name
    dict_df.to_csv(path_or_buf=workingdirectory +'/SP500'+today+'.csv',index =False)





Comments

Popular posts from this blog

Application of GARCH models in R – Part II ( APARCH)

How to check if a distribution is normal?