1059 lines
44 KiB
Python
1059 lines
44 KiB
Python
# Refer to the user manual for details on how to use this script and what the script intends to achieve.
|
|
# EDIT: This project is so old the software design document was online only and has been lost to time.
|
|
|
|
import datetime as dt
|
|
import logging
|
|
import os
|
|
import sys
|
|
import requests
|
|
from requests.adapters import HTTPAdapter
|
|
from requests.packages.urllib3.util.retry import Retry
|
|
import pandas as pd
|
|
import io
|
|
import json
|
|
import numpy as np
|
|
import statistics
|
|
import math
|
|
|
|
# Elapsed time it took for the script to run.
|
|
script_start_time = dt.datetime.now()
|
|
|
|
# Hard coded parameters.
|
|
master_ticker_list = []
|
|
current_date = dt.datetime.today()
|
|
|
|
timeseries_days_lookback = 3650 # 10 year look back. Length determined by amount of data needed to calculate seasonality.
|
|
timeseries_start_date = current_date - dt.timedelta(days = timeseries_days_lookback)
|
|
|
|
# Risk-free rate variables.
|
|
forex_code_list = []
|
|
forex_rate_list = []
|
|
|
|
# Factor variables.
|
|
new_ticker_list = []
|
|
name_list = []
|
|
eod_list = []
|
|
country_list = []
|
|
sector_list = []
|
|
industry_list = []
|
|
momentum_list = []
|
|
momentum_1mo_list = []
|
|
roe_list = []
|
|
etd_list = []
|
|
evar_list = []
|
|
roa_list = []
|
|
equal_list = []
|
|
assgro_list = []
|
|
eyield_list = []
|
|
bv_list = []
|
|
size_list = []
|
|
mo_3_vol_list = []
|
|
mo_12_vol_list = []
|
|
max_vol_list = []
|
|
div_yield_list = []
|
|
payout_list = []
|
|
div_growth5_list = []
|
|
div_above_index_list = []
|
|
growth5_list = []
|
|
region_mom_list = []
|
|
region_rfr_list = []
|
|
region_rfr_change_list = []
|
|
region_3m_vol_list = []
|
|
region_12m_vol_list = []
|
|
lt_reversal_list = []
|
|
lt_has_history = []
|
|
earnings_date_list = []
|
|
liquid_21_list = []
|
|
liquid_63_list = []
|
|
liquid_252_list = []
|
|
|
|
# Check if we need to be using dev settings.
|
|
def is_dev_mode():
|
|
if os.getcwd()[-3:] == "dev":
|
|
logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
|
|
else:
|
|
logging.basicConfig(stream=sys.stderr, level=logging.INFO)
|
|
|
|
|
|
# Creating sessions to reduce API calls .
|
|
def create_session():
|
|
session = requests.Session()
|
|
retry = Retry(total=3, backoff_factor=1, status_forcelist=[502, 503, 504])
|
|
adapter = HTTPAdapter(max_retries=retry)
|
|
session.mount('https://', adapter)
|
|
return session
|
|
|
|
|
|
# In a dev environment it is recommended that FEZ.US and DIA.US ETFs be used for scrapping index data.
|
|
# ETFs used in place of index data should be saved in a text file named "index_inclusion.txt".
|
|
# If none is found, DIA.US will be used.
|
|
# One ETF per line.
|
|
# Every ticker needs a country code, e.g. SPY.US.
|
|
def get_indices():
|
|
index_file = "parameters/index_inclusion.txt"
|
|
if os.path.exists(index_file):
|
|
with open(index_file) as f:
|
|
index_inclusion_list = [x.strip() for x in f.readlines()]
|
|
logging.info(f"Including index data of the following tickers: {index_inclusion_list}")
|
|
else:
|
|
default_index = "DIA.US"
|
|
logging.warning(f"No index_inclusion.txt file found. Using {default_index} as the default index.")
|
|
index_inclusion_list = [default_index]
|
|
return index_inclusion_list
|
|
|
|
|
|
# For measuring benchmark variables and factors.
|
|
def get_parent_index():
|
|
parent_index_file = "parameters/parent_index.txt"
|
|
if os.path.exists(parent_index_file):
|
|
with open(parent_index_file) as f:
|
|
parent_index = f.read().strip().split("\n")[0]
|
|
logging.info(f"Following ticker will be used as the parent index: {parent_index}")
|
|
logging.info("If there are multiple indices, only the first one is used.")
|
|
else:
|
|
parent_index = None
|
|
logging.warning("No parent index found.")
|
|
logging.warning("No normalization will be applied to volatility factors")
|
|
return parent_index
|
|
|
|
|
|
def canada_check(url, ticker):
|
|
session = create_session()
|
|
if ticker.endswith('.TO'):
|
|
url_un = url.replace(ticker, ticker[:-3] + "-UN.TO")
|
|
response = session.get(url_un).content
|
|
if response.decode("utf-8") == "Ticker Not Found." or "Symbol not found":
|
|
response = session.get(url).content
|
|
return response
|
|
else:
|
|
return response
|
|
else:
|
|
response = session.get(url).content
|
|
return response
|
|
|
|
|
|
# Returns a json object filled with fundamental data of the security ticker. Do keep in mind that
|
|
# ETFs and individual securities contain different data when called.
|
|
def get_fundamental_data(ticker, token):
|
|
logging.info(f"Getting {ticker} fundamental data.")
|
|
url = f"https://eodhistoricaldata.com/api/fundamentals/{ticker}?api_token={token}"
|
|
return canada_check(url, ticker)
|
|
|
|
|
|
# For calculating yield factor.
|
|
def get_dividend_data(ticker, token):
|
|
logging.info(f"Getting {ticker} dividend data.")
|
|
url = f"https://eodhistoricaldata.com/api/div/{ticker}?fmt=json&api_token={token}"
|
|
return canada_check(url, ticker)
|
|
|
|
|
|
# For calculating momentum and volatility.
|
|
def get_timeseries_data(ticker, token):
|
|
logging.info(f"Getting {ticker} timeseries data.")
|
|
grab_start_date = timeseries_start_date.strftime("%Y-%m-%d")
|
|
url = f"https://eodhistoricaldata.com/api/eod/{ticker}?from={grab_start_date}&api_token={token}"
|
|
return pd.read_csv(io.StringIO(canada_check(url, ticker).decode("utf-8"))).head(-1)
|
|
|
|
|
|
def get_ticker_list(marketIndex, token):
|
|
ticker_list = []
|
|
inclusion_file = "parameters/ticker_inclusion.txt"
|
|
exclusion_file = "parameters/ticker_exclusion.txt"
|
|
|
|
# Add tickers from market index
|
|
for ticker in marketIndex:
|
|
try:
|
|
response = get_fundamental_data(ticker, token)
|
|
if response:
|
|
table_dataframe = pd.read_json(response.decode('utf8'), orient = "index")
|
|
ticker_list += list(pd.DataFrame.from_dict(table_dataframe["Holdings"].iloc[2], orient = "index").index.values)
|
|
except Exception as e:
|
|
logging.info(f"Error occured while processing {ticker}: {e}")
|
|
|
|
# Add tickers that the users want that are not part of the index that is being referenced.
|
|
if os.path.exists(inclusion_file):
|
|
logging.info("Including specific tickers;")
|
|
with open(inclusion_file) as f:
|
|
ticker_inclusion_list = [x.strip() for x in f.readlines() if x.strip() != ""]
|
|
ticker_list += ticker_inclusion_list
|
|
logging.info(ticker_inclusion_list)
|
|
|
|
# Tickers like ERIC B.ST because wtf is a standard
|
|
ticker_list = list(set(ticker_list))
|
|
ticker_list = [ticker.replace(' ', '-') for ticker in ticker_list]
|
|
|
|
# Tickers like FAE/D.MC? WHY LIST TICKERS LIKE THIS?!?!
|
|
ticker_list = [ticker.replace('/', '-') for ticker in ticker_list]
|
|
|
|
# Remove tickers that the users do not want to analyze.
|
|
if os.path.exists(exclusion_file):
|
|
logging.info("Excluding specific tickers;")
|
|
with open(exclusion_file) as f:
|
|
ticker_exclusion_list = [x.strip() for x in f.readlines() if x.strip() != ""]
|
|
for ticker in ticker_exclusion_list:
|
|
if ticker in ticker_list:
|
|
ticker_list.remove(ticker)
|
|
logging.info(ticker_exclusion_list)
|
|
|
|
return ticker_list
|
|
|
|
|
|
def get_riskfree_rate_from_website():
|
|
try:
|
|
# Seriously need to find a better and more reliable source for this.
|
|
response = requests.get("http://www.worldgovernmentbonds.com/central-bank-rates/")
|
|
table_dataframe = pd.read_html(response.content)[0]
|
|
|
|
# Because we store rate data locally after every lookup, this allows us to use
|
|
# locally saved data as a back up.
|
|
benchmark_dataframe = pd.read_csv('riskfree_rate.csv')
|
|
key_policy_countries = benchmark_dataframe["Country"]
|
|
|
|
# Initialize lists to store risk-free rates and rate changes
|
|
rfr_list = []
|
|
rfr_change_list = []
|
|
|
|
for country in key_policy_countries:
|
|
row = table_dataframe.loc[table_dataframe["Paese"] == country, ["Central Bank Rate", "Variation"]].values[0]
|
|
rfr_list.append(float(row[0][:-2]) / 100)
|
|
rfr_change_list.append(0 if pd.isna(row[1]) else float(row[1][:-3]) / 10000)
|
|
|
|
benchmark_dataframe["Rate"] = rfr_list
|
|
benchmark_dataframe["Rate Change"] = rfr_change_list
|
|
|
|
return benchmark_dataframe
|
|
except ValueError:
|
|
return None
|
|
|
|
|
|
def save_riskfree_rate_to_csv(dataframe):
|
|
dataframe.to_csv("riskfree_rate.csv", index = False)
|
|
|
|
|
|
def get_riskfree_rate():
|
|
logging.info("Getting risk-free rates.")
|
|
rate_dataframe = get_riskfree_rate_from_website()
|
|
if rate_dataframe is not None:
|
|
save_riskfree_rate_to_csv(rate_dataframe)
|
|
else:
|
|
rate_dataframe = pd.read_csv('riskfree_rate.csv')
|
|
return rate_dataframe
|
|
|
|
|
|
def price_last_close(ticker, stock_price_data):
|
|
logging.info(f"Getting {ticker} EOD price.")
|
|
if not stock_price_data.empty:
|
|
return stock_price_data["Adjusted_close"].iloc[-1]
|
|
|
|
logging.debug("No price data found?")
|
|
return 0
|
|
|
|
|
|
# Getting non-numerical data of the ticker.
|
|
def get_general_data(ticker, fund_data):
|
|
logging.info(f"Getting general {ticker} stock data.")
|
|
|
|
try:
|
|
general_data = json.loads(fund_data.decode("utf-8")).get("General", {})
|
|
stock_name = general_data["Name"]
|
|
country_name = general_data["CountryName"]
|
|
sector_name = general_data.get("Sector", "Other")
|
|
industry_name = general_data.get("Industry", "Other")
|
|
except (KeyError, json.decoder.JSONDecodeError) as e:
|
|
logging.debug(f"Error: {e}")
|
|
stock_name = "drop_ticker"
|
|
country_name = "drop_ticker"
|
|
sector_name = "Other"
|
|
industry_name = "Other"
|
|
|
|
return [stock_name, country_name, sector_name, industry_name]
|
|
|
|
|
|
def extract_currency_code(fund_data):
|
|
return json.loads(fund_data.decode("utf-8")).get("General", {}).get("CurrencyCode", "USD")
|
|
|
|
|
|
def map_currency_code(code):
|
|
return "GBP" if code == "GBX" else "ILS" if code == "ILA" else code
|
|
|
|
|
|
def get_riskfree_rate_and_change(currency_code):
|
|
rate = riskfree_table[riskfree_table["Currency"] == currency_code]["Rate"].iloc[0]
|
|
rate_change = riskfree_table[riskfree_table["Currency"] == currency_code]["Rate Change"].iloc[0]
|
|
return rate, rate_change
|
|
|
|
|
|
def date_string_to_datetime(dataframe):
|
|
if "Date" in dataframe.columns:
|
|
dataframe["Date"] = pd.to_datetime(dataframe["Date"])
|
|
else:
|
|
dataframe["Adjusted_close"] = [0]
|
|
return dataframe
|
|
|
|
|
|
def extract_weekly_returns(is_israel_stock, price_data):
|
|
weekly = price_data[price_data["Date"].dt.weekday == 3] if is_israel_stock else price_data[price_data["Date"].dt.weekday == 4]
|
|
weekly_returns = (weekly["Adjusted_close"].shift(-1) / weekly["Adjusted_close"]) - 1
|
|
return weekly_returns[:-1]
|
|
|
|
|
|
def calculate_volatility(returns, period=52):
|
|
return np.std(returns) * math.sqrt(period)
|
|
|
|
|
|
def volatility_analysis(ticker, is_israel_stock, price_data):
|
|
logging.info(f"Performing {ticker} volatility factor analysis.")
|
|
|
|
weekly_returns = extract_weekly_returns(is_israel_stock, price_data)
|
|
|
|
volatility_momentum = calculate_volatility(weekly_returns.tail(156))
|
|
volatility_3_month = calculate_volatility(weekly_returns.tail(13))
|
|
volatility_12_month = calculate_volatility(weekly_returns.tail(52))
|
|
|
|
return [volatility_momentum, volatility_3_month, volatility_12_month]
|
|
|
|
|
|
def momentum_analysis(ticker, stock_price_data, fund_data):
|
|
logging.info(f"Performing {ticker} momentum factor analysis.")
|
|
|
|
currency_code = map_currency_code(extract_currency_code(fund_data))
|
|
|
|
# Get risk-free rate and rate change for the currency
|
|
riskfree_rate, riskfree_rate_change = get_riskfree_rate_and_change(currency_code)
|
|
|
|
# 2520 trading days for 5 years of historical calculation. Will eventually be needed to calculate beta.
|
|
stock_price_data_tail = stock_price_data.tail(2520)
|
|
|
|
# String objects need to be converted into datetime objects.
|
|
stock_price_data_tail = date_string_to_datetime(stock_price_data_tail)
|
|
|
|
lt_reversal = 0
|
|
|
|
# Tickers listed for less than 1 year do not have enough data for momentum trading.
|
|
if len(stock_price_data_tail) <= 147:
|
|
logging.info(f"{ticker} does not have enough timeseries data for momentum analysis. It has been marked to drop.")
|
|
return ["drop_ticker", riskfree_rate, riskfree_rate_change, "drop_ticker", "drop_ticker", 0, "drop_ticker", "drop_ticker"]
|
|
|
|
# Check if the stock is traded in Israel because why trade on different schedule
|
|
is_israel_stock = currency_code == 'ILS'
|
|
|
|
try:
|
|
volatility_data = volatility_analysis(ticker, is_israel_stock, stock_price_data_tail)
|
|
volatility_weekly, volatility_3_month, volatility_12_month = volatility_data
|
|
|
|
stock_price_data_list = stock_price_data_tail["Adjusted_close"].tolist()
|
|
|
|
while len(stock_price_data_list) < 1260:
|
|
stock_price_data_list.insert(0, stock_price_data_list[0])
|
|
|
|
momentum_12_month = (((stock_price_data_list[-21] / stock_price_data_list[-273]) - 1) - riskfree_rate) / volatility_weekly
|
|
momentum_6_month = (((stock_price_data_list[-21] / stock_price_data_list[-147]) - 1) - riskfree_rate) / volatility_weekly
|
|
momentum_returns = (momentum_12_month + momentum_6_month)/2
|
|
# Calculate long-term reversal momentum if there is enough data
|
|
if len(stock_price_data_tail) > 777:
|
|
lt_reversal = 1
|
|
momentum_60_month = (((stock_price_data_list[-273] / stock_price_data_list[-1260]) - 1) - riskfree_rate) / volatility_weekly * -1
|
|
else:
|
|
momentum_60_month = np.nan
|
|
|
|
except Exception as e:
|
|
logging.error(f"Error analyzing momentum for {ticker}: {e}")
|
|
return ["drop_ticker", riskfree_rate, riskfree_rate_change, "drop_ticker", "drop_ticker", "drop_ticker", "drop_ticker"]
|
|
|
|
return [momentum_returns, riskfree_rate, riskfree_rate_change, momentum_60_month, lt_reversal, volatility_3_month, volatility_12_month]
|
|
|
|
|
|
# Regional momentum for macroeconomics analysis.
|
|
def get_regional_momentum():
|
|
regional_data_table = pd.read_csv("regions_msci_codes.csv")
|
|
momentum_list = []
|
|
volatility_3m_list = []
|
|
volatility_12m_list = []
|
|
for ticker in regional_data_table["Ticker"].unique():
|
|
timeseries_data = get_timeseries_data(ticker, token)
|
|
momentum_data = momentum_analysis(ticker, timeseries_data, get_fundamental_data(ticker,token))
|
|
momentum_list.append(momentum_data[0])
|
|
volatility_3m_list.append(momentum_data[5])
|
|
volatility_12m_list.append(momentum_data[6])
|
|
regional_data_table["Momentum"] = [momentum_list[list(regional_data_table["Ticker"].unique()).index(ticker)] for ticker in regional_data_table["Ticker"]]
|
|
regional_data_table["Volatility 3M"] = [volatility_3m_list[list(regional_data_table["Ticker"].unique()).index(ticker)] for ticker in regional_data_table["Ticker"]]
|
|
regional_data_table["Volatility 12M"] = [volatility_12m_list[list(regional_data_table["Ticker"].unique()).index(ticker)] for ticker in regional_data_table["Ticker"]]
|
|
|
|
return regional_data_table
|
|
|
|
|
|
def size_analysis(ticker, fund_data):
|
|
logging.info(f"Performing {ticker} size factor analysis.")
|
|
|
|
# Market capitalization normalized for currency rates.
|
|
general_data = json.loads(fund_data).get("General", {})
|
|
fx_code = general_data.get("CurrencyCode", "USD")
|
|
# GBP is coded as GBX and ILS is coded as ILA for some reason.
|
|
fx_code = "GBP" if fx_code == "GBX" else fx_code
|
|
fx_code = "ILS" if fx_code == "ILA" else fx_code
|
|
market_cap = json.loads(fund_data).get("Highlights", {}).get("MarketCapitalization", "drop_ticker")
|
|
if market_cap == 0:
|
|
return "drop_ticker"
|
|
|
|
# Return "drop_ticker" if fx_code or market_cap are not available.
|
|
if fx_code == "drop_ticker" or market_cap == "drop_ticker" or market_cap == None:
|
|
return "drop_ticker"
|
|
|
|
# Get the exchange rate for the currency if it's not already in the list.
|
|
if fx_code not in forex_code_list:
|
|
forex_code_list.append(fx_code)
|
|
fx_rate = get_timeseries_data(fx_code + ".FOREX", token)["Adjusted_close"].tail(1)
|
|
forex_rate_list.append(fx_rate)
|
|
else:
|
|
fx_rate = forex_rate_list[forex_code_list.index(fx_code)]
|
|
|
|
# Calculate the market capitalization in the base currency.
|
|
market_cap = 1 / math.log(float(market_cap) / fx_rate)
|
|
|
|
return market_cap
|
|
|
|
|
|
def liquidity_analysis(ticker, stock_price_data, fund_data):
|
|
logging.info(f"Performing {ticker} liquidity factor analysis.")
|
|
|
|
stock_price_data_tail = stock_price_data.tail(252)
|
|
|
|
# String objects need to be converted into datetime objects.
|
|
stock_price_data_tail = date_string_to_datetime(stock_price_data_tail)
|
|
|
|
if len(stock_price_data_tail) < 252:
|
|
logging.info(f"{ticker} does not have enough timeseries data for liquidity analysis. It has been marked to drop.")
|
|
return ["drop_ticker", "drop_ticker", "drop_ticker"]
|
|
|
|
share_volume_list = stock_price_data_tail["Volume"].tolist()
|
|
shares_outstanding = json.loads(fund_data.decode("utf-8")).get("SharesStats", {}).get("SharesOutstanding", 0)
|
|
|
|
try:
|
|
monthly_liquidity = math.log(sum(share_volume_list[-21:]) / shares_outstanding)
|
|
quarterly_liquidity = math.log(sum(share_volume_list[-63:]) / shares_outstanding)
|
|
annual_liquidity = math.log(sum(share_volume_list[-252:]) / shares_outstanding)
|
|
|
|
except Exception as e:
|
|
logging.error(f"Error analyzing momentum for {ticker}: {e}")
|
|
return ["drop_ticker", "drop_ticker", "drop_ticker"]
|
|
|
|
return [monthly_liquidity, quarterly_liquidity, annual_liquidity]
|
|
|
|
|
|
def quality_analysis(ticker, fund_data):
|
|
logging.info(f"Performing {ticker} quality factor analysis.")
|
|
|
|
try:
|
|
financials = json.loads(fund_data.decode("utf-8"))["Financials"]
|
|
quarterly_balance_sheet = financials["Balance_Sheet"]["quarterly"]
|
|
quarterly_income_statement = financials["Income_Statement"]["quarterly"]
|
|
except:
|
|
logging.info(f"{ticker} has no financial data?")
|
|
return ["drop_ticker", "drop_ticker", "drop_ticker", "drop_ticker"]
|
|
|
|
try:
|
|
last_reported_quarter_balance = list(quarterly_balance_sheet)[0]
|
|
total_equity = float(quarterly_balance_sheet[last_reported_quarter_balance]["totalStockholderEquity"])
|
|
total_assets = float(quarterly_balance_sheet[last_reported_quarter_balance]["totalAssets"])
|
|
except TypeError:
|
|
logging.info("Possible non-quarterly reporting detected. Trying previous quarter.")
|
|
try:
|
|
last_reported_quarter_balance = list(quarterly_balance_sheet)[1]
|
|
total_equity = float(quarterly_balance_sheet[last_reported_quarter_balance]["totalStockholderEquity"])
|
|
total_assets = float(quarterly_balance_sheet[last_reported_quarter_balance]["totalAssets"])
|
|
except TypeError:
|
|
logging.info(f"{ticker} has bad balance sheet?")
|
|
return ["drop_ticker", "drop_ticker", "drop_ticker", "drop_ticker"]
|
|
except:
|
|
logging.info(ticker + " has bad balance sheet?")
|
|
return ["drop_ticker", "drop_ticker", "drop_ticker", "drop_ticker"]
|
|
|
|
# In previous versions of this script, we tried looking at cash flow reports if the income statement
|
|
# was not available. This was removed because we want to ignore the ticker if we cannot calculate
|
|
# revenue.
|
|
net_income = 0
|
|
total_revenue = 0
|
|
for quarter in range(4):
|
|
try:
|
|
last_reported_quarter_income = list(quarterly_income_statement)[quarter]
|
|
net_income += float(quarterly_income_statement[last_reported_quarter_income]["netIncome"])
|
|
total_revenue += float(quarterly_income_statement[last_reported_quarter_income]["totalRevenue"])
|
|
except (UnboundLocalError, TypeError, IndexError):
|
|
pass
|
|
|
|
# Return-on-Equity and Return-on-Assets, for calculating profitability.
|
|
try:
|
|
return_on_equity = net_income / total_equity
|
|
return_on_assets = net_income / total_assets
|
|
except (UnboundLocalError, TypeError, ZeroDivisionError):
|
|
try:
|
|
return_on_equity = json.loads(fund_data.decode("utf-8"))["Highlights"]["ReturnOnEquityTTM"]
|
|
return_on_assets = json.loads(fund_data.decode("utf-8"))["Highlights"]["ReturnOnAssetsTTM"]
|
|
except:
|
|
logging.info(f"{ticker} Return on Equity or Return on Assets data not found. Ticker marked for drop.")
|
|
return_on_equity = "drop_ticker"
|
|
return_on_assets = "drop_ticker"
|
|
|
|
# Equity-to-Debt ratio, for calculating leverage.
|
|
try:
|
|
total_debt = quarterly_balance_sheet[last_reported_quarter_balance]["totalLiab"]
|
|
equity_to_debt = float(total_equity) / float(total_debt)
|
|
except (UnboundLocalError, TypeError, ZeroDivisionError):
|
|
logging.info(ticker + " Debt to Equity data not found. Ticker marked for drop.")
|
|
equity_to_debt = "drop_ticker"
|
|
# This needs to be moved outside of this function.
|
|
logging.info("Dumping json data for inspection.")
|
|
if not os.path.exists("debug"):
|
|
os.makedirs("debug")
|
|
with open("debug/" + ticker + "." + current_date.strftime("%Y%m%d") + ".json", 'w') as dumpfile:
|
|
json.dump(json.loads(fund_data.decode("utf-8")), dumpfile)
|
|
|
|
# Earnings quality.
|
|
try:
|
|
earnings_quality = net_income / total_revenue
|
|
except (UnboundLocalError, TypeError, ZeroDivisionError):
|
|
logging.info(f"{ticker} earnings quality could not be resolved. Ticker marked for drop.")
|
|
earnings_quality = "drop_ticker"
|
|
|
|
return [return_on_equity, equity_to_debt, return_on_assets, earnings_quality]
|
|
|
|
|
|
def growth_slope(starting_value, ending_value):
|
|
slope = (starting_value - ending_value) / abs(starting_value)
|
|
return slope
|
|
|
|
|
|
def earnings_analysis(ticker, fund_data):
|
|
logging.info(f"Performing {ticker} earnings analysis.")
|
|
|
|
# EPS variability.
|
|
try:
|
|
earnings_history = json.loads(fund_data.decode("utf-8"))["Earnings"]["History"]
|
|
shift_one_year = dt.timedelta(days = 365)
|
|
current_observation = current_date - shift_one_year
|
|
eps_sums = []
|
|
eps_growth = []
|
|
for earnings_period in range(0, len(earnings_history)):
|
|
date_object = dt.datetime.strptime(earnings_history[list(earnings_history)[earnings_period]]["reportDate"], "%Y-%m-%d")
|
|
|
|
eps_actual = earnings_history[list(earnings_history)[earnings_period]]["epsActual"]
|
|
eps_estimate = earnings_history[list(earnings_history)[earnings_period]]["epsEstimate"]
|
|
|
|
# Use eps_estimate if eps_actual is not available.
|
|
if eps_actual == None:
|
|
eps_actual = eps_estimate
|
|
if eps_estimate == None:
|
|
eps_actual = 0
|
|
|
|
if date_object > current_observation and date_object < current_date and len(eps_sums) < 6:
|
|
if len(eps_sums) == 0:
|
|
eps_sums.append(eps_actual)
|
|
elif len(eps_sums) > 0:
|
|
eps_sums[-1] += eps_actual
|
|
elif date_object < current_observation and len(eps_sums) < 5:
|
|
current_observation -= shift_one_year
|
|
eps_sums.append(eps_actual)
|
|
|
|
for i in range(0, len(eps_sums[:5]) - 1):
|
|
if eps_sums[i + 1] > 0:
|
|
eps_growth.append((eps_sums[i] - eps_sums[i + 1]) / eps_sums[i + 1])
|
|
elif eps_sums[i + 1] < 0:
|
|
eps_growth.append(-(eps_sums[i] - eps_sums[i + 1]) / eps_sums[i + 1])
|
|
|
|
earnings_variability = statistics.pstdev(eps_growth) if eps_growth else "drop_ticker"
|
|
|
|
# Growth factor. Wrote as part of quality analysis since the code was already written as a part of
|
|
# calculating EPS variability.
|
|
eps_growth_trend = growth_slope(eps_sums[0], sum(eps_sums[0:5]) / 5) if eps_sums else "drop_ticker"
|
|
|
|
except Exception as e:
|
|
logging.error(f"Error occurred while analyzing {ticker}'s earnings: {str(e)}")
|
|
earnings_variability = "drop_ticker"
|
|
eps_growth_trend = "drop_ticker"
|
|
|
|
return [earnings_variability, eps_growth_trend]
|
|
|
|
|
|
def earnings_report_date(ticker, fund_data):
|
|
logging.info(f"Getting {ticker} next earnings report date.")
|
|
|
|
shift_one_quarter = dt.timedelta(days = 92)
|
|
target_date_range = current_date + shift_one_quarter
|
|
report_date = ""
|
|
try:
|
|
earnings_history = json.loads(fund_data.decode("utf-8"))["Earnings"]["History"]
|
|
except KeyError:
|
|
return str(report_date)
|
|
|
|
for earnings_period in range(0, len(earnings_history)):
|
|
date_object = dt.datetime.strptime(earnings_history[list(earnings_history)[earnings_period]]["reportDate"], "%Y-%m-%d")
|
|
if date_object < target_date_range and date_object > current_date:
|
|
report_date = date_object.date()
|
|
break
|
|
|
|
return str(report_date)
|
|
|
|
|
|
def asset_growth_analysis(ticker, fund_data):
|
|
logging.info(f"Performing {ticker} asset growth analysis.")
|
|
|
|
# Investment quality
|
|
try:
|
|
asset_history = json.loads(fund_data.decode("utf-8"))["Financials"]["Balance_Sheet"]["quarterly"]
|
|
shift_one_year = dt.timedelta(days = 365)
|
|
current_observation = current_date - shift_one_year
|
|
asset_sums = []
|
|
# We only need the current quarter annually.
|
|
quarter_index = 0
|
|
for earnings_period in range(0, len(asset_history)):
|
|
date_object = dt.datetime.strptime(asset_history[list(asset_history)[earnings_period]]["date"], "%Y-%m-%d")
|
|
total_assets = asset_history[list(asset_history)[earnings_period]]["totalAssets"]
|
|
|
|
if date_object > current_observation and date_object < current_date and len(asset_sums) < 5:
|
|
if quarter_index == 0:
|
|
# Some regions only have semi-annual reporting, this is an attempt to offset the current quarter
|
|
# to the next.
|
|
try:
|
|
asset_sums.append(float(total_assets))
|
|
logging.debug(total_assets)
|
|
except:
|
|
pass
|
|
quarter_index += 1
|
|
elif quarter_index != 0 :
|
|
quarter_index += 1
|
|
elif date_object < current_observation and len(asset_sums) < 5:
|
|
current_observation -= shift_one_year
|
|
try:
|
|
asset_sums.append(float(total_assets))
|
|
logging.debug(total_assets)
|
|
quarter_index = 1
|
|
except:
|
|
pass
|
|
|
|
# Copied from quality
|
|
asset_growth_trend = growth_slope(asset_sums[0], sum(asset_sums[0:5]) / 5)
|
|
|
|
except:
|
|
logging.info(f"{ticker} asset growth could not be calculated. Ticker marked for drop.")
|
|
asset_growth_trend = "drop_ticker"
|
|
|
|
return [asset_growth_trend]
|
|
|
|
|
|
def value_analysis(ticker, eod_data, fund_data):
|
|
logging.info(f"Performing {ticker} value factor analysis.")
|
|
|
|
earnings_yield = bookvalue = "drop_ticker"
|
|
try:
|
|
eod_last_close = eod_data["Adjusted_close"].iloc[-1]
|
|
|
|
highlights = json.loads(fund_data)["Highlights"]
|
|
if eod_last_close == 0:
|
|
raise ZeroDivisionError
|
|
earnings_yield = highlights["EarningsShare"] / eod_last_close
|
|
bookvalue = highlights["BookValue"] / eod_last_close
|
|
except ZeroDivisionError:
|
|
pass
|
|
except:
|
|
logging.exception("Error in value_analysis")
|
|
|
|
return [earnings_yield, bookvalue]
|
|
|
|
|
|
# Yield factor
|
|
def dividend_analysis(ticker, div_data, eod_data, fund_data, index_fund_data):
|
|
logging.info(f"Performing {ticker} dividend analysis.")
|
|
|
|
json_div = json.loads(div_data.decode("utf-8"))
|
|
shift_one_year = dt.timedelta(days = 365)
|
|
current_observation = current_date - shift_one_year
|
|
dividend_sums = []
|
|
|
|
# 5Y DPS
|
|
logging.debug("5Y DPS")
|
|
if len(json_div) > 0:
|
|
dividend_sum = 0
|
|
for div_period in range(1, len(json_div)):
|
|
date_object = dt.datetime.strptime(json_div[-div_period]["date"], "%Y-%m-%d")
|
|
if date_object > current_observation:
|
|
dividend_sum += json_div[-div_period]["value"]
|
|
elif date_object < current_observation:
|
|
dividend_sums.append(dividend_sum)
|
|
dividend_sum = 0
|
|
current_observation -= shift_one_year
|
|
dividend_sums.append(dividend_sum)
|
|
|
|
# dividend_sums is ordered oldest to most recent
|
|
logging.debug(dividend_sums)
|
|
|
|
try:
|
|
div_yield = dividend_sums[0] / eod_data["Adjusted_close"].iloc[-1]
|
|
except:
|
|
div_yield = 0
|
|
|
|
try:
|
|
payout_ratio = dividend_sums[0] / json.loads(fund_data)["Highlights"]["EarningsShare"]
|
|
except:
|
|
payout_ratio = 0
|
|
|
|
# 5Y DPS Growth
|
|
if len(dividend_sums) >= 5:
|
|
try:
|
|
div_growth_5years = growth_slope(dividend_sums[0], sum(dividend_sums[:5]) / 5)
|
|
except:
|
|
div_growth_5years = 0
|
|
else:
|
|
div_growth_5years = 0
|
|
|
|
# Yield above parent
|
|
above_parent = div_yield - float(json.loads(index_fund_data.decode("utf-8"))["ETF_Data"]["Yield"]) / 100 * 1.3
|
|
|
|
return [div_yield, payout_ratio, div_growth_5years, above_parent]
|
|
|
|
|
|
def month_index_lookup(date_object):
|
|
if date_object.month == 12:
|
|
return 1
|
|
elif date_object.month != 12:
|
|
return date_object.month + 1
|
|
else:
|
|
return np.nan
|
|
|
|
|
|
def max_check_drop(value):
|
|
try:
|
|
return max(value)
|
|
except:
|
|
return "drop_ticker"
|
|
|
|
|
|
# Run all our factor analysis at once.
|
|
def factor_analysis():
|
|
for ticker in master_ticker_list:
|
|
logging.info(f"Performing factor analysis on {ticker}.")
|
|
fund_data = get_fundamental_data(ticker, token)
|
|
eod_data = get_timeseries_data(ticker, token)
|
|
div_data = get_dividend_data(ticker, token)
|
|
|
|
# Fix for REITs and Trust units in Canada is causing bad data to be gathered
|
|
try:
|
|
ticker_code = json.loads(fund_data.decode("utf-8"))["General"]["Code"]
|
|
except:
|
|
pass
|
|
if ticker_code not in ticker and ".TO" in ticker:
|
|
master_ticker_list[master_ticker_list.index(ticker)] = ticker_code + ".TO"
|
|
|
|
general_data_var = get_general_data(ticker, fund_data)
|
|
momentum_data_var = momentum_analysis(ticker, eod_data, fund_data)
|
|
size_data_var = size_analysis(ticker, fund_data)
|
|
quality_data_var = quality_analysis(ticker, fund_data)
|
|
earnings_data_var = earnings_analysis(ticker, fund_data)
|
|
asset_growth_data_var = asset_growth_analysis(ticker, fund_data)
|
|
value_data_var = value_analysis(ticker, eod_data, fund_data)
|
|
dividend_data_var = dividend_analysis(ticker, div_data, eod_data, fund_data, index_fund_data)
|
|
liquidity_data_var = liquidity_analysis(ticker, eod_data, fund_data)
|
|
|
|
# General Data
|
|
name_list.append(general_data_var[0])
|
|
eod_list.append(price_last_close(ticker, eod_data))
|
|
country_list.append(general_data_var[1])
|
|
sector_list.append(general_data_var[2])
|
|
industry_list.append(general_data_var[3])
|
|
earnings_date_list.append(earnings_report_date(ticker, fund_data))
|
|
|
|
# Momentum
|
|
momentum_list.append(momentum_data_var[0])
|
|
|
|
size_list.append(size_data_var)
|
|
|
|
# Quality
|
|
roe_list.append(quality_data_var[0])
|
|
etd_list.append(quality_data_var[1])
|
|
roa_list.append(quality_data_var[2])
|
|
equal_list.append(quality_data_var[3])
|
|
# Earnings
|
|
evar_list.append(earnings_data_var[0])
|
|
# Asset Growth
|
|
assgro_list.append(asset_growth_data_var[0])
|
|
|
|
# Value
|
|
eyield_list.append(value_data_var[0])
|
|
bv_list.append(value_data_var[1])
|
|
|
|
# Volatility
|
|
mo_3_vol_list.append(momentum_data_var[5])
|
|
mo_12_vol_list.append(momentum_data_var[6])
|
|
max_vol_list.append(max_check_drop([momentum_data_var[5], momentum_data_var[6]]))
|
|
|
|
# Yield
|
|
div_yield_list.append(dividend_data_var[0])
|
|
payout_list.append(dividend_data_var[1])
|
|
div_growth5_list.append(dividend_data_var[2])
|
|
div_above_index_list.append(dividend_data_var[3])
|
|
|
|
growth5_list.append(earnings_data_var[1])
|
|
|
|
liquid_21_list.append(liquidity_data_var[0])
|
|
liquid_63_list.append(liquidity_data_var[1])
|
|
liquid_252_list.append(liquidity_data_var[2])
|
|
|
|
try:
|
|
region_mom_list.append(list(region_momentum_table["Momentum"])[list(region_momentum_table["Country"]).index(general_data_var[1])])
|
|
region_rfr_list.append(momentum_data_var[1])
|
|
region_rfr_change_list.append(momentum_data_var[2])
|
|
region_3m_vol_list.append(list(region_momentum_table["Volatility 3M"])[list(region_momentum_table["Country"]).index(general_data_var[1])])
|
|
region_12m_vol_list.append(list(region_momentum_table["Volatility 12M"])[list(region_momentum_table["Country"]).index(general_data_var[1])])
|
|
except ValueError:
|
|
region_mom_list.append(np.nan)
|
|
region_rfr_list.append(np.nan)
|
|
region_rfr_change_list.append(np.nan)
|
|
region_3m_vol_list.append(np.nan)
|
|
region_12m_vol_list.append(np.nan)
|
|
|
|
# Long-term Reversal
|
|
lt_reversal_list.append(momentum_data_var[3])
|
|
lt_has_history.append(momentum_data_var[4])
|
|
|
|
|
|
# Compile data for reading
|
|
def compile_data():
|
|
logging.info("Compiling data...")
|
|
|
|
data_table = pd.DataFrame()
|
|
data_table["Ticker"] = master_ticker_list
|
|
data_table["Name"] = name_list
|
|
data_table["Price"] = eod_list
|
|
data_table["Dividend Yield"] = div_yield_list
|
|
data_table["Country Name"] = country_list
|
|
data_table["Sector"] = sector_list
|
|
data_table["Industry"] = industry_list
|
|
data_table["Earnings Report"] = earnings_date_list
|
|
|
|
data_table["Momentum fct"] = momentum_list
|
|
|
|
data_table["Size fct"] = size_list
|
|
|
|
data_table["Liquidity 1M fct"] = liquid_21_list
|
|
data_table["Liquidity 3M fct"] = liquid_63_list
|
|
data_table["Liquidity 12M fct"] = liquid_252_list
|
|
|
|
data_table["Return-on-Assets fct"] = roa_list
|
|
data_table["Return-on-Equity fct"] = roe_list
|
|
data_table["Equity-to-Debt fct"] = etd_list
|
|
data_table["Earnings Vol fct"] = evar_list
|
|
data_table["Asset Growth fct"] = assgro_list
|
|
data_table["Earnings Quality fct"] = equal_list
|
|
|
|
data_table["Earnings Yield fct"] = eyield_list
|
|
data_table["Book Value fct"] = bv_list
|
|
|
|
data_table["3M Vol fct"] = mo_3_vol_list
|
|
data_table["12M Vol fct"] = mo_12_vol_list
|
|
data_table["Max Vol"] = max_vol_list
|
|
|
|
data_table["Payout Ratio"] = payout_list
|
|
data_table["Dividend Growth 5Y"] = div_growth5_list
|
|
data_table["% Above Index"] = div_above_index_list
|
|
|
|
data_table["EPS Growth fct"] = growth5_list
|
|
|
|
data_table["LT Reversal fct"] = lt_reversal_list
|
|
data_table["LT_has_history"] = lt_has_history
|
|
|
|
data_table["Regional Momentum"] = region_mom_list
|
|
data_table["Regional Riskfree Rate"] = region_rfr_list
|
|
data_table["Regional Riskfree Rate Change"] = region_rfr_change_list
|
|
data_table["Regional Volatility 3M"] = region_3m_vol_list
|
|
data_table["Regional Volatility 12M"] = region_12m_vol_list
|
|
|
|
return data_table
|
|
|
|
|
|
# We need a list of rejected tickers for full analysis and checking of false negatives.
|
|
def output_rejected_tickers():
|
|
logging.info("Outputting rejected tickers. These can be found in rejected_tickers.txt.")
|
|
|
|
rejected_data_table = fundamental_data_table[(fundamental_data_table.iloc[:, 1:].isin(["drop_ticker"]).any(axis = 1))]
|
|
rejected_tickers = rejected_data_table["Ticker"]
|
|
with open('output/rejected_tickers.txt', 'w') as f:
|
|
for ticker in list(rejected_tickers):
|
|
f.write("%s\n" % ticker)
|
|
|
|
|
|
def winsorize_scores(scores):
|
|
upper_bound = 3.0
|
|
lower_bound = -3.0
|
|
|
|
winsorized_scores = [score if lower_bound <= score <= upper_bound else upper_bound if score > upper_bound else lower_bound for score in scores]
|
|
|
|
return winsorized_scores
|
|
|
|
|
|
# There are several sectors that are not labled correctly from the data source.
|
|
def fix_sectors(data_table):
|
|
proper_sectors = ["Basic Materials",
|
|
"Communication Services",
|
|
"Consumer Cyclical",
|
|
"Consumer Defensive",
|
|
"Energy",
|
|
"Financial Services",
|
|
"Healthcare",
|
|
"Industrials",
|
|
"Real Estate",
|
|
"Technology",
|
|
"Utilities"]
|
|
new_data_table = data_table[data_table["Sector"].isin(proper_sectors)]
|
|
|
|
return new_data_table
|
|
|
|
|
|
# These factors do not need to be normalized, simply winsorized.
|
|
def standardize_simple_scores(data_table):
|
|
logging.info("Standardizing simple scores...")
|
|
simple_factors = ["Momentum fct",
|
|
"Size fct",
|
|
"Liquidity 1M fct",
|
|
"Liquidity 3M fct",
|
|
"Liquidity 12M fct",
|
|
"LT Reversal fct",
|
|
"Max Vol"]
|
|
|
|
scores = [(data_table[factor].astype(float) - np.nanmean(data_table[factor].astype(float))) / np.nanstd(data_table[factor].astype(float)) for factor in simple_factors]
|
|
winsorized_scores = [winsorize_scores(score) for score in scores]
|
|
|
|
for i, factor in enumerate(simple_factors):
|
|
data_table[factor[:-3] + "Z-Scores"] = winsorized_scores[i]
|
|
|
|
return data_table
|
|
|
|
|
|
# These factors need to be standardized relative to their industry sector.
|
|
def standardize_sector_relative_scores(data_table):
|
|
logging.info("Standardizing sector relative scores...")
|
|
|
|
variables_to_sector_norm = ["Return-on-Assets fct",
|
|
"Return-on-Equity fct",
|
|
"Equity-to-Debt fct",
|
|
"Earnings Vol fct",
|
|
"Asset Growth fct",
|
|
"Earnings Quality fct",
|
|
"Earnings Yield fct",
|
|
"Book Value fct",
|
|
"EPS Growth fct"]
|
|
|
|
sector_to_normalize = []
|
|
for sector in set(data_table["Sector"]):
|
|
sector_to_normalize.append(data_table[data_table["Sector"] == sector])
|
|
|
|
for sector_index in sector_to_normalize:
|
|
for column_item in sector_index.columns:
|
|
if column_item in variables_to_sector_norm:
|
|
stats = sector_index[column_item].astype(float)
|
|
score = (stats - np.nanmean(stats)) / np.nanstd(stats)
|
|
sector_index[column_item[:-3] + "Z-Scores"] = winsorize_scores(list(score))
|
|
|
|
data_table = pd.concat(sector_to_normalize)
|
|
|
|
return data_table
|
|
|
|
|
|
# For beta calculation? Eventually?
|
|
"""
|
|
# These factors need to be standardized relative to their regional markets.
|
|
def standardize_index_relative_scores(data_table):
|
|
logging.info("Standardizing index relative scores...")
|
|
|
|
volatility_to_norm = ["Daily Vol fct", "Weekly Vol fct"]
|
|
parent_index = get_parent_index()
|
|
if parent_index is None:
|
|
return data_table
|
|
parent_index_timeseries = get_timeseries_data(parent_index, token)
|
|
parent_index_vol = volatility_analysis(parent_index, parent_index_timeseries)
|
|
for column_item in volatility_to_norm:
|
|
stats = data_table[column_item].astype(float) - parent_index_vol[volatility_to_norm.index(column_item)]
|
|
data_table[column_item[:-3] + "Z-Scores"] = winsorize_scores(((stats - np.nanmean(stats))/ np.nanstd(stats)) * -1)
|
|
|
|
return data_table
|
|
"""
|
|
|
|
# Logic for normalizing dividend factors to be implemented in the future.
|
|
# Refer to the design document on why this featured is deferred indefinetly.
|
|
|
|
|
|
def multifactor_scores(data_table):
|
|
|
|
data_table["Liquidity Z-Scores"] = (data_table["Liquidity 1M Z-Scores"] + data_table["Liquidity 3M Z-Scores"] + data_table["Liquidity 12M Z-Scores"]) / 3
|
|
data_table["Profitability Z-Scores"] = (data_table["Return-on-Assets Z-Scores"] + data_table["Return-on-Equity Z-Scores"]) / 2
|
|
data_table["Quality"] = (data_table["Return-on-Equity Z-Scores"] + data_table["Equity-to-Debt Z-Scores"] + data_table["Earnings Vol Z-Scores"]) / 3
|
|
data_table["Quality DFM"] = (data_table["Profitability Z-Scores"] + data_table["Equity-to-Debt Z-Scores"] + data_table["Earnings Vol Z-Scores"] + data_table["Asset Growth Z-Scores"] + data_table["Earnings Quality Z-Scores"]) / 5
|
|
data_table["Quality FaCS"] = ((data_table["Equity-to-Debt Z-Scores"] * 0.125) + (data_table["Asset Growth Z-Scores"] * 0.25) + (data_table["Earnings Vol Z-Scores"] * 0.125) + (data_table["Earnings Quality Z-Scores"] * 0.25) + (data_table["Profitability Z-Scores"] * 0.25))
|
|
data_table["Value DFM"] = ((data_table["Earnings Yield Z-Scores"] * 2) + data_table["Book Value Z-Scores"]) / 3
|
|
data_table["Value Enhanced"] = (data_table["Earnings Yield Z-Scores"] + data_table["Book Value Z-Scores"] + data_table["EPS Growth Z-Scores"]) / 3
|
|
# This is a simple way to scale value scores based on whether long-term reversal factors are evident in the security or not.
|
|
# If long-term reversal factor cannot be analyise, we simply use classic value factor calculations. The scaling allows the script
|
|
# to compute value without a skew for or against securities with a reversal score.
|
|
data_table["Value FaCS"] = ((data_table["Earnings Yield Z-Scores"] * 0.6) + (data_table["Book Value Z-Scores"] * 0.3) + (data_table["LT Reversal Z-Scores"].fillna(0) * 0.1)) / (0.9 + data_table["LT_has_history"] * 0.1)
|
|
# Weights defined by MSCI Multifactor Methodology but with quality tweaked to calculate quality factor as outlined
|
|
# in the MSCI Quality Indexes Methodology.
|
|
data_table["QVMS"] = (data_table["Quality DFM"] + data_table["Value DFM"] + data_table["Momentum Z-Scores"] + data_table["Size Z-Scores"]) / 4
|
|
# Same as above but with Value tweaked to calculate Value as outlined in the MSCI Enhanced Value Indexes Methodology.
|
|
# This can also be used in place of GARP as this introduces Growth factor into calculation but with a low weight.
|
|
data_table["GARP"] = (data_table["Size Z-Scores"] + data_table["Quality"] + data_table["Value Enhanced"] + data_table["Momentum Z-Scores"]) / 4
|
|
# Constructed from MSCI FaCS. Yield and Volatility excluded because their components are a part of other listed factors used.
|
|
data_table["FaCS"] = (data_table["Value FaCS"] + data_table["Size Z-Scores"] + data_table["Momentum Z-Scores"] + data_table["Quality FaCS"] + data_table["EPS Growth Z-Scores"]) / 5
|
|
|
|
cols = data_table.columns.tolist()
|
|
important_columns = ["Momentum Z-Scores",
|
|
"Size Z-Scores",
|
|
"Quality",
|
|
"Quality DFM",
|
|
"Quality FaCS",
|
|
"Value DFM",
|
|
"Value Enhanced",
|
|
"Value FaCS",
|
|
"QVMS",
|
|
"GARP",
|
|
"FaCS"]
|
|
cols = [column_name for column_name in cols if column_name not in important_columns]
|
|
cols.extend(important_columns)
|
|
data_table = data_table[cols]
|
|
|
|
return data_table
|
|
|
|
|
|
dev_mode = is_dev_mode()
|
|
|
|
# API key for authentication
|
|
licenseFile = open("licenseFile.key", "r")
|
|
api_key = licenseFile.read()
|
|
token = api_key
|
|
|
|
logging.info("Grabbing indicies data.")
|
|
|
|
master_ticker_list = get_ticker_list(get_indices(), token)
|
|
index_fund_data = get_fundamental_data(get_parent_index(), token)
|
|
riskfree_table = get_riskfree_rate()
|
|
region_momentum_table = get_regional_momentum()
|
|
|
|
factor_analysis()
|
|
fundamental_data_table = compile_data()
|
|
output_rejected_tickers()
|
|
fundamental_data_table.to_csv("output/" + current_date.strftime("%Y%m%d") + "dump.csv", index = False, header = True)
|
|
#fundamental_data_table = pd.read_csv('20221107dump.csv')
|
|
fundamental_data_table = fix_sectors(fundamental_data_table)
|
|
|
|
# THE SQUIGGLY IS NOT A TYPO
|
|
fundamental_data_table = fundamental_data_table[~fundamental_data_table.isin(["drop_ticker"]).any(axis=1)]
|
|
fundamental_data_table = fundamental_data_table.reset_index(drop=True)
|
|
fundamental_data_table = standardize_sector_relative_scores(fundamental_data_table)
|
|
#fundamental_data_table = standardize_index_relative_scores(fundamental_data_table)
|
|
|
|
# These are ordered this way specifically to make it easier to read the output spreadsheet.
|
|
fundamental_data_table = standardize_simple_scores(fundamental_data_table)
|
|
fundamental_data_table = multifactor_scores(fundamental_data_table)
|
|
|
|
fundamental_data_table.to_csv("output/" + current_date.strftime("%Y%m%d") + ".csv", index = False, header = True)
|
|
|
|
logging.info("[" + str(dt.datetime.now()) + "] " + "Script duration " + str((dt.datetime.now() - script_start_time)))
|
|
|