def __init__(self): """initiate module""" self.BASE_URL = ( "https://finviz.com/screener.ashx?v=411{signal}{filter}&ft=4{ticker}" ) self.url = self.BASE_URL.format(signal="", filter="", ticker="") Overview._load_setting(self)
def __init__(self): """initiate module """ self.BASE_URL = 'https://finviz.com/screener.ashx?v=141{signal}{filter}&ft=4{ticker}' self.NUMBER_COL = ['Perf Week', 'Perf Month', 'Perf Quart', 'Perf Half', 'Perf Year', 'Perf YTD', 'Volatility W', 'Volatility M', 'Recom', 'Avg Volume', 'Rel Volume', 'Price', 'Change', 'Volume'] self.url = self.BASE_URL.format(signal='', filter='', ticker='') Overview._loadSetting(self)
def __init__(self): """initiate module """ self.BASE_URL = 'https://finviz.com/screener.ashx?v=161{signal}{filter}&ft=4{ticker}' self.NUMBER_COL = ['Market Cap', 'Dividend', 'ROA', 'ROE', 'ROI', 'Curr R', 'Quick R', 'LTDebt/Eq', 'Debt/Eq', 'Gross M', 'Oper M', 'Profit M', 'Price', 'Change', 'Volume'] self.url = self.BASE_URL.format(signal='', filter='', ticker='') Overview._loadSetting(self)
def __init__(self): """initiate module """ self.BASE_URL = 'https://finviz.com/screener.ashx?v=121{signal}{filter}&ft=4{ticker}' self.NUMBER_COL = ['Market Cap', 'P/E', 'Fwd P/E', 'PEG', 'P/S', 'P/B', 'P/C', \ 'P/FCF', 'EPS this Y', 'EPS next Y', 'EPS past 5Y', 'EPS next 5Y', \ 'Sales past 5Y', 'Price', 'Change', 'Volume'] self.url = self.BASE_URL.format(signal='', filter='', ticker='') Overview._loadSetting(self)
def __init__(self): """initiate module """ self.BASE_URL = 'https://finviz.com/screener.ashx?v=171{signal}{filter}&ft=4{ticker}' self.NUMBER_COL = [ 'Beta', 'ATR', 'SMA20', 'SMA50', 'SMA200', '52W High', '52W Low', 'RSI', 'Price', 'Change', 'from Open', 'Gap', 'Volume' ] self.url = self.BASE_URL.format(signal='', filter='', ticker='') Overview._loadSetting(self)
def __init__(self): """initiate module """ self.BASE_URL = 'https://finviz.com/screener.ashx?v=131{signal}{filter}&ft=4{ticker}' self.NUMBER_COL = [ 'Market Cap', 'Outstanding', 'Float', 'Insider Own', 'Insider Trans', 'Inst Own', 'Inst Trans', 'Float Short', 'Short Ratio', 'Avg Volume', 'Price', 'Change', 'Volume' ] self.url = self.BASE_URL.format(signal='', filter='', ticker='') Overview._loadSetting(self)
def get_similar_companies(ticker: str, compare_list: List[str]) -> Tuple[List[str], str]: """Get similar companies from Finviz Parameters ---------- ticker : str Ticker to find comparisons for compare_list : List[str] List of fields to comparse Returns ------- List[str] List of similar companies str String containing data source """ try: similar = (Overview().compare(ticker, compare_list, verbose=0)["Ticker"].to_list()) user = "******" except Exception as e: console.print(e) similar = [""] user = "******" return similar, user
def partition_days(self, mode="financial"): """Partition dataframe to separate dataframes according to the dates. Args: mode(str): choose an option of period(financial, overview, valuation, ownership, performance, technical). """ check_list = [ "financial", "overview", "valuation", "ownership", "performance", "technical", ] if mode not in check_list: raise ValueError("Invalid mode '{}'. Available mode: {}".format( mode, check_list)) for earning_day in self.earning_days: if mode == "financial": self.df_days[earning_day] = self.df[ self.df["Earnings"] == earning_day].reset_index(drop=True) else: self.df_days[earning_day] = self.df[ self.df["Earnings"] == earning_day]["Ticker"].to_list() fearnings = None if mode == "financial": return self.df_days elif mode == "overview": fearnings = Overview() elif mode == "valuation": fearnings = Valuation() elif mode == "ownership": fearnings = Ownership() elif mode == "performance": fearnings = Performance() elif mode == "technical": fearnings = Technical() filters_dict = {"Earnings Date": self.period} fearnings.set_filter(filters_dict=filters_dict) df2 = fearnings.screener_view(order="Earnings Date", verbose=0) df2_days = {} for earning_day in self.earning_days: tickers = self.df_days[earning_day] df2_days[earning_day] = df2[df2["Ticker"].isin( tickers)].reset_index(drop=True) self.df_days = df2_days return self.df_days
def test_screener_overview(): foverview = Overview() filters_dict = {'Exchange': 'AMEX', 'Sector': 'Basic Materials'} foverview.set_filter(filters_dict=filters_dict) df = foverview.screener_view() assert (df is not None) ticker = 'TSLA' foverview.set_filter(signal='', filters_dict={}, ticker=ticker) df = foverview.screener_view() assert (df is not None)
def partitionDays(self, mode='financial'): """Partition dataframe to separate dataframes according to the dates. Args: mode(str): choose an option of period(financial, overview, valuation, ownership, performance, technical). """ check_list = [ 'financial', 'overview', 'valuation', 'ownership', 'performance', 'technical' ] if mode not in check_list: print('Available mode: {}'.format(check_list)) raise ValueError() for earning_day in self.earning_days: if mode == 'financial': self.df_days[earning_day] = self.df[ self.df['Earnings'] == earning_day].reset_index(drop=True) else: self.df_days[earning_day] = self.df[ self.df['Earnings'] == earning_day]['Ticker'].to_list() fearnings = None if mode == 'financial': return self.df_days elif mode == 'overview': fearnings = Overview() elif mode == 'valuation': fearnings = Valuation() elif mode == 'ownership': fearnings = Ownership() elif mode == 'performance': fearnings = Performance() elif mode == 'technical': fearnings = Technical() filters_dict = {'Earnings Date': self.period} fearnings.set_filter(filters_dict=filters_dict) df2 = fearnings.ScreenerView(order='Earnings Date', verbose=0) df2_days = {} for earning_day in self.earning_days: tickers = self.df_days[earning_day] df2_days[earning_day] = df2[df2['Ticker'].isin( tickers)].reset_index(drop=True) self.df_days = df2_days return self.df_days
def test_screener_get_settings(): foverview = Overview() signals = foverview.get_signal() assert type(signals) is list filters = foverview.get_filters() assert type(filters) is list filter_options = foverview.get_filter_options('Exchange') assert type(filter_options) is list with pytest.raises(ValueError): foverview.get_filter_options('Dummy')
def __init__(self): """initiate module """ self.BASE_URL = 'https://finviz.com/screener.ashx?v=131{signal}{filter}&ft=4{ticker}' self.url = self.BASE_URL.format(signal='', filter='', ticker='') Overview._loadSetting(self)
def get_similar_companies(self, other_args: List[str]): """ Get similar companies. [Source: Polygon API] """ parser = argparse.ArgumentParser( add_help=False, prog="get", description="""Get similar companies to compare with.""", ) parser.add_argument( "-p", "--polygon", action="store_true", default=False, dest="b_polygon", help="Polygon data source flag.", ) # If polygon source not selected, the user may want to get # similar companies based on Industry and Sector only, and not # on the fact that they are based on the same country if "-p" not in other_args and "--polygon" not in other_args: parser.add_argument( "--nocountry", action="store_true", default=False, dest="b_no_country", help= "Similar stocks from finviz using only Industry and Sector.", ) try: ns_parser = parse_known_args_and_warn(parser, other_args) if not ns_parser: return if ns_parser.b_polygon: result = requests.get( f"https://api.polygon.io/v1/meta/symbols/{self.ticker.upper()}/company?&apiKey={cfg.API_POLYGON_KEY}" ) if result.status_code == 200: self.similar = result.json()["similar"] self.user = "******" else: print(result.json()["error"]) else: if ns_parser.b_no_country: compare_list = ["Sector", "Industry"] else: compare_list = ["Sector", "Industry", "Country"] self.similar = (Overview().compare( self.ticker, compare_list, verbose=0)["Ticker"].to_list()) self.user = "******" if self.similar: print( f"\n[{self.user}] Similar Companies: {', '.join(self.similar)}" ) if len(self.similar) > 10: print( "\nThe limit of stocks to compare with are 10. Hence, 10 random similar stocks will be displayed.", "\nThe selected list will be:", ) random.shuffle(self.similar) self.similar = sorted(self.similar[:10]) print(", ".join(self.similar)) except Exception as e: print(e) print("") return
def test_group_overview(): from finvizfinance.group.overview import Overview fgoverview = Overview() df = fgoverview.ScreenerView(group='Industry') assert (df is not None)
def get_similar_companies(self, other_args: List[str]): """Get similar companies. [Source: Polygon API] Parameters ---------- other_args : List[str] argparse other args """ parser = argparse.ArgumentParser( add_help=False, prog="get", description="""Get similar companies to compare with.""", ) parser.add_argument( "-s", "--source", action="store", default="finviz", dest="source", choices=["polygon", "finnhub", "finviz"], help="source that provides similar companies", ) # If source is finviz the user may want to get # similar companies based on Industry and Sector only, and not # on the fact that they are based on the same country if "finviz" in other_args or not other_args: parser.add_argument( "--nocountry", action="store_true", default=False, dest="b_no_country", help= "Similar stocks from finviz using only Industry and Sector.", ) try: if other_args: if "-" not in other_args[0]: other_args.insert(0, "-s") ns_parser = parse_known_args_and_warn(parser, other_args) if not ns_parser: return if ns_parser.source == "polygon": result = requests.get( f"https://api.polygon.io/v1/meta/symbols/{self.ticker.upper()}/company?&apiKey={cfg.API_POLYGON_KEY}" ) if result.status_code == 200: self.similar = result.json()["similar"] self.user = "******" else: print(result.json()["error"]) elif ns_parser.source == "finnhub": result = requests.get( f"https://finnhub.io/api/v1/stock/peers?symbol={self.ticker}&token={cfg.API_FINNHUB_KEY}" ) if result.status_code == 200: d_peers = result.json() if d_peers: self.similar = d_peers self.user = "******" else: print("Similar companies not found.") else: if ns_parser.b_no_country: compare_list = ["Sector", "Industry"] else: compare_list = ["Sector", "Industry", "Country"] self.similar = (Overview().compare( self.ticker, compare_list, verbose=0)["Ticker"].to_list()) self.user = "******" if self.ticker.upper() in self.similar: self.similar.remove(self.ticker.upper()) if len(self.similar) > 10: random.shuffle(self.similar) self.similar = sorted(self.similar[:10]) print( "The limit of stocks to compare with are 10. Hence, 10 random similar stocks will be displayed.\n", ) if self.similar: print( f"[{self.user}] Similar Companies: {', '.join(self.similar)}" ) except Exception as e: print(e) print("") return