Add cash flow and SEC filing command

This commit is contained in:
didier
2021-01-03 23:26:11 +00:00
parent 24df5c93e3
commit 5f57594137
3 changed files with 243 additions and 1 deletions

View File

@@ -2,6 +2,7 @@ import argparse
import pandas as pd
from bs4 import BeautifulSoup
import requests
from stock_market_helper_funcs import *
# ---------------------------------------------------- INCOME ----------------------------------------------------
def income(l_args, s_ticker):
@@ -178,3 +179,232 @@ def liabilities(l_args, s_ticker):
except:
print("ERROR!\n")
return
# ---------------------------------------------------- OPERATING ----------------------------------------------------
def operating(l_args, s_ticker):
parser = argparse.ArgumentParser(prog='operating',
description="""Gives cash flow operating activities of the company. The following fields
are expected: Net Income before Extraordinaries, Net Income Growth, Depreciation,
Depletion & Amortization, Depreciation and Depletion, Amortization of Intangible Assets,
Deferred Taxes & Investment Tax Credit, Deferred Taxes, Investment Tax Credit, Other Funds,
Funds from Operations, Extraordinaries, Changes in Working Capital, Receivables, Accounts Payable,
Other Assets/Liabilities, and Net Operating Cash Flow Growth. [Source: Market Watch BS]""")
parser.add_argument('-q', "--quarter", action="store_true", default=False, dest="b_quarter", help='Quarter fundamental data')
try:
(ns_parser, l_unknown_args) = parser.parse_known_args(l_args)
if l_unknown_args:
print(f"The following args couldn't be interpreted: {l_unknown_args}")
if ns_parser.b_quarter:
url_financials = f"https://www.marketwatch.com/investing/stock/{s_ticker}/financials/cash-flow/quarter"
else:
url_financials = f"https://www.marketwatch.com/investing/stock/{s_ticker}/financials/cash-flow"
text_soup_financials = BeautifulSoup(requests.get(url_financials).text,"lxml")
# Define financials columns
a_financials_header = list()
for financials_header in text_soup_financials.findAll('th', {'class': 'overflow__heading'}):
a_financials_header.append(financials_header.text.strip('\n').split('\n')[0])
s_header_end_trend = ("5-year trend", "5- qtr trend")[ns_parser.b_quarter]
df_financials = pd.DataFrame(columns=a_financials_header[0:a_financials_header.index(s_header_end_trend)])
# Add financials values
soup_financials = text_soup_financials.findAll('tr', {'class': 'table__row '})
soup_financials += text_soup_financials.findAll('tr', {'class': 'table__row is-highlighted'})
for financials_info in soup_financials:
a_financials_info = financials_info.text.split('\n')
l_financials = [a_financials_info[2]]
l_financials.extend(a_financials_info[5:-2])
n_vals_to_add = len(df_financials.columns)-len(l_financials)
if n_vals_to_add > 0:
l_financials.append(n_vals_to_add * ' ')
# Append data values to financials
df_financials.loc[len(df_financials.index)] = l_financials
# Set item name as index
df_financials = df_financials.set_index('Item')
print(df_financials.iloc[:16].to_string())
print("")
except:
print("ERROR!\n")
return
# ---------------------------------------------------- INVESTING ----------------------------------------------------
def investing(l_args, s_ticker):
parser = argparse.ArgumentParser(prog='investing',
description="""Gives cash flow investing activities of the company. The following fields
are expected: Capital Expenditures, Capital Expenditures Growth, Capital Expenditures/Sales,
Capital Expenditures (Fixed Assets), Capital Expenditures (Other Assets), Net Assets from Acquisitions,
Sale of Fixed Assets & Businesses, Purchase/Sale of Investments, Purchase of Investments,
Sale/Maturity of Investments, Other Uses, Other Sources, Net Investing Cash Flow Growth.
[Source: Market Watch BS]""")
parser.add_argument('-q', "--quarter", action="store_true", default=False, dest="b_quarter", help='Quarter fundamental data')
try:
(ns_parser, l_unknown_args) = parser.parse_known_args(l_args)
if l_unknown_args:
print(f"The following args couldn't be interpreted: {l_unknown_args}")
if ns_parser.b_quarter:
url_financials = f"https://www.marketwatch.com/investing/stock/{s_ticker}/financials/cash-flow/quarter"
else:
url_financials = f"https://www.marketwatch.com/investing/stock/{s_ticker}/financials/cash-flow"
text_soup_financials = BeautifulSoup(requests.get(url_financials).text,"lxml")
# Define financials columns
a_financials_header = list()
for financials_header in text_soup_financials.findAll('th', {'class': 'overflow__heading'}):
a_financials_header.append(financials_header.text.strip('\n').split('\n')[0])
s_header_end_trend = ("5-year trend", "5- qtr trend")[ns_parser.b_quarter]
df_financials = pd.DataFrame(columns=a_financials_header[0:a_financials_header.index(s_header_end_trend)])
# Add financials values
soup_financials = text_soup_financials.findAll('tr', {'class': 'table__row '})
soup_financials += text_soup_financials.findAll('tr', {'class': 'table__row is-highlighted'})
for financials_info in soup_financials:
a_financials_info = financials_info.text.split('\n')
l_financials = [a_financials_info[2]]
l_financials.extend(a_financials_info[5:-2])
n_vals_to_add = len(df_financials.columns)-len(l_financials)
if n_vals_to_add > 0:
l_financials.append(n_vals_to_add * ' ')
# Append data values to financials
df_financials.loc[len(df_financials.index)] = l_financials
# Set item name as index
df_financials = df_financials.set_index('Item')
print(df_financials.iloc[17:30].to_string())
print("")
except:
print("ERROR!\n")
return
# ---------------------------------------------------- FINANCING ----------------------------------------------------
def financing(l_args, s_ticker):
parser = argparse.ArgumentParser(prog='financing',
description="""Gives cash flow financing activities of the company. The following fields
are expected: Cash Dividends Paid - Total, Common Dividends, Preferred Dividends,
Change in Capital Stock, Repurchase of Common & Preferred Stk., Sale of Common & Preferred Stock,
Proceeds from Stock Options, Other Proceeds from Sale of Stock, Issuance/Reduction of Debt, Net,
Change in Current Debt, Change in Long-Term Debt, Issuance of Long-Term Debt, Reduction in Long-Term Debt,
Other Funds, Other Uses, Other Sources, Net Financing Cash Flow Growth, Net Financing Cash Flow/Sales,
Exchange Rate Effect, Miscellaneous Funds, Net Change in Cash, Free Cash Flow, Free Cash Flow Growth,
Free Cash Flow Yield, Net Operating Cash Flow, Net Investing Cash Flow, Net Financing Cash Flow
[Source: Market Watch BS]""")
parser.add_argument('-q', "--quarter", action="store_true", default=False, dest="b_quarter", help='Quarter fundamental data')
try:
(ns_parser, l_unknown_args) = parser.parse_known_args(l_args)
if l_unknown_args:
print(f"The following args couldn't be interpreted: {l_unknown_args}")
if ns_parser.b_quarter:
url_financials = f"https://www.marketwatch.com/investing/stock/{s_ticker}/financials/cash-flow/quarter"
else:
url_financials = f"https://www.marketwatch.com/investing/stock/{s_ticker}/financials/cash-flow"
text_soup_financials = BeautifulSoup(requests.get(url_financials).text,"lxml")
# Define financials columns
a_financials_header = list()
for financials_header in text_soup_financials.findAll('th', {'class': 'overflow__heading'}):
a_financials_header.append(financials_header.text.strip('\n').split('\n')[0])
s_header_end_trend = ("5-year trend", "5- qtr trend")[ns_parser.b_quarter]
df_financials = pd.DataFrame(columns=a_financials_header[0:a_financials_header.index(s_header_end_trend)])
# Add financials values
soup_financials = text_soup_financials.findAll('tr', {'class': 'table__row '})
soup_financials += text_soup_financials.findAll('tr', {'class': 'table__row is-highlighted'})
for financials_info in soup_financials:
a_financials_info = financials_info.text.split('\n')
l_financials = [a_financials_info[2]]
l_financials.extend(a_financials_info[5:-2])
n_vals_to_add = len(df_financials.columns)-len(l_financials)
if n_vals_to_add > 0:
l_financials.append(n_vals_to_add * ' ')
# Append data values to financials
df_financials.loc[len(df_financials.index)] = l_financials
# Set item name as index
df_financials = df_financials.set_index('Item')
print(df_financials.iloc[31:].to_string())
print("")
except:
print("ERROR!\n")
return
# ---------------------------------------------------- SEC FILLINGS ----------------------------------------------------
def sec_fillings(l_args, s_ticker):
parser = argparse.ArgumentParser(prog='sec',
description="""Gives SEC filings of the company. The following fields
are expected: Filing Date, Document Date, Type, Category, Amended, and Link.
[Source: Market Watch BS]""")
parser.add_argument('-n', "--num", action="store", dest="n_num", type=check_positive, default=5, help='Number of latest SEC filings')
try:
(ns_parser, l_unknown_args) = parser.parse_known_args(l_args)
if l_unknown_args:
print(f"The following args couldn't be interpreted: {l_unknown_args}")
pd.set_option('display.max_colwidth', -1)
url_financials = "https://www.marketwatch.com/investing/stock/aapl/financials/secfilings"
text_soup_financials = BeautifulSoup(requests.get(url_financials).text,"lxml")
a_financials_header = list()
b_ready_to_process_info = False
soup_financials = text_soup_financials.findAll('tr', {'class': 'table__row'})
for financials_info in soup_financials:
a_financials = financials_info.text.split('\n')
# If header has been processed and dataframe created ready to populate the SEC information
if b_ready_to_process_info:
l_financials_info = [a_financials[2]]
l_financials_info.extend(a_financials[5:-1])
l_financials_info.append(financials_info.a['href'])
# Append data values to financials
df_financials.loc[len(df_financials.index)] = l_financials_info
if 'Filing Date' in a_financials:
l_financials_header = [a_financials[2]]
l_financials_header.extend(a_financials[5:-1])
l_financials_header.append('Link')
df_financials = pd.DataFrame(columns=l_financials_header)
df_financials.set_index('Filing Date')
b_ready_to_process_info = True
# Set Filing Date as index
df_financials = df_financials.set_index('Filing Date')
print(df_financials.head(n=ns_parser.n_num))
print("")
except:
print("ERROR!\n")
return

View File

@@ -203,6 +203,18 @@ def fa_menu(fa_parser, s_ticker, s_start, s_interval):
elif ns_known_args.fa == 'liabilities':
mw_bs.liabilities(l_args, s_ticker)
elif ns_known_args.fa == 'operating':
mw_bs.operating(l_args, s_ticker)
elif ns_known_args.fa == 'investing':
mw_bs.investing(l_args, s_ticker)
elif ns_known_args.fa == 'financing':
mw_bs.financing(l_args, s_ticker)
elif ns_known_args.fa == 'sec':
mw_bs.sec_fillings(l_args, s_ticker)
# ------------------------------------------------------------------------------------------------------------
else:
print("Command not recognized!")

View File

@@ -66,7 +66,7 @@ def main():
'profile', 'rating', 'quote', 'enterprise', 'dcf', # FMP
'inc', 'bal', 'cashf', 'metrics', 'ratios', 'growth', # FMP
'screener', 'insider', 'news', 'analyst', # Finviz
'incom', 'assets', 'liabilities']) # MW
'incom', 'assets', 'liabilities', 'operating', 'investing', 'financing', 'sec']) # MW
# Add list of arguments that the technical analysis parser accepts
ta_parser = argparse.ArgumentParser(prog='technical_analysis', add_help=False)