Skip to content

Commit

Permalink
linting, beautification, small improvements. Pending further linting …
Browse files Browse the repository at this point in the history
…and testing.
  • Loading branch information
MauererM committed Dec 15, 2023
1 parent 2c14dcd commit dda9163
Show file tree
Hide file tree
Showing 9 changed files with 32 additions and 34 deletions.
2 changes: 1 addition & 1 deletion profit_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ def main():

config = ProfitConfig()

# Add the parsed data:
# Add the parsed data to the main config-class:
config.DAYS_ANALYSIS_ARGPARSE = args.days
config.INTERACTIVE_MODE = args.interactive

Expand Down
12 changes: 6 additions & 6 deletions profit_src/dataprovider/yahoofinance/yahoofinance.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,11 +82,11 @@ def retrieve_forex_data(self, sym_a, sym_b, startdate, stopdate):
req = urllib.request.Request(url, headers=self.useragent)
try:
# There is no need to enter the cookie here, as it is automatically handled by opener
f = urllib.request.urlopen(req, timeout=6)
with urllib.request.urlopen(req, timeout=6) as f:
strlines = f.read().decode('utf-8')
except:
return None

strlines = f.read().decode('utf-8')
if len(strlines) < 2:
return None

Expand Down Expand Up @@ -137,11 +137,11 @@ def retrieve_stock_data(self, symbol, startdate, stopdate, symbol_exchange=None)

try:
# There is no need to enter the cookie here, as it is automatically handled by opener
f = urllib.request.urlopen(req, timeout=6)
with urllib.request.urlopen(req, timeout=6) as f:
strlines = f.read().decode('utf-8')
except:
return None

strlines = f.read().decode('utf-8')
if len(strlines) < 2:
return None

Expand All @@ -161,8 +161,8 @@ def retrieve_stock_data(self, symbol, startdate, stopdate, symbol_exchange=None)
def __obtain_cookie_crumb(self):
self.cooker.cookiejar.clear()
req = urllib.request.Request('http://finance.yahoo.com/quote/TSLA', headers=self.useragent)
f = urllib.request.urlopen(req, timeout=6)
strlines = f.read().decode('utf-8')
with urllib.request.urlopen(req, timeout=6) as f:
strlines = f.read().decode('utf-8')

# Find the crumb in the response. Code from Stackoverflow.
cs = strlines.find('CrumbStore')
Expand Down
9 changes: 4 additions & 5 deletions profit_src/dateoperations.py
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,7 @@ def extend_data_past(datelist, vallist, begin_date, analyzer, zero_padding):

# Create new lists, before the existing list. Then join the lists.
auxdates = create_datelist(begin_date, datelist[0], analyzer)
del auxdates[-1] # Avoid the duplicate date
del auxdates[-1] # Avoid the duplicate date
if zero_padding is True:
auxvals = [0.0] * len(auxdates)
else:
Expand Down Expand Up @@ -334,8 +334,7 @@ def check_date_order(datelist, analyzer, allow_ident_days=False):
# Don't begin with the first element with the iteration:
if allow_ident_days:
return all(curr_date >= prev_date for prev_date, curr_date in zip(datelist_dt, datelist_dt[1:]))
else:
return all(curr_date > prev_date for prev_date, curr_date in zip(datelist_dt, datelist_dt[1:]))
return all(curr_date > prev_date for prev_date, curr_date in zip(datelist_dt, datelist_dt[1:]))


def find_holes_in_dates(datelist, analyzer):
Expand Down Expand Up @@ -367,9 +366,9 @@ def check_dates_consecutive(datelist, analyzer):
if len(datelist) == 1:
return True
datelist = [analyzer.str2datetime(x) for x in datelist]
for i in range(len(datelist)-1):
for i in range(len(datelist) - 1):
nextday = datelist[i] + datetime.timedelta(days=1)
if datelist[i+1] != nextday:
if datelist[i + 1] != nextday:
return False
return True

Expand Down
2 changes: 1 addition & 1 deletion profit_src/helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,7 @@ def is_near_zero(val, t):

return any(is_near_zero(val, tol) for val in trimmed)


def is_valid_float(input_str):
"""Checks if a string is a valid floating point number, or not"""
return re.match(r'^[+-]?(\d+(\.\d*)?|\.\d+)$', input_str) is not None

6 changes: 3 additions & 3 deletions profit_src/investment.py
Original file line number Diff line number Diff line change
Expand Up @@ -416,7 +416,8 @@ def set_analysis_data(self, date_start, date_stop):
than recorded data.
:param date_stop: String of a date that designates the stop-date. Cannot be in the future.
"""
print(f"\n{self.symbol} ({self.filename.name}):") # Show in the terminal what's going on/which investment is getting processed
print(
f"\n{self.symbol} ({self.filename.name}):") # Show in the terminal what's going on/which investment is getting processed

# Extrapolate or crop the data:
# The balance is extrapolated with zeroes into the past, and with the last known values into the future,
Expand Down Expand Up @@ -618,7 +619,7 @@ def __handle_interactive_mode(self):
if ret is None:
return True
self.__append_file_with_newest_price(ret)
return False # Changes have been made to the investment-file.
return False # Changes have been made to the investment-file.

def __append_file_with_newest_price(self, price):
"""The user wants to update the file with a new balance.
Expand Down Expand Up @@ -653,7 +654,6 @@ def __ask_user_for_update_transaction(self):
except ValueError:
raise RuntimeError("Could not convert the float. Is the float-checking-function not working?")


def get_trans_datelist(self):
"""Return the list of transaction-dates (as strings)"""
return list(self.datelist)
Expand Down
27 changes: 13 additions & 14 deletions profit_src/parsing.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,6 @@ def clean_asset_whitespaces(filepath, transactions_string, eof_string, delimiter
else: # EOF not reached/found in above's for-loop
raise RuntimeError(f"Did not find the eof-string when cleaning white spaces in file {filepath}")
files.write_file_lines(filepath, lines_formatted, overwrite=True) # Write back to disk
return None


class ParsingConfig:
Expand Down Expand Up @@ -178,9 +177,9 @@ def __init__(self, parsing_config, profit_config, filepath, analyzer):
self.lines = read_strip_file_lines(self.filepath)

def clean_account_whitespaces(self):
return clean_asset_whitespaces(self.filepath, self.parsing_conf.STRING_TRANSACTIONS,
self.parsing_conf.STRING_EOF, self.profit_conf.DELIMITER,
self.parsing_conf.COLUMN_WIDTHS_ACCOUNTS)
clean_asset_whitespaces(self.filepath, self.parsing_conf.STRING_TRANSACTIONS,
self.parsing_conf.STRING_EOF, self.profit_conf.DELIMITER,
self.parsing_conf.COLUMN_WIDTHS_ACCOUNTS)

def parse_account_file(self, skip_interactive_mode=False):
"""Parses an account-file.
Expand Down Expand Up @@ -208,14 +207,14 @@ def parse_account_file(self, skip_interactive_mode=False):

if self.profit_conf.INTERACTIVE_MODE is False or skip_interactive_mode is True:
return self.__create_account_instance()
else: # Interactive mode: Display what the current account is.
print(f"\nAccount: {self.filepath.name} ({self.account_dict[self.parsing_conf.STRING_ID]}, "
f"{self.account_dict[self.parsing_conf.STRING_CURRENCY]})")
ret = self.__ask_user_for_updated_balance()
if ret is None: # No balance-update needed
return self.__create_account_instance()
self.__append_file_with_newest_balance(ret) # Update the file and local data
# Else: Interactive mode: Display what the current account is.
print(f"\nAccount: {self.filepath.name} ({self.account_dict[self.parsing_conf.STRING_ID]}, "
f"{self.account_dict[self.parsing_conf.STRING_CURRENCY]})")
ret = self.__ask_user_for_updated_balance()
if ret is None: # No balance-update needed
return self.__create_account_instance()
self.__append_file_with_newest_balance(ret) # Update the file and local data
return self.__create_account_instance()

def __append_file_with_newest_balance(self, balance):
"""The user wants to update the file with a new balance.
Expand Down Expand Up @@ -418,9 +417,9 @@ def __init__(self, parsing_config, profit_config, filepath, analyzer, dataprovid
self.lines = read_strip_file_lines(self.filepath)

def clean_investment_whitespaces(self):
return clean_asset_whitespaces(self.filepath, self.parsing_conf.STRING_TRANSACTIONS,
self.parsing_conf.STRING_EOF, self.profit_conf.DELIMITER,
self.parsing_conf.COLUMN_WIDTHS_INVESTMENTS)
clean_asset_whitespaces(self.filepath, self.parsing_conf.STRING_TRANSACTIONS,
self.parsing_conf.STRING_EOF, self.profit_conf.DELIMITER,
self.parsing_conf.COLUMN_WIDTHS_INVESTMENTS)

def parse_investment_file(self):
"""Parses an investment-file.
Expand Down
2 changes: 1 addition & 1 deletion profit_src/profit.py
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,7 @@ def main(config):
filepath = investment.get_filepath()
investment_file = parsing.InvestmentFile(parsing_config, config, filepath, analyzer, provider, storage)
investment = investment_file.parse_investment_file()
investment.write_forex_obj(forexdict[investment.get_currency()]) # Re-write forex-data to the new instance
investment.write_forex_obj(forexdict[investment.get_currency()]) # Re-write forex-data to the new instance
ret = investment.set_analysis_data(date_analysis_start_str, date_today_str)
if ret is True:
investments_analyzed.append(investment)
Expand Down
2 changes: 1 addition & 1 deletion profit_src/storage/stock/stock.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,4 +96,4 @@ def get_splits(self):
return self.splits

def get_overwrite_flag(self):
return self.overwrite_flag
return self.overwrite_flag
4 changes: 2 additions & 2 deletions profit_src/stringoperations.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@ def remove_leading_whitespace(s):
return leading_whitespace, trimmed_string
return '', s


def count_whitespace_length(s, tab_length=4):
"""Counts the length of the white space given in s as equivalent spaces.
:param s: String of white spaces (tabs or spaces).
Expand All @@ -122,6 +123,5 @@ def count_whitespace_length(s, tab_length=4):
elif char == ' ':
space_cnt += 1
else:
raise RuntimeError(f"This function can only accept tabs or spaces.")
raise RuntimeError("This function can only accept tabs or spaces.")
return space_cnt + tab_cnt * tab_length

0 comments on commit dda9163

Please sign in to comment.