Please act as an excellent professional Django developer and give advice on how to improve code in "profits/services" folder. How can organize the code so if follows coding best patterns and practices. Should I move the functionality into classes? Should I move the classes into folders? What other changes should I perform?
Assistant
User
if add a custom exception CurrencyConversionException, to raise exceptions inside CurrencyService where should it be added ?
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Okay, let's analyze the code in the profits/services directory and discuss improvements, best practices, and potential refactoring.
Current Structure & Observations
The profits/services directory currently contains the following files:
currency_service.py: Handles currency exchange data retrieval and currency conversion checks.
operation_service.py: Deals with fetching account operation data (sales, all operations for ticker).
operation_tracker.py: Defines a dataclass to track operation details.
profit_service.py: Implements the core profit calculation logic, including retrieving data, calculating profits, and handling FIFO logic.
General Recommendations
Embrace Classes for Services:
Problem: Currently, the services are implemented as collections of standalone functions. This can lead to difficulties in maintaining state, testing, and extensibility.
Solution: Refactor each service into a class. This promotes encapsulation, improves readability, and allows you to add methods and properties naturally.
Example: Instead of currency_service.py having standalone functions like load_currency_exchanges, make a CurrencyService class, with the function load_currency_exchanges being a method inside the class.
Benefits: This will allow to instantiate service objects and make them more easily testable as well as better maintainable.
Create Separate Folders for Services (Optional):
Problem: As the application grows, a flat structure for services might become hard to navigate.
Solution: Organize related services into subfolders. For instance, you could have a currency folder containing currency_service.py, or an operation folder, etc.
Benefits: Improves project organization and maintainability, especially for larger projects. It can make it easier to find services related to certain areas.
Note: For the current size of the project, it might be optional.
Decouple data fetching from calculation Logic:
Problem: The profit_service.py is doing both fetching data using Operation.objects.filter and calculating the profit. This makes the code hard to test and reason about.
Solution: Move the data fetching from profit_service.py to operation_service.py. The profit_service.py should receive the data needed to do the calculation.
Benefits: Each service has its own responsibility, which makes it easier to test, reason about and maintain.
Dependency Injection (If Needed):
Problem: As the application grows, your services may depend on each other. Instantiating them directly within each other can make testing harder.
Solution: You can consider using dependency injection when services depend on each other. Pass the service dependencies as arguments in the constructor of the classes.
Benefits: Easier testing by mocking dependencies.
Note: For the current size, this is also optional. If there is no dependency between the services classes, you can skip this recommendation.
Type Hinting:
Current: The code already has good type hinting.
Recommendation: Continue enforcing type hinting, which will help catch errors early and make the code more readable.
Clear Naming:
Current: Most of the code already has clear naming.
Recommendation: Ensure that names are consistent and describe their purpose accurately.
Testability:
Current: The code already contains some integration tests.
Recommendation: Writing unit tests for individual functions/methods after refactoring to classes will be key for good design and will help to cover all code branches, as well as allow refactoring with confidence.
Refactoring Plan (Example)
Here's a conceptual plan on how you could refactor the services.
1. currency_service.py to CurrencyService
python
# profits/services/currency/currency_service.py
from datetime import datetime
from typing import Optional
from profits.models import CurrencyExchange
class CurrencyService:
def load_currency_exchanges(
self,
origin_currency_code: Optional[str],
target_currency_code: Optional[str],
date_start: Optional[datetime],
date_end: Optional[datetime]) -> dict:
"""
Loads currency exchange rates from the database, filtered by the given parameters
Returns a dictionary with the exchange rates, where the keys are the dates
and the values are dictionaries with the exchange rates for that date.
The keys of the inner dictionary are strings of the form
"origin-target", where origin and target are the ISO codes of the
currencies, and the values are the exchange rates.
"""
exchanges= CurrencyExchange.objects
if origin_currency_code:
exchanges = exchanges.filter(origin_iso_code=origin_currency_code)
if target_currency_code:
exchanges = exchanges.filter(target_iso_code=target_currency_code)
if date_start:
exchanges = exchanges.filter(date__gte=date_start)
if date_end:
exchanges = exchanges.filter(date__lte=date_end)
exchange_dict = {}
for exchange in exchanges:
day_exchange = exchange_dict.get(exchange.date, {})
day_exchange[f"{exchange.origin.iso_code}-{exchange.target.iso_code}"] = exchange.rate
exchange_dict[exchange.date] = day_exchange
return exchange_dict
def is_currency_conversion(self, ticker: str) -> bool:
"""
Checks if the given ticker represents a currency conversion.
"""
return ticker.upper() in ('USDGBP', 'USDEUR', 'GBPUSD', 'GBPEUR', 'EURUSD', 'EURGBP')
2. operation_service.py to OperationService
python
# profits/services/operation/operation_service.py
from datetime import datetime
from typing import Optional
from profits.models import Account, Operation
class OperationService:
def get_account_tickers_sold_period(self, account: Account, date_start: Optional[datetime], date_end: Optional[datetime]) -> list[str]:
"""
Returns the list of tickers that were sold within the given time period for the given account.
"""
operations = Operation.objects.filter(account=account)
if date_start:
operations = operations.filter(date__gte=date_start)
if date_end:
operations = operations.filter(date__lte=date_end)
operations = operations.filter(type='SELL')
operations = operations.values_list('ticker', flat=True).distinct()
return list(operations)
def get_account_ticker_operations(self, account: Account, ticker_sold: str, date_end: Optional[datetime]) -> list[Operation]:
operations = Operation.objects.filter(account=account).filter(ticker=ticker_sold)
if date_end:
operations = operations.filter(date__lte=date_end)
operations = operations.order_by('date', 'type') # Order by type so 'BUY' come before 'SELL' and no error if on same date
return list(operations)
3. profit_service.py to ProfitService
python
4. Usage Example
After refactoring, here is how the get_total_details can be used:
By applying these changes, you'll have code that is:
More Organized: Easier to locate and understand services.
More Maintainable: Changes in one service are less likely to affect others.
More Testable: You can mock dependencies and unit test services more easily.
More Extensible: Adding new features or services is easier.
Remember to adapt these recommendations to your specific needs and project scale. As you refactor, write unit tests to cover all code branches.
Okay, let's talk about adding a custom exception CurrencyConversionException and where it should reside within your project structure, specifically in relation to the CurrencyService.
Best Practices for Custom Exceptions
Dedicated exceptions.py File:
Recommendation: Create a separate file, typically named exceptions.py, within the profits app to house your custom exception classes. This keeps your service code cleaner and centralizes your custom exception definitions.
Why:
Organization: Keeps custom exceptions together.
Reusability: Makes it easy to import and use these exceptions in different parts of your application.
Readability: Makes it clear that these are custom exceptions defined specifically for your project.
Subclassing Exception:
Recommendation: Your custom exception should typically inherit from the built-in Exception class or a more specific built-in exception if appropriate (e.g., ValueError, TypeError).
Implementation
Here's how you'd implement the CurrencyConversionException and integrate it with the CurrencyService:
1. Create profits/exceptions.py
python
# profits/exceptions.py
class CurrencyConversionException(Exception):
"""Custom exception for currency conversion related errors."""
pass
2. Modify currency_service.py
python
# profits/services/currency/currency_service.py
from datetime import datetime
from typing import Optional
from profits.models import CurrencyExchange
from profits.exceptions import CurrencyConversionException
class CurrencyService:
def load_currency_exchanges(
self,
origin_currency_code: Optional[str],
target_currency_code: Optional[str],
date_start: Optional[datetime],
date_end: Optional[datetime]) -> dict:
"""
Loads currency exchange rates from the database, filtered by the given parameters
Returns a dictionary with the exchange rates, where the keys are the dates
and the values are dictionaries with the exchange rates for that date.
The keys of the inner dictionary are strings of the form
"origin-target", where origin and target are the ISO codes of the
currencies, and the values are the exchange rates.
"""
exchanges= CurrencyExchange.objects
if origin_currency_code:
exchanges = exchanges.filter(origin_iso_code=origin_currency_code)
if target_currency_code:
exchanges = exchanges.filter(target_iso_code=target_currency_code)
if date_start:
exchanges = exchanges.filter(date__gte=date_start)
if date_end:
exchanges = exchanges.filter(date__lte=date_end)
exchange_dict = {}
for exchange in exchanges:
day_exchange = exchange_dict.get(exchange.date, {})
if not exchange.rate:
raise CurrencyConversionException(f"No exchange rate found for {exchange.origin.iso_code}-{exchange.target.iso_code} on {exchange.date}")
day_exchange[f"{exchange.origin.iso_code}-{exchange.target.iso_code}"] = exchange.rate
exchange_dict[exchange.date] = day_exchange
return exchange_dict
def is_currency_conversion(self, ticker: str) -> bool:
"""
Checks if the given ticker represents a currency conversion.
"""
return ticker.upper() in ('USDGBP', 'USDEUR', 'GBPUSD', 'GBPEUR', 'EURUSD', 'EURGBP')
Explanation of changes
We've added the import statement from profits.exceptions import CurrencyConversionException to be able to use the new exception.
We've added if not exchange.rate: to load_currency_exchanges to check if the rate is present in the CurrencyExchange object and we raise a CurrencyConversionException if the rate is missing.
How to Use the Exception
In other parts of your code (e.g., your ProfitService, a view, or a management command) where you use CurrencyService, you would handle this exception like so:
python
from profits.services.currency.currency_service import CurrencyService
from profits.exceptions import CurrencyConversionException
currency_service = CurrencyService()
try:
exchange_rates = currency_service.load_currency_exchanges(
origin_currency_code="USD",
target_currency_code="EUR",
date_start=datetime(2024, 1, 1),
date_end=datetime(2024, 1, 31),
)
except CurrencyConversionException as e:
print(f"Error loading currency data: {e}")
# Handle the exception here - log, display an error, etc.
Important Considerations
Specific Error Messages: Provide clear and informative messages within your custom exceptions (as shown in the example above) that aid in debugging.
Exception Handling: Make sure to catch and handle your custom exceptions appropriately at the right places in your application.
Documentation: Document your custom exceptions so other developers know what they represent and under what circumstances they are raised.
By following these steps, you'll have a more robust and maintainable way to handle specific error conditions within your application. Remember to add unit tests for the exception handling in your services.
Dataset releases
Not yet included in a published release.
# profits/services/profit/profit_service.py
from datetime import datetime
from decimal import Decimal
from typing import Optional
from profits.models import Account, Operation
from profits.services.currency.currency_service import CurrencyService
from profits.services.operation.operation_service import OperationService
from profits.services.operation_tracker import OperationTracker
class ProfitService:
def __init__(self, operation_service: OperationService, currency_service: CurrencyService):
self.operation_service = operation_service
self.currency_service = currency_service
def get_total(self, account: Account, date_start: Optional[datetime], date_end: Optional[datetime]) -> Decimal:
"""
TODO: refactor logic to base return on results from 'get_total_details'
"""
operations = Operation.objects.filter(account=account)
if date_start:
operations = operations.filter(date__gte=date_start)
if date_end:
operations = operations.filter(date__lte=date_end)
operations = operations.order_by('date')
amount_total = Decimal(0)
for sell_operation in operations:
if self.currency_service.is_currency_conversion(sell_operation.ticker):
continue
amount_total += sell_operation.amount_total
return amount_total
def add_profit_line(self, sell_quantity_line: Decimal, sell: OperationTracker, buy: OperationTracker, profits: list[dict]):
profits.append(
{
'sell_date': sell.date,
'sell_quantity': sell_quantity_line,
'sell_amount_total': sell_quantity_line * sell.price_avg,
'sell_currency': sell.currency,
'buy_date': buy.date,
'buy_amount_total': sell_quantity_line * buy.price_avg,
'buy_currency': buy.currency,
'profit': sell_quantity_line * (sell.price_avg - buy.price_avg)
}
)
def add_profit_lines(self, sell_left: OperationTracker, buys: list[OperationTracker], buys_used_index: int, profits: list[dict]):
while sell_left.quantity > 0 and buys_used_index < len(buys):
if buys[buys_used_index].quantity > sell_left.quantity:
sell_quantity_line = sell_left.quantity
sell_left.quantity = Decimal(0)
buys[buys_used_index].quantity -= sell_quantity_line
self.add_profit_line(sell_quantity_line, sell_left, buys[buys_used_index], profits)
else:
sell_quantity_line = buys[buys_used_index].quantity
sell_left.quantity -= sell_quantity_line
buys[buys_used_index].quantity = Decimal(0)
self.add_profit_line(sell_quantity_line, sell_left, buys[buys_used_index], profits)
buys_used_index += 1
if sell_left.quantity > 0:
raise ValueError(f'On date {sell_left.date} there are {sell_left.quantity} stocks left to sell without corresponding buys.')
def create_operation_tracker(self, ticker_operation: Operation) -> OperationTracker:
return OperationTracker(
date= ticker_operation.date,
quantity= ticker_operation.quantity,
currency= ticker_operation.currency.iso_code,
price_avg= ticker_operation.amount_total / ticker_operation.quantity
)
def get_total_details_ticker(self, ticker_operations: list[Operation]) -> list[dict]:
buys = []
profits = []
buys_used_index = 0
for ticker_operation in ticker_operations:
operation_tracker= self.create_operation_tracker(ticker_operation)
if ticker_operation.type == 'BUY':
buys.append(operation_tracker)
else:
try:
self.add_profit_lines(operation_tracker, buys, buys_used_index, profits)
except ValueError as e:
raise ValueError(f'For ticker {ticker_operation.ticker} there is error: {e}') from e
return profits
def get_total_details(self, account: Account, date_start: Optional[datetime], date_end: Optional[datetime]) -> list[dict]:
account_tickers_sold = self.operation_service.get_account_tickers_sold_period(account, date_start, date_end)
tickers_profit = []
for ticker_sold in account_tickers_sold:
if self.currency_service.is_currency_conversion(ticker_sold):
continue
ticker_operations= self.operation_service.get_account_ticker_operations(account, ticker_sold, date_end)
ticker_profits = self.get_total_details_ticker(ticker_operations)
tickers_profit.append(
{
'ticker': ticker_sold,
'profit_detail': ticker_profits
}
)
return tickers_profit