Skip to content

Instantly share code, notes, and snippets.

@aquilax
Created May 11, 2026 05:15
Show Gist options
  • Select an option

  • Save aquilax/3324e98d6bbac12c35571896da781020 to your computer and use it in GitHub Desktop.

Select an option

Save aquilax/3324e98d6bbac12c35571896da781020 to your computer and use it in GitHub Desktop.
etrade2k4
import csv
import sys
import os
from datetime import datetime
# ==========================================================
# 1. DEFINE YOUR EXCHANGE RATES HERE
# Format: "MM/DD/YYYY": rate
# Use the rate from the date of sale (or last banking day)
# ==========================================================
EXCHANGE_RATES = {
"01/15/2025": 10.45,
"02/20/2025": 10.52,
"03/05/2025": 10.38,
# Add all dates found in your E-Trade report here...
}
def clean_num(val):
if not val or val.strip() == "":
return 0.0
return float(val.replace('$', '').replace(',', '').strip())
def process_k4(input_file):
if not os.path.exists(input_file):
print(f"Error: File '{input_file}' not found.")
sys.exit(1)
output_file = "k4_manual_report.csv"
results = []
with open(input_file, mode='r', encoding='utf-8-sig') as f_in:
reader = csv.DictReader(f_in)
print(f"\n{'DATE':<12} | {'SYMBOL':<8} | {'RATE':<8} | {'NET SEK'}")
print("-" * 50)
for line_num, row in enumerate(reader, start=2):
# Process only 'Sell' or 'Closing' transactions
rec_type = row.get('Record Type', '')
if 'Sell' in rec_type or 'Closing' in rec_type:
date_sold = row['Date Sold']
symbol = row['Symbol']
# --- STRICT CHECK ---
if date_sold not in EXCHANGE_RATES:
print(f"\n[!!!] FATAL ERROR: Date '{date_sold}' (Row {line_num}) not found in EXCHANGE_RATES.")
print("Please add this date to the dictionary at the top of the script and run again.")
sys.exit(1) # Stop the script entirely
rate = EXCHANGE_RATES[date_sold]
# K4 Calculations (Rounding to whole Krona for Skatteverket)
usd_proceeds = clean_num(row['Total Proceeds'])
usd_cost = clean_num(row['Adjusted Cost Basis'])
sek_proceeds = round(usd_proceeds * rate)
sek_cost = round(usd_cost * rate)
net = sek_proceeds - sek_cost
results.append([date_sold, symbol, row['Quantity'], rate, sek_proceeds, sek_cost, net])
print(f"{date_sold:<12} | {symbol:<8} | {rate:<8.4f} | {net:>10}")
# Write to CSV only if we made it through the whole file without stopping
with open(output_file, mode='w', newline='', encoding='utf-8') as f_out:
writer = csv.writer(f_out)
writer.writerow(['Date Sold', 'Symbol', 'Qty', 'USD Rate', 'Proceeds (SEK)', 'Cost (SEK)', 'Profit/Loss (SEK)'])
writer.writerow(['Date Sold', 'Beteckning', 'Antal', 'USD Rate', ' Försäljningspris', 'Omkostnadsbelopp', 'Profit/Loss (SEK)'])
writer.writerows(results)
print(f"\nSuccess! All dates validated. Report saved to {output_file}")
if __name__ == "__main__":
if len(sys.argv) < 2:
print("Usage: python k4_manual.py <your_etrade_file.csv>")
else:
process_k4(sys.argv[1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment