Cost Calculator Service - sgajbi/portfolio-analytics-system GitHub Wiki

Overview

The Cost Calculator service is a core component of the analytics pipeline. It consumes persisted raw transaction events, processes them using the financial-calculator-engine, calculates transaction-level cost basis analytics (such as net_cost and realized_gain_loss), persists these enriched values back to the transactions table, and emits a processed_transactions_completed event for downstream consumers like the Position Calculator.


Key Responsibilities

  • Consume raw_transactions_completed events from its Kafka topic.
  • For a given transaction, fetch all other relevant transactions for that security from the database to establish a full history for calculation.
  • Utilize the financial-calculator-engine library to perform a full recalculation of the security's transaction history.
  • Persist the newly calculated net_cost and realized_gain_loss values to the correct row in the transactions table.
  • Emit a processed_transactions_completed event containing the fully enriched transaction data.

Technology Stack

  • Python Kafka consumer (confluent-kafka-python).
  • financial-calculator-engine (shared library for core logic).
  • SQLAlchemy (ORM for database interaction).
  • PostgreSQL for persistence.

Testing

  • End-to-end tests validate that an ingested transaction results in correctly calculated cost basis values in both the database and the final API response.
  • Unit tests within the financial-calculator-engine library validate the core calculation logic for various scenarios (e.g., FIFO vs. Average Cost).