This commit is contained in:
2026-01-15 09:06:47 +01:00
parent aa4b41d7a7
commit c468746108
11 changed files with 1961911 additions and 60 deletions

View File

@@ -150,13 +150,56 @@ def fetch_last_key_from_dict(dict):
def add_benchmark_ticker(tickers, ticker_benchmarkt):
tickers.append(ticker_benchmarkt)
logging(logging_level="success")
return tickers
# CREATE BENCHMARK TRADES
def create_benchmark_trades(trades):
def create_benchmark_trades(trades, yf_data):
# Prepertion
benchmark_trades = {}
i = 0
# Creating benchmark trades
try:
benchmark_trades = trades
for trade_id in benchmark_trades:
benchmark_trades[trade_id]['ticker'] = config.ticker_benchmark
for trade_id in trades:
# Benchmark-id
i = i+1
benchmark_id = "benchmark" + str(i)
# Copy raw trades
benchmark_trades[benchmark_id] = trades[trade_id]
benchmark_trades[benchmark_id]["ticker"] = config.ticker_benchmark
# Calculate amount invested
amount_invested = benchmark_trades[benchmark_id]["units"] * benchmark_trades[benchmark_id]["course_open"]
# Change course-open for benchmark-ticker performance calculation
success = False
index_date = benchmark_trades[benchmark_id]["date_open"]
while success == False:
try:
course_open_new = yf_data[config.ticker_benchmark].at[index_date, 'Close']
success = True
except:
index_date = index_date + datetime.timedelta(days=1)
benchmark_trades[benchmark_id]["course_open"] = course_open_new # type: ignore
# Change amount for benchmark-ticker performance calculation
benchmark_trades[benchmark_id]["units"] = amount_invested / course_open_new # type: ignore
# Change course-open for benchmark-ticker performance calculation, if relevant
if trades[trade_id]["date_close"] != 0:
success = False
index_date = benchmark_trades[benchmark_id]["date_close"]
while success == False:
try:
course_close_new = yf_data[config.ticker_benchmark].at[index_date, 'Close']
success = True
except:
index_date = index_date + datetime.timedelta(days=1)
benchmark_trades[benchmark_id]["course_close"] = course_close_new # type: ignore
# Logging
logging(logging_level="success")
return benchmark_trades
except Exception as error_message:
@@ -164,6 +207,40 @@ def create_benchmark_trades(trades):
logging(logging_level="error", message=f"Failed with error: {error_message}")
return False
# MERGE BENCHMARK HISTORY & TICKER-HISTROY
def merge_histories(history_per_ticker, benchmark_history):
# Preperation
benchmark_ticker = config.ticker_benchmark
error_count = 0
# Merging Data
for index_date in history_per_ticker:
try:
history_per_ticker[index_date]["benchmark"] = {}
history_per_ticker[index_date]["benchmark"]["current_invested"] = benchmark_history[index_date][benchmark_ticker]["current_invested"]
history_per_ticker[index_date]["benchmark"]["total_dividends"] = benchmark_history[index_date][benchmark_ticker]["total_dividends"]
history_per_ticker[index_date]["benchmark"]["current_value"] = benchmark_history[index_date][benchmark_ticker]["current_value"]
history_per_ticker[index_date]["benchmark"]["current_irr"] = benchmark_history[index_date][benchmark_ticker]["current_irr"]
history_per_ticker[index_date]["benchmark"]["total_performanance"] = benchmark_history[index_date][benchmark_ticker]["total_performanance"]
except:
error_count = error_count +1
# Debugging
if config.selected_logging_level == "debug":
data = json.dumps(history_per_ticker, indent=2) # Converts a python-dictionary into a json
with open("history_per_ticker_with_benchmark.json", "w") as f:
f.write(data)
# Main Logging
if error_count == 0:
logging(logging_level="success")
return history_per_ticker
else:
logging(logging_level="warning")
logging(logging_level="warning", message=f"Error merging benchmark-history into ticker-history in {error_count} cases")
return False
# -------------------------- #
@@ -268,19 +345,25 @@ def fetch_format_notion_trades(db_id_trades):
format_errors = format_errors + 1
error_message = e
# Main Logging
if fetch_error == False & format_errors == 0:
logging(logging_level="success")
logging(logging_level="info", message=f"{number_of_trades} trades recieved and formated")
return trades
elif fetch_error == False & format_errors > 0:
logging(logging_level="warning")
logging(logging_level="warning", message=f"{format_errors} trades out of {number_of_trades} skiped...maybe due to missing values?")
return trades
# Logging
if fetch_error == True:
logging(logging_level="error")
logging(logging_level="error", message=f"Failed with error: {error_message}")
return False
else:
logging(logging_level="error")
logging(logging_level="error", message=f"Failed with error: {error_message}")
return False
# Writing Example File
if config.selected_logging_level == "debug":
with open("trades.json", "w") as f:
f.write(str(trades))
# Logging
if format_errors == 0:
logging(logging_level="success")
logging(logging_level="info", message=f"{number_of_trades} trades recieved and formated")
return trades
else:
logging(logging_level="warning")
logging(logging_level="warning", message=f"{format_errors} trades out of {number_of_trades} skiped...maybe due to missing values?")
return trades
# NOTION FETCH & FORMAT INVESTMENT OVERVIEW
def fetch_format_notion_investments(db_id_investments):
@@ -289,7 +372,6 @@ def fetch_format_notion_investments(db_id_investments):
format_errors = 0
number_of_investments = 0
# Download data & check for success
data = notion_get_pages(db_id_investments)
if data is True:
@@ -322,11 +404,11 @@ def fetch_format_notion_investments(db_id_investments):
# Main Logging
if fetch_error == False & format_errors == 0:
logging(logging_level="success")
logging(logging_level="info", message=f"{number_of_investments} trades recieved and formated")
logging(logging_level="info", message=f"{number_of_investments} investments recieved and formated")
return investments
elif fetch_error == False & format_errors > 0:
logging(logging_level="warning")
logging(logging_level="warning", message=f"{format_errors} trades out of {number_of_investments} skiped...maybe due to missing values?")
logging(logging_level="warning", message=f"{format_errors} investments out of {number_of_investments} skiped...maybe due to missing values?")
return investments
else:
logging(logging_level="error")
@@ -351,18 +433,18 @@ def fetch_format_yf_data(tickers):
try:
# Download data
api = yf.Ticker(ticker)
data = api.history(period="max")
data = api.history(period="max", auto_adjust=False)
except:
# Store error for later logging
fetch_errors = fetch_errors + 1
skip_formating = True
data = True
# If the download was successfull:
if skip_formating == False:
# Try formating the data
try:
# Convert to Pandas DataFrame
data = pd.DataFrame(data)
data = pd.DataFrame(data) # type: ignore
# Delete the columns "Stock Splits", "High", "Low" and "Open"
del data['Open']
@@ -713,7 +795,7 @@ def calc_history_per_trade(trades, yf_data):
return False
# CALC THE HISTORY PER TRADE & OVERALL
def calc_history_per_ticker(history_per_trade, tickers):
def calc_history_per_ticker(history_per_trade, tickers, trades):
# ------------------ CREATE JSON OBJECT
# Create the json-dict
@@ -748,7 +830,6 @@ def calc_history_per_ticker(history_per_trade, tickers):
dict_daily["total"]["total_dividends"] = 0
dict_daily["total"]["current_value"] = 0
dict_daily["total"]["current_irr"] = 0
dict_daily["total"]["current_irr"] = 0
dict_daily["total"]["total_performanance"] = 0
# Loop over each trade-entry for that day
@@ -830,6 +911,8 @@ def calc_history_per_ticker(history_per_trade, tickers):
logging(logging_level="error", message=f"Failed with error message: {error_message}")
return False
# --------------------------- #
# HISTORY SELECTION FUNCTIONS #
# --------------------------- #
@@ -1012,6 +1095,10 @@ def prep_trmnl_chart_udpate(history_to_show, series_to_show_1 = "total", data_to
series_to_show_1 = "Portfolio"
if series_to_show_2 == "total":
series_to_show_2 = "Portfolio"
if series_to_show_1 == "benchmark":
series_to_show_1 = "Benchmark: " + config.ticker_benchmark
if series_to_show_2 == "benchmark":
series_to_show_2 = "Benchmark: " + config.ticker_benchmark
# Generating nicer data titels
data_to_show_1 = data_to_show_1.replace("_", " ").capitalize()