feat: Add CI/CD setup guide with Gitea Actions for trading analysis application

feat: Implement multi-user support with separate brokerage accounts and user authentication

feat: Configure SSO authentication setup using Google OAuth 2.0 for secure access

refactor: Update index page to reflect new Trading Analysis Dashboard features and descriptions

docs: Enhance quickstart guide for deploying Trading Analysis Dashboard with detailed steps

chore: Add runner configuration for Gitea Actions with logging and container settings
This commit is contained in:
Peter Wood
2025-11-14 12:43:09 -05:00
parent 2f5e59b40f
commit c6eb26037b
24 changed files with 3594 additions and 169 deletions

109
features/csv-upload.mdx Normal file
View File

@@ -0,0 +1,109 @@
---
title: 'CSV Upload'
description: 'Import trading data via CSV files with drag-and-drop support'
---
## Overview
The CSV Upload feature allows you to import trading transaction data through an intuitive web interface with drag-and-drop support and real-time processing feedback.
## Features
<CardGroup cols={2}>
<Card title="Drag & Drop" icon="hand-pointer">
Drag CSV files directly onto the upload area
</Card>
<Card title="Progress Tracking" icon="spinner">
Real-time progress bar during processing
</Card>
<Card title="Upload History" icon="clock-rotate-left">
View recent uploads and statistics
</Card>
<Card title="Validation" icon="check">
Automatic CSV format and size validation
</Card>
</CardGroup>
## CSV Format Requirements
Your CSV file must include these columns:
| Column | Format | Description |
|--------|--------|-------------|
| **Date** | MM/DD/YYYY | Transaction date |
| **Action** | Text | Buy, Sell, Cash Dividend, etc. |
| **Symbol** | Text | Stock ticker |
| **Description** | Text | Transaction description |
| **Quantity** | Number | Number of shares (can be empty for dividends) |
| **Price** | Number | Price per share (can be empty for dividends) |
| **Fees & Comm** | Number | Trading fees |
| **Amount** | Number | Total transaction amount |
## Example CSV
```csv
Date,Action,Symbol,Description,Quantity,Price,Fees & Comm,Amount
01/15/2024,Buy,AAPL,Apple Inc,100,150.50,6.95,-15056.95
01/30/2024,Sell,AAPL,Apple Inc,100,155.75,6.95,15568.05
02/15/2024,Cash Dividend,MSFT,Microsoft Corp,,,0.00,75.50
```
## Upload Process
<Steps>
<Step title="Navigate to Upload Page">
Go to `/upload` in your application
</Step>
<Step title="Select File">
Either drag and drop your CSV file or click to browse
</Step>
<Step title="Validation">
The system validates file type (CSV only) and size (50MB max)
</Step>
<Step title="Processing">
Watch real-time progress updates as the file is processed
</Step>
<Step title="Completion">
View the upload in your history and navigate to the dashboard
</Step>
</Steps>
## Processing Flow
1. File uploaded to Flask backend
2. Server validation (file type, size)
3. Trading analysis script processes CSV
4. Database synchronization
5. History updated and temp files cleaned up
## Security
<CardGroup cols={2}>
<Card title="Authentication" icon="lock">
Login required for all uploads
</Card>
<Card title="Validation" icon="shield-check">
File type and size validation
</Card>
<Card title="Sanitization" icon="broom">
Secure filename handling
</Card>
<Card title="Cleanup" icon="trash">
Automatic temp file removal
</Card>
</CardGroup>
## Next Steps
<CardGroup cols={2}>
<Card title="Trading Analysis" icon="chart-line" href="/features/trading-analysis">
Analyze your uploaded data
</Card>
<Card title="Portfolio Management" icon="briefcase" href="/features/portfolio-management">
Track your current holdings
</Card>
</CardGroup>

View File

@@ -0,0 +1,111 @@
---
title: 'Hybrid Matching Algorithm'
description: 'Broker-level accuracy for profit/loss and wash sale tracking'
---
## Overview
The hybrid matching algorithm combines two data sources to provide the most accurate profit/loss and wash sale tracking:
1. **Broker's Realized Gains/Losses CSV** - Pre-calculated lot matches with definitive P&L
2. **Transaction History CSV** - Complete record of all buy/sell transactions
## Key Benefits
<CardGroup cols={2}>
<Card title="Broker-Level Accuracy" icon="bullseye">
Uses broker's proprietary matching logic
</Card>
<Card title="Wash Sale Detection" icon="flag">
Accurate wash sale flags from broker
</Card>
<Card title="FIFO Fallback" icon="layer-group">
Estimates P/L when broker data unavailable
</Card>
<Card title="Complete Coverage" icon="check-double">
Handles all transaction types
</Card>
</CardGroup>
## How It Works
<Steps>
<Step title="Load Broker Lots">
System loads pre-calculated lot matches from broker's realized gains/losses CSV
</Step>
<Step title="Process Sells">
For each sell transaction, checks if corresponding broker lot exists
</Step>
<Step title="Use Broker Data">
If lot found, uses broker's P/L, wash sale flag, and cost basis
</Step>
<Step title="FIFO Estimate">
If no broker lot, applies FIFO (First In, First Out) matching logic
</Step>
</Steps>
## Data Sources
### Broker Realized Gains/Losses
Contains:
- Opened date (purchase date)
- Closed date (sale date)
- Quantity sold from specific lot
- Cost basis and proceeds
- Gain/loss amount (pre-calculated)
- Wash sale flag
- Disallowed loss amount
- Term (Short/Long)
### Transaction History
Contains:
- All buy/sell transactions
- Transaction dates
- Symbol, quantity, price
- Commissions and fees
## Matching Criteria
The system matches broker lots to transactions using:
- **Symbol**: Must match exactly
- **Date**: Must match the transaction date
- **Quantity**: With tolerance for fractional shares
## Data Source Indicators
<Tabs>
<Tab title="Broker-Verified">
✓ **Broker-verified badge**
All trades matched to broker lots with definitive P/L
</Tab>
<Tab title="FIFO Estimate">
⚠️ **FIFO estimate badge**
Trades matched using FIFO logic (no broker lot available)
</Tab>
<Tab title="Mixed Sources">
✓ **Broker-verified** + ⚠️ **FIFO estimate**
Month contains both broker-verified and FIFO-estimated trades
</Tab>
</Tabs>
## Next Steps
<CardGroup cols={2}>
<Card title="CSV Upload" icon="file-csv" href="/features/csv-upload">
Learn how to upload both CSV files
</Card>
<Card title="Trading Analysis" icon="chart-line" href="/features/trading-analysis">
View your matched trades
</Card>
</CardGroup>

View File

@@ -0,0 +1,153 @@
---
title: 'Portfolio Management'
description: 'Track your stock, ETF, and mutual fund holdings with real-time price updates'
---
## Overview
The Portfolio Management feature allows you to track your current stock, ETF, and mutual fund holdings with real-time price updates from Finnhub.io. View comprehensive metrics, allocation charts, and performance analysis all in one place.
## Key Features
<CardGroup cols={2}>
<Card title="Real-time Pricing" icon="clock">
Automatic price updates from Finnhub API
</Card>
<Card title="Multi-Asset Support" icon="layer-group">
Track stocks, ETFs, and mutual funds
</Card>
<Card title="Visual Analytics" icon="chart-pie">
Interactive allocation and performance charts
</Card>
<Card title="CSV Import" icon="file-csv">
Bulk import holdings from CSV files
</Card>
</CardGroup>
## Quick Start
<Steps>
<Step title="Get Finnhub API Key">
Register at [Finnhub.io](https://finnhub.io/register) and copy your API key
</Step>
<Step title="Configure Environment">
Add your API key to `.env`:
```bash
FINNHUB_API_KEY=your_api_key_here
```
</Step>
<Step title="Add Holdings">
Use the web interface to add holdings manually or upload a CSV file
</Step>
<Step title="Refresh Prices">
Click "Refresh Prices" to fetch current market prices
</Step>
</Steps>
## Adding Holdings
### Manual Entry
<Steps>
<Step title="Click Add Holding">
Navigate to the Portfolio page and click the "Add Holding" button
</Step>
<Step title="Fill in Details">
- **Symbol**: Stock ticker (e.g., AAPL, MSFT)
- **Type**: Select stock, ETF, or mutual_fund
- **Shares**: Number of shares owned
- **Average Cost**: Your average cost per share
- **Notes**: Optional notes about the holding
</Step>
<Step title="Save">
Click "Save" to add the holding to your portfolio
</Step>
</Steps>
### CSV Upload
Upload a CSV file with the following format:
```csv
symbol,type,shares,average_cost,notes
AAPL,stock,100,150.50,Tech holding
VOO,etf,50,400.00,S&P 500 ETF
VTSAX,mutual_fund,500,120.25,Index fund
```
<Info>
See the [CSV Upload guide](/features/csv-upload) for detailed formatting instructions.
</Info>
## Portfolio Metrics
The dashboard displays four key summary cards:
| Metric | Description |
|--------|-------------|
| **Total Value** | Current market value of all holdings |
| **Total Cost** | Total amount invested (shares × average cost) |
| **Total Gain/Loss** | Dollar amount gained or lost |
| **Total Return** | Percentage return on investment |
## Charts
### Allocation Chart
Interactive doughnut chart showing:
- Percentage of portfolio in each holding
- Dollar amounts on hover
- Click legend to show/hide holdings
### Performance Chart
Bar chart displaying:
- Gain/loss for each holding
- Green bars for profitable holdings
- Red bars for losing holdings
## Managing Holdings
### Edit a Holding
1. Click the edit (✏️) button next to any holding
2. Update the fields you want to change
3. Click "Save"
<Warning>
You cannot change the symbol of an existing holding. To change a symbol, delete the holding and add a new one.
</Warning>
### Delete a Holding
1. Click the delete (🗑️) button next to any holding
2. Confirm the deletion
## Price Updates
Click the **"Refresh Prices"** button to fetch the latest market prices for all holdings. Prices are also automatically refreshed when viewing the page if the last update was more than 15 minutes ago.
### Rate Limiting
The free Finnhub API tier allows:
- **60 requests per minute**
- **Real-time US stock quotes**
- **Delayed mutual fund prices** (typically 15-30 minutes)
The application intelligently manages API requests to stay within these limits.
## Next Steps
<CardGroup cols={2}>
<Card title="Trading Analysis" icon="chart-line" href="/features/trading-analysis">
Analyze your historical trading performance
</Card>
<Card title="API Reference" icon="code" href="/api-reference/portfolio-holdings">
Integrate with the Portfolio API
</Card>
</CardGroup>

View File

@@ -0,0 +1,181 @@
---
title: 'Portfolio Quick Start'
description: 'Get started with portfolio tracking in minutes'
---
## Quick Setup Guide
Get your portfolio up and running in just a few minutes.
## Step 1: Get Your Finnhub API Key
<Steps>
<Step title="Register">
Go to [Finnhub.io](https://finnhub.io/register) and sign up for a free account
</Step>
<Step title="Get API Key">
After logging in, copy your API key from the dashboard
</Step>
</Steps>
## Step 2: Configure the API Key
Add your Finnhub API key to the `.env.docker` file (or `.env` if running locally):
```bash .env.docker
FINNHUB_API_KEY=your_api_key_here
```
<Note>
The `.env.docker` file already has a placeholder for the API key.
</Note>
## Step 3: Deploy/Restart the Application
If you're already running the application, restart it to load the new environment variable:
```bash
docker compose down
docker compose up -d
```
For first-time deployment:
<Tabs>
<Tab title="Linux/Mac">
```bash
./deploy.sh
```
</Tab>
<Tab title="Windows">
```batch
deploy.bat
```
</Tab>
</Tabs>
## Step 4: Apply Database Schema
The portfolio holdings table needs to be created in your database:
```bash
# Access the database container
docker compose exec postgres psql -U trading_user -d mining_wood
# Run the schema file
\i /docker-entrypoint-initdb.d/portfolio_schema.sql
# Or run it directly from the host
docker compose exec -T postgres psql -U trading_user -d mining_wood < database_init/portfolio_schema.sql
```
## Step 5: Access the Portfolio Page
<Steps>
<Step title="Open your browser">
Navigate to `http://localhost:8080`
</Step>
<Step title="Go to Portfolio">
You should be redirected to the Portfolio Management page (now the default landing page)
</Step>
<Step title="Check for errors">
If you see an error, check the application logs:
```bash
docker compose logs -f trading_app
```
</Step>
</Steps>
## Step 6: Add Your First Holding
### Option A: Manual Entry
<Steps>
<Step title="Click Add Holding">
Click the **"Add Holding"** button
</Step>
<Step title="Fill in the form">
- **Symbol**: Enter a stock ticker (e.g., AAPL)
- **Type**: Select "stock", "etf", or "mutual_fund"
- **Shares**: Enter the number of shares you own
- **Average Cost**: Enter your average cost per share
- **Notes**: (Optional) Add any notes
</Step>
<Step title="Save">
Click **"Save"**
</Step>
</Steps>
### Option B: CSV Upload
<Steps>
<Step title="Prepare CSV file">
Create a CSV file with your holdings:
```csv
symbol,type,shares,average_cost,notes
AAPL,stock,100,150.50,Apple Inc
MSFT,stock,50,300.00,Microsoft
VOO,etf,25,400.00,S&P 500 ETF
```
</Step>
<Step title="Upload">
- Click the **"Upload CSV"** button
- Select your CSV file
- Click **"Upload"**
</Step>
</Steps>
## Step 7: Refresh Prices
Click the **"Refresh Prices"** button to fetch current market prices from Finnhub for all your holdings.
## Troubleshooting
<AccordionGroup>
<Accordion title="Prices Not Updating">
**Solution**: Verify your API key is set correctly in `.env.docker` and you've restarted the containers.
```bash
# Check if environment variable is loaded
docker compose exec trading_app env | grep FINNHUB
```
</Accordion>
<Accordion title="Database Table Not Found">
**Solution**: Run the portfolio schema script:
```bash
docker compose exec -T postgres psql -U trading_user -d mining_wood < database_init/portfolio_schema.sql
```
</Accordion>
<Accordion title="CSV Upload Fails">
**Solution**: Make sure your CSV file has the correct format with columns: `symbol`, `type`, `shares`, `average_cost`, `notes`
</Accordion>
<Accordion title="Application Won't Start">
**Solution**: Check the logs for errors:
```bash
docker compose logs -f trading_app
```
</Accordion>
</AccordionGroup>
## Next Steps
<CardGroup cols={2}>
<Card title="Portfolio Management" icon="chart-line" href="/features/portfolio-management">
Learn more about portfolio features
</Card>
<Card title="Trading Analysis" icon="magnifying-glass-chart" href="/features/trading-analysis">
Analyze your trading performance
</Card>
</CardGroup>

View File

@@ -0,0 +1,92 @@
---
title: 'Timeframe Analysis'
description: 'Analyze trading performance across custom time periods'
---
## Overview
The Timeframe Analysis feature allows you to analyze trading performance across different time periods with comprehensive P/L summaries including both trading profits/losses and dividend income.
## Time Period Selection
<CardGroup cols={2}>
<Card title="All Time" icon="infinity">
Analyzes all available trading data
</Card>
<Card title="Current Month" icon="calendar-day">
Current calendar month performance
</Card>
<Card title="Year to Date" icon="calendar-check">
Performance from January 1st to today
</Card>
<Card title="Past Year" icon="calendar-days">
Rolling 365-day performance
</Card>
<Card title="Custom Period" icon="calendar-range">
Select your own date range
</Card>
</CardGroup>
## Key Metrics
- **Period**: Exact date range for selected timeframe
- **Total P/L**: Combined trading profit/loss and dividends
- **Trading P/L**: Profit/loss from completed trades only
- **Dividends**: Total dividend income received
- **Closed Trades**: Number of completed buy/sell transactions
- **Win Rate**: Percentage of profitable trades
## Summary Breakdowns
### Weekly Summary
Groups data by calendar week showing:
- Trading P/L per week
- Dividends per week
- Total P/L per week
- Number of trades per week
### Monthly Summary
Groups data by calendar month showing:
- Trading P/L per month
- Dividends per month
- Total P/L per month
- Number of trades per month
## Open Positions
Displays current open positions (stocks bought but not yet sold):
- Symbol and number of shares
- Notes that open positions are excluded from P/L calculations
## Usage
<Steps>
<Step title="Navigate to Summary">
Go to the Summary page and click "By Timeframe"
</Step>
<Step title="Select Period">
Choose from dropdown - date fields auto-populate
</Step>
<Step title="Custom Dates (Optional)">
Manually adjust start/end dates for fine-tuning
</Step>
<Step title="Apply">
Click "Apply Dates" for custom date ranges
</Step>
</Steps>
## Next Steps
<CardGroup cols={2}>
<Card title="Trading Analysis" icon="chart-line" href="/features/trading-analysis">
View monthly trading performance
</Card>
<Card title="API Reference" icon="code" href="/api-reference/timeframe">
Use the Timeframe API
</Card>
</CardGroup>

View File

@@ -0,0 +1,69 @@
---
title: 'Trading Analysis'
description: 'Analyze monthly trading performance and track profit/loss'
---
## Overview
The Trading Analysis feature provides comprehensive monthly trading performance analysis with detailed profit/loss tracking, trade-by-trade breakdowns, and dividend income reporting.
## Features
<CardGroup cols={2}>
<Card title="Monthly Navigation" icon="calendar">
Navigate between months with trading data
</Card>
<Card title="P/L Display" icon="dollar-sign">
Color-coded profit/loss amounts
</Card>
<Card title="Trade Details" icon="list">
Detailed breakdown of individual trades
</Card>
<Card title="Dividend Tracking" icon="coins">
Track dividend income separately
</Card>
</CardGroup>
## Monthly Dashboard
The dashboard displays:
- **Total Trades**: Number of completed buy/sell transactions
- **Winning Trades**: Number of profitable trades
- **Win Rate**: Percentage of winning trades
- **Trading P/L**: Profit/loss from trades
- **Dividend Income**: Total dividends received
- **Total Return**: Combined trading P/L and dividends
## Trade Details
Click on any profit/loss amount to see detailed trade information:
- **Symbol**: Stock ticker
- **Buy Date**: Purchase date
- **Sell Date**: Sale date
- **Buy Price**: Purchase price per share
- **Sell Price**: Sale price per share
- **Volume**: Number of shares traded
- **Profit/Loss**: Total profit or loss
- **Return %**: Percentage return
## Hybrid Matching Algorithm
The system uses a hybrid matching algorithm that combines:
1. **Broker Realized Gains/Losses** - Pre-calculated lot matches with definitive P/L
2. **Transaction History** - Complete record of all buy/sell transactions
This achieves **broker-level accuracy** for closed positions.
## Next Steps
<CardGroup cols={2}>
<Card title="CSV Upload" icon="file-csv" href="/features/csv-upload">
Import your trading history
</Card>
<Card title="API Reference" icon="code" href="/api-reference/months">
Integrate with the Trading API
</Card>
</CardGroup>

View File

@@ -0,0 +1,90 @@
---
title: 'Trading Calendar'
description: 'Real-time market trading days and holiday information'
---
## Overview
The Trading Calendar API provides real-time metrics about NYSE (New York Stock Exchange) trading days and upcoming market holidays.
## Features
<CardGroup cols={2}>
<Card title="Remaining Days" icon="calendar-days">
Trading days left in month and year
</Card>
<Card title="Next Holiday" icon="flag">
Upcoming market closure information
</Card>
<Card title="Market Status" icon="clock">
Is the market open today/tomorrow?
</Card>
<Card title="Holiday List" icon="list">
View upcoming market holidays
</Card>
</CardGroup>
## API Endpoint
### GET /api/trading-calendar/metrics
Returns trading calendar metrics including remaining trading days and next market holiday.
**Authentication**: Required (OAuth 2.0)
**Response**:
```json
{
"success": true,
"remaining_trading_days_month": 14,
"remaining_trading_days_year": 36,
"next_market_holiday": {
"name": "Thanksgiving Day",
"date": "2025-11-27"
},
"days_until_next_market_holiday": 19,
"upcoming_holidays": [
{
"name": "Thanksgiving Day",
"date": "2025-11-27",
"days_until": 19
},
{
"name": "Christmas Day",
"date": "2025-12-25",
"days_until": 47
}
],
"is_market_open_today": false,
"is_market_open_tomorrow": false,
"timezone": "America/New_York"
}
```
## Response Fields
| Field | Type | Description |
|-------|------|-------------|
| `remaining_trading_days_month` | integer | Trading days left in current month |
| `remaining_trading_days_year` | integer | Trading days left in current year |
| `next_market_holiday` | object | Next market closure info |
| `days_until_next_market_holiday` | integer | Days until next closure |
| `upcoming_holidays` | array | List of upcoming holidays (up to 10) |
| `is_market_open_today` | boolean | Market open today? |
| `is_market_open_tomorrow` | boolean | Market open tomorrow? |
## Data Source
Uses `pandas_market_calendars` library for accurate NYSE calendar data.
## Next Steps
<CardGroup cols={2}>
<Card title="API Reference" icon="code" href="/api-reference/introduction">
View full API documentation
</Card>
<Card title="Trading Analysis" icon="chart-line" href="/features/trading-analysis">
Analyze trading performance
</Card>
</CardGroup>