Skip to content

bug fixes#680

Merged
chrisaddy merged 5 commits intoportfolio-fixesfrom
bug-fixes
Jan 21, 2026
Merged

bug fixes#680
chrisaddy merged 5 commits intoportfolio-fixesfrom
bug-fixes

Conversation

@chrisaddy
Copy link
Copy Markdown
Collaborator

@chrisaddy chrisaddy commented Jan 21, 2026

This pull request improves the handling of position closures in the portfolio manager by making the process more robust and informative, and ensures data consistency during portfolio performance calculations. The main changes include updating the close_position method to return whether a position was actually closed, updating the server logic to reflect this new behavior, and ensuring timestamp consistency in dataframes used for risk management.

Position closing improvements:

  • Updated the close_position method in alpaca_client.py to return a boolean indicating if the position was actually closed, and to handle the case where the position does not exist by logging and returning False instead of raising an exception.
  • Modified server.py to use the new return value from close_position, logging and recording a "skipped" status with a reason if the position was already closed or did not exist, instead of treating it as a failure. [1] [2]

Data consistency improvements:

  • In risk_management.py, added logic to cast the timestamp column to Float64 in all relevant dataframes before performing joins and comparisons, ensuring consistent data types and preventing subtle bugs.

chrisaddy and others added 2 commits January 20, 2026 21:28
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
## Bug Fixes

### 1. PYTHON-FASTAPI-21: Position not found error (alpaca_client.py, server.py)
**Root cause**: When closing positions, the code tried to close positions from
`prior_portfolio` (database) without checking if they actually exist in Alpaca.
Positions could have been manually closed or never opened successfully.

**Fix**: Modified `close_position()` to return `bool` and gracefully handle
"position not found" errors by returning `False` instead of raising. The server
now logs these as "skipped" rather than errors.

### 2. PYTHON-FASTAPI-1E: SchemaError type mismatch (risk_management.py)
**Root cause**: Join failed because `timestamp` column had different types
(`f64` vs `i64`) between DataFrames.

**Fix**: Added explicit cast of `prior_equity_bars.timestamp` to `Float64` for
consistency with the other DataFrames. This ensures all timestamp columns have
matching types for joins and comparisons.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Copilot AI review requested due to automatic review settings January 21, 2026 02:49
@chrisaddy chrisaddy changed the base branch from master to portfolio-fixes January 21, 2026 02:49
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Jan 21, 2026

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@pulumi
Copy link
Copy Markdown

pulumi Bot commented Jan 21, 2026

🚀 The Update (preview) for forstmeier/pocketsizefund/production (at 30ec903) was successful.

✨ Neo Explanation

Initial production deployment creating a complete AWS microservices infrastructure for a portfolio management application with three containerized services, load balancing, service discovery, and secure networking across multiple availability zones.

Root Cause Analysis

This is an initial production deployment from a brand-new Pulumi infrastructure-as-code configuration. The developer has defined a complete AWS infrastructure for a microservices-based portfolio management application ("pocketsizefund") that includes three main services: datamanager, equitypricemodel, and portfoliomanager. This appears to be setting up a production-ready environment from scratch rather than modifying existing infrastructure.

Dependency Chain

The infrastructure builds from the ground up in this order:

  1. Network Foundation: VPC → Subnets (public/private across 2 AZs) → Internet Gateway and NAT Gateway for connectivity
  2. Security Layer: Security groups for ALB, ECS tasks, and VPC endpoints with appropriate ingress/egress rules
  3. Container Infrastructure: ECR repositories for storing Docker images → ECS cluster → Task definitions → ECS services
  4. Load Balancing: Application Load Balancer with target groups and listener rules for routing traffic to each microservice
  5. Storage & Configuration: S3 buckets (with versioning) for data and model artifacts, SSM parameters for configuration
  6. Service Discovery: Private DNS namespace enabling services to discover and communicate with each other
  7. IAM Permissions: Execution and task roles with policies for ECS, SageMaker, S3, and Secrets Manager access
  8. VPC Endpoints: Private connections to ECR and S3 to keep container traffic off the public internet

Risk Analysis

Risk Level: Low

This is a greenfield deployment creating all new resources. Since no existing infrastructure exists, there's no risk of downtime, data loss, or service disruption. All stateful resources (S3 buckets) are being created fresh with versioning enabled for data protection.

Resource Changes

    Name                                 Type                                                          Operation
+   public_subnet_1                      aws:ec2/subnet:Subnet                                         create
+   ecs_sg                               aws:ec2/securityGroup:SecurityGroup                           create
+   datamanager_tg                       aws:lb/targetGroup:TargetGroup                                create
+   sagemaker_cloudwatch_policy          aws:iam/rolePolicy:RolePolicy                                 create
+   vpc_endpoints_sg                     aws:ec2/securityGroup:SecurityGroup                           create
+   sagemaker_ecr_policy                 aws:iam/rolePolicy:RolePolicy                                 create
+   model_artifacts_bucket_versioning    aws:s3/bucketVersioning:BucketVersioning                      create
+   portfoliomanager_logs                aws:cloudwatch/logGroup:LogGroup                              create
+   public_subnet_2                      aws:ec2/subnet:Subnet                                         create
+   ecr_dkr_endpoint                     aws:ec2/vpcEndpoint:VpcEndpoint                               create
+   portfoliomanager_service             aws:ecs/service:Service                                       create
+   ssm_uncertainty_threshold            aws:ssm/parameter:Parameter                                   create
+   equitypricemodel_trainer_repository  aws:ecr/repository:Repository                                 create
+   model_artifacts_bucket               aws:s3/bucket:Bucket                                          create
+   private_route_table                  aws:ec2/routeTable:RouteTable                                 create
+   portfoliomanager_repository          aws:ecr/repository:Repository                                 create
+   private_subnet_1                     aws:ec2/subnet:Subnet                                         create
+   task_role_s3_policy                  aws:iam/rolePolicy:RolePolicy                                 create
+   s3_gateway_endpoint                  aws:ec2/vpcEndpoint:VpcEndpoint                               create
+   portfoliomanager_rule                aws:lb/listenerRule:ListenerRule                              create
+   nat_elastic_ip                       aws:ec2/eip:Eip                                               create
+   sagemaker_execution_role             aws:iam/role:Role                                             create
+   public_internet_route                aws:ec2/route:Route                                           create
+   datamanager_sd                       aws:servicediscovery/service:Service                          create
+   public_route_table                   aws:ec2/routeTable:RouteTable                                 create
+   task_role_ssm_policy                 aws:iam/rolePolicy:RolePolicy                                 create
+   service_discovery                    aws:servicediscovery/privateDnsNamespace:PrivateDnsNamespace  create
+   pocketsizefund-production            pulumi:pulumi:Stack                                           create
+   portfoliomanager_sd                  aws:servicediscovery/service:Service                          create
+   ecr_api_endpoint                     aws:ec2/vpcEndpoint:VpcEndpoint                               create
+   datamanager_repository               aws:ecr/repository:Repository                                 create
+   datamanager_task                     aws:ecs/taskDefinition:TaskDefinition                         create
+   public_subnet_1_rta                  aws:ec2/routeTableAssociation:RouteTableAssociation           create
+   http_listener                        aws:lb/listener:Listener                                      create
+   equitypricemodel_service             aws:ecs/service:Service                                       create
+   equitypricemodel_tg                  aws:lb/targetGroup:TargetGroup                                create
+   sagemaker_s3_policy                  aws:iam/rolePolicy:RolePolicy                                 create
+   nat_gateway                          aws:ec2/natGateway:NatGateway                                 create
+   equitypricemodel_logs                aws:cloudwatch/logGroup:LogGroup                              create
+   private_subnet_2                     aws:ec2/subnet:Subnet                                         create
+   alb_sg                               aws:ec2/securityGroup:SecurityGroup                           create
... and 28 other changes

Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR contains bug fixes addressing position closing errors, timestamp type mismatches, and configuration improvements in the portfolio manager application.

Changes:

  • Improved error handling for closing non-existent positions in the Alpaca trading client
  • Fixed timestamp type inconsistencies that caused join failures in portfolio performance calculations
  • Added nushell environment file to gitignore

Reviewed changes

Copilot reviewed 3 out of 4 changed files in this pull request and generated 2 comments.

File Description
applications/portfoliomanager/src/portfoliomanager/alpaca_client.py Modified close_position to return bool and handle position not found errors gracefully
applications/portfoliomanager/src/portfoliomanager/server.py Updated to handle close_position return value and distinguish between successful closes and skipped (position not found) cases
applications/portfoliomanager/src/portfoliomanager/risk_management.py Added explicit Float64 casting for timestamp columns before joins to prevent type mismatch errors
.gitignore Added .env.nu to exclude nushell environment files from version control

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread applications/portfoliomanager/src/portfoliomanager/alpaca_client.py Outdated
Comment thread applications/portfoliomanager/src/portfoliomanager/risk_management.py Outdated
@greptile-apps
Copy link
Copy Markdown
Contributor

greptile-apps Bot commented Jan 21, 2026

Confidence Score: 4/5

  • This PR is generally safe to merge with one logic issue that should be fixed
  • The PR addresses critical production bugs with proper error handling and type fixes. Most changes improve system robustness through better validation, logging, and error handling. However, there is one missing validation for empty tickers in the sync_equity_categories.py that contradicts the PR description and could cause issues with empty ticker symbols being added to the database.
  • Pay close attention to tools/sync_equity_categories.py which is missing the empty ticker validation mentioned in the PR description

Copy link
Copy Markdown
Contributor

@greptile-apps greptile-apps Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Additional Comments (1)

  1. tools/sync_equity_categories.py, line 75-96 (link)

    logic: Missing check for empty ticker values before appending to rows

46 files reviewed, 1 comment

Edit Code Review Agent Settings | Greptile

@chrisaddy addressed this in latest commit

chrisaddy and others added 3 commits January 20, 2026 21:55
Address PR feedback:
- alpaca_client.py: Check HTTP status code (404) and error_code attributes
  before falling back to string matching for position not found errors
- risk_management.py: Document why unconditional timestamp casting is used
  (timestamps may arrive as i64 or f64 depending on serialization path)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Skip entries where the ticker value is empty or missing to prevent
creating rows with empty ticker values in the categories CSV.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
@chrisaddy chrisaddy merged commit 3877247 into portfolio-fixes Jan 21, 2026
6 checks passed
@chrisaddy chrisaddy deleted the bug-fixes branch January 21, 2026 04:18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants