def holdings(tickers, metadata, type): code = 0 for i in tickers: try: if len(type) == 0: resp = cm.getHtml("hld", i) code = resp[0] d = getTopHoldings(resp[1], i) return d elif type == 'comp': resp = cm.getHtml("hld", i) code = resp[0] d = getComposition(resp[1], i) return d elif type == 'weight': resp = cm.getHtml("hld", i) code = resp[0] d = getWeight(resp[1], i) return d except: print( "Exception occured, this is the status code {0}, and this is the ticker - {1}" .format(code, i)) traceback.print_exc() return None
def main(filter, tickers): """ Usage: ./script.py [quote|fin|bs|cf] [ticker] quote: returns the basic data for the ticker as a dataframe fin: returns the income statement for the ticker as a dataframe bs: returns the balance sheet for the ticker as a dataframe cf: returns the cash flow for the ticker as a dataframe -> You can also get quote for various other securities, and a group of securities. There is a universe of securty tickers that can be found in /data/ folder. There are csv files where the ticker information is saved. Below are examples on how to query: ./script.py quote filename_startindex:endindex Examples: ------------------------------------------------------------------------------------------------------------------------------ |./script.py quote Stocks_1001:1003 | This returns the quote for stocks index 1001 (inclusive) to 1003 (not inclusive) | ------------------------------------------------------------------------------------------------------------------------------ |./script.py quote Currency_2011:2016| This returns the quote for currency index 2011 (inclusive) to 2016 (not inclusive) | ------------------------------------------------------------------------------------------------------------------------------ To get the index of required tickers in a file use the grep command, for example: ------------------------------------------------------------------------------------------------------------------------------ |grep -in apple Stocks.csv | This returns all lines & line number containing "Apple" startindex = line number - 2 | ------------------------------------------------------------------------------------------------------------------------------ """ if filter == 'quote': input = str(tickers) return q.getQuote(input) elif filter == 'fin': resp = cm.getHtml("financial", tickers) if resp[0] == 200: df = f.getFinancialNumbers(resp[1]) pd.set_option('display.max_rows', 10, 'display.max_columns', 100) return df elif filter == 'bs': resp = cm.getHtml("bs", tickers) if resp[0] == 200: df = b.getBalanceSheet(resp[1]) pd.set_option('display.max_rows', 10, 'display.max_columns', 100) return df elif filter == 'cf': resp = cm.getHtml("cf", tickers) if resp[0]: df = c.getCashFlow(resp[1]) pd.set_option('display.max_rows', 10, 'display.max_columns', 100) return df else: print("Invalid data request type, usage: ", end='') print("'./script.py [quote|fin|bs|cf] [ticker]'")
def dividend(tickers, metadata, val_filter_1): code = 0 test = lambda x: (x >= float(val_filter_1)) l = [] data_return = {} for i in tickers: try: resp = cm.getHtml("quote", i) code = resp[0] quote = q.parse(resp[1]) val = re.search( "[0-9]*[.][0-9]*", str(str(quote['Forward Dividend & Yield']).split(' ')[5])) if val: if test(float(val.group())): print(val.group(), end='') l = [val for val in metadata if val['Ticker'] == str(i)] if len(l) > 0: print(" -----------------INFO------------> ", end='') print(l[0]) else: print(" ---Ticker (No Info available)--> ", end='') print(i) data_return[i] = float(val.group()) except: print( "Exception occured, this is the status code {0}, and this is the ticker - {1}" .format(code, i)) #traceback.print_exc() return data_return
def pe_ratio(tickers, metadata, val_filter_1, val_filter_2): code = 0 test = False l = [] data_return = {} if str(val_filter_1) == 'lt': test = lambda x: (x <= float(val_filter_2)) elif str(val_filter_1) == 'gt': test = lambda x: (x >= float(val_filter_2)) for i in tickers: try: resp = cm.getHtml("quote", i) code = resp[0] quote = q.parse(resp[1]) pe = float(quote['PE Ratio (TTM)']) if test(pe): print(pe, end='') l = [val for val in metadata if val['Ticker'] == str(i)] if len(l) > 0: print(" -----------------INFO------------> ", end='') print(l[0]) else: print(" ---Ticker (No Info available)--> ", end='') print(i) data_return[i] = pe except: print( "Exception occured, this is the status code {0}, and this is the ticker - {1}" .format(code, i)) #traceback.print_exc() return data_return
def risk(tickers, metadata): code = 0 for i in tickers: try: resp = cm.getHtml("risk", i) code = resp[0] return getRisk(resp[1], i) except: print("Exception occured, this is the status code {0}, and this is the ticker".format(i)) traceback.print_exc() return None
def history(tickers, metadata): code = 0 for i in tickers: try: resp = cm.getHtml("hist", i) code = resp[0] d = getHistoryData(resp[1], i) return d except: print( "Exception occured, this is the status code {0}, and this is the ticker - {1}" .format(code, i)) traceback.print_exc() return None
def getQuote(input): df_list = {} if "_" in input: count = 0 details = [] if os.path.isfile('./data/' + input[0:int(input.index("_"))] + '.csv'): details = tl.ticker_details(input) for i in tl.tickers(input): resp = cm.getHtml("quote", i) try: if resp[0] == 200: df = parse(resp[1]) pd.set_option('display.max_rows', 5, 'display.max_columns', 100) #print("Quote for: {} ".format(i), end='') if len(details) > count: #print(details[count]) df_list[str(details[count])] = df else: df_list[i] = df #print("No Details available") #print(df) except: print( "Exception occured while getting quote for: {0}".format(i)) traceback.print_exc() finally: count = count + 1 return df_list else: resp = cm.getHtml("quote", input) if resp[0] == 200: df = parse(resp[1]) pd.set_option('display.max_rows', 5, 'display.max_columns', 100) #print(df) return df return df_list
def performance(tickers, metadata, type): code = 0 for i in tickers: try: resp = cm.getHtml("perf", i) code = resp[0] if type == 'ann': d = getPerformanceData(resp[1], i) return d elif type == 'trail': d = getPerformanceTrail(resp[1], i) return d except: print( "Exception occured, this is the status code {0}, and this is the ticker - {1}" .format(code, i)) traceback.print_exc() return None
def profit(tickers, metadata): l = [] data_return = {} #locale.setlocale(locale.LC_ALL, '') for i in tickers: try: resp = cm.getHtml("financial", i) code = resp[0] fin = f.getFinancialNumbers(resp[1]) revenue = [ int(i.replace(",", "")) for i in list(fin['Total Revenue']) ] cost = [ int(i.replace(",", "")) for i in list(fin['Cost of Revenue']) ] sga = [ int(i.replace(",", "")) for i in list(fin['Selling General and Administrative']) ] prof = [] for x in range(0, len(revenue)): t = revenue[x] - (cost[x] + sga[x]) prof.append(t) print("Net Profit: ", end='') print(['{:,}'.format(i) + ',000' for i in prof[1:]], end='') change = list(pd.Series(prof[::-1]).pct_change())[1:] rate = [round(i * 100, 3) for i in change][::-1][1:] print("; % Profit change (y/y): ", end='') print(rate, end='') l = [val for val in metadata if val['Ticker'] == str(i)] if len(l) > 0: print(" -----------------INFO------------> ", end='') print(l[0]) else: print(" ---Ticker (No Info available)--> ", end='') print(i) data_return[i] = (prof[1:], rate) except: print( "Exception occured, this is the status code {0}, and this is the ticker - {1}" .format(code, i)) #traceback.print_exc() return data_return
def ratio(tickers, metadata): l = [] data_return = {} for i in tickers: try: resp = cm.getHtml("financial", i) code = resp[0] fin = f.getFinancialNumbers(resp[1]) revenue = [ int(i.replace(",", "")) for i in list(fin['Total Revenue']) ] net = [int(i.replace(",", "")) for i in list(fin['Net Income'])] rd = [ int(i.replace(",", "")) for i in list(fin['Research Development']) ] prof = [] for x in range(0, len(revenue)): t = revenue[x] / (net[x] + rd[x]) prof.append(t) #change = list(pd.Series(prof[::-1]).pct_change())[1:] rate = [round(i, 3) for i in prof][1:] print(rate, end='') l = [val for val in metadata if val['Ticker'] == str(i)] if len(l) > 0: print(" -----------------INFO------------> ", end='') print(l[0]) else: print(" ---Ticker (No Info available)--> ", end='') print(i) data_return[i] = rate except: print( "Exception occured, this is the status code {0}, and this is the ticker - {1}" .format(code, i)) #traceback.print_exc() return data_return
def growth(tickers, metadata, val_filter_1): code = 0 test = lambda x: (x >= int(val_filter_1)) l = [] data_return = {} for i in tickers: try: ret_tickers = [] resp = cm.getHtml("financial", i) code = resp[0] fin = f.getFinancialNumbers(resp[1]) revenue = [ int(i.replace(",", "")) for i in list(fin['Total Revenue']) ] change = list(pd.Series(revenue[::-1]).pct_change())[1:] rate = [round(i * 100) for i in change][::-1][1:] for x in rate: if test(x): ret_tickers.append(x) if len(ret_tickers) == 3: data_return[i] = ret_tickers print(ret_tickers, end=' ') l = [val for val in metadata if val['Ticker'] == str(i)] if len(l) > 0: print(" -----------------INFO------------> ", end='') print(l[0]) else: print(" ---Ticker (No Info available)--> ", end='') print(i) except: print( "Exception occured, this is the status code {0}, and this is the ticker - {1}" .format(code, i)) #traceback.print_exc() return data_return