import tkinter as tk from tkinter import filedialog import os from datetime import datetime from zoneinfo import ZoneInfo import pandas as pd import sys #pyinstaller main.py --onefile --windowed --icon=icon.ico false = False true = True DEBUG = false def log(s): if DEBUG: print(s) else: pass line = '\n\n--------------------------------------------------------------------------------------' berlin_tz = ZoneInfo("Europe/Berlin") eastern_tz = ZoneInfo("America/New_York") def select_file(): # Create a Tk root widget root = tk.Tk() root.withdraw() # Hide the root window # Open a file dialog and get the selected file path file_path = filedialog.askopenfilename(title="Select Heldental Trade Report CSV File", filetypes=[("CSV files", "*.csv")]) return file_path def get_output_filename(base_name): # Generate a timestamp timestamp = datetime.now().strftime("_%m-%d-%Y_%H-%M-%S") # Create a new filename with timestamp name, ext = os.path.splitext(base_name) new_filename = f"{name}{timestamp}{ext}" return new_filename def process_trades(input_file, output_file): trades = pd.read_csv(input_file, sep=';', skiprows=1, skipfooter=2, usecols=[0,1,6,7,8,9,11,12], engine='python') trades = trades.iloc[::-1].reset_index(drop=True) # Convert 'Date' column to datetime trades['Date'] = pd.to_datetime(trades['Date'], format='%d.%m.%Y %H:%M:%S') # Extract date part only (without time) and add as a new column trades['Time'] = trades['Date'].dt.time trades['Date_only'] = trades['Date'].dt.date # Group by 'Date_only' and 'Instrument' (stock symbol) grouped = trades.groupby(['Date_only', 'Instrument']) export = [] # Loop through each group (date and symbol) for (date, symbol), group in grouped: log(line) log(f"Date: {date}, Symbol: {symbol}") strategy = '' new_trade = True total_qty = 0 # Loop through each transaction within the group for _, row in group.iterrows(): log(f"\nrow: {row}") log(f" Time: {row['Time']} - Operation: {row['Operation']} - Price: {row['Price']} - Amount: {row['Amount']}") qty = row['Amount'] if new_trade == True: log("\n\n------------New Trade--------------------") if new_trade == True and row['Operation'] == 'Buy': new_trade = False strategy = 'long' side = 'B' total_qty += qty elif new_trade == True and row['Operation'] == 'Sell': new_trade = False strategy = 'short' side = 'SS' total_qty += -qty elif new_trade == False and row['Operation'] == 'Buy': if strategy == 'long': side = 'B' elif strategy == 'short': side = 'BC' total_qty += qty elif new_trade == False and row['Operation'] == 'Sell': if strategy == 'long': side = 'S' elif strategy == 'short': side = 'SS' total_qty += -qty log('\nTotal QTY = ' + str(total_qty) + '\n') if total_qty == 0: new_trade = True date = row['Date'] date = str(date).split(' ')[0] date = datetime.strptime(date, "%Y-%m-%d") date = date.strftime("%m/%d/%Y") account = row['Account'] exec_time = row['Date'] exec_time = exec_time.replace(tzinfo=berlin_tz) exec_time = exec_time.astimezone(eastern_tz) exec_time = str(exec_time).split(' ')[1] exec_time = exec_time.split('-')[0] symbol = row['Instrument'] qty = row['Amount'] price = row['Price'] exec_fee = row['Execution fee'] sign = -1 gross = round(row['Profit'],2) net = round(gross - (sign*exec_fee),2) log('Gross= ' + str(gross)) log('Net= ' + str(net)) export.append( { 'Account': account, 'T/D':date, # trade date in MM/DD/YYYY format 'S/D':date, # same as T/D, trade date in MM/DD/YYYY format 'Currency':str('USD'), 'Type':str('stock'), 'Side':side, # B: Buy / S: Sell / SS: Short / BC: Buy cover 'Symbol':symbol, # symbol 'Qty':str(qty).split('.')[0], # number of shares executed 'Price':price, # price of symbol 'Exec Time':exec_time, # trade time in HH:mm:ss format 'Comm':str('0'), 'SEC':str('0'), 'TAF':str('0'), 'NSCC':str('0'), 'Nasdaq':(sign*exec_fee), 'ECN Remove':str('0'), 'ECN Add':str('0'), 'Gross Proceeds':gross, # gross proceeds = shares * price 'Net Proceeds':net, # gross proceeds minus commissions and fees = shares * price - fee 'Clr Broker':str(''), 'Liq':str(''), 'Note':total_qty }) export_data = pd.DataFrame(export) export_data.to_csv(output_file, index=False, header=True, mode='w', sep=';') # Delete the last empty line which was generated by the .to_csv function with open(output_file) as f: lines = f.readlines() last = len(lines) - 1 lines[last] = lines[last].replace('\r','').replace('\n','') with open(output_file, 'w') as wr: wr.writelines(lines) if __name__ == "__main__": # Prompt the user to select an input file input_file = select_file() if not input_file: print("No file selected. Exiting.") sys.exit() # Define output filename and append timestamp if necessary output_file = get_output_filename("TradeNote_.txt") # Process trades process_trades(input_file, output_file)