Portfolio Tracker

A comprehensive portfolio management application built with Go that allows users to track their investment portfolios across multiple currencies with real-time data integration.

## 🚀 Features

### Portfolio Management
- **Multiple Portfolios**: Create and manage multiple investment portfolios
- **Multi-Currency Support**: Track investments in different currencies with automatic conversion
- **Transaction Tracking**: Record buy, sell, and dividend transactions
- **Real-time Data**: Integration with Yahoo Finance API for live stock prices and data

### Currency Conversion
- **Automatic Currency Detection**: Automatically detects stock currencies from Yahoo Finance
- **Historical Exchange Rates**: Fetches historical exchange rates from the actual transaction date for accurate conversion
- **Smart Caching**: 24-hour cache for historical rates, 1-hour cache for current rates to optimize performance
- **Fallback System**: Uses current rates when historical rates are unavailable (marked with *)
- **160+ Currencies Supported**: Including major currencies like USD, EUR, GBP, JPY, CHF

### User Experience
- **User Authentication**: Secure registration and login system
- **Responsive Design**: Clean, modern UI built with Tabler CSS framework
- **Stock Search**: Advanced search functionality for stocks and securities
- **Interactive Charts**: Stock price and dividend charts powered by ApexCharts
- **Transaction Management**: Edit and delete transactions with full audit trail

## 🛠️ Technology Stack

- **Backend**: Go 1.24.4
- **Database**: SQLite with GORM ORM
- **Templates**: Templ templating engine
- **Frontend**: Tabler CSS framework
- **Charts**: ApexCharts
- **APIs**: Yahoo Finance, ExchangeRate API
- **Session Management**: Gorilla Sessions

## 📋 Prerequisites

- Go 1.24.4 or later
- Git

## 🔧 Installation

1. **Clone the repository**:
```bash
git clone <repository-url>
cd portfolio-tracker
```

2. **Install dependencies**:
```bash
go mod download
```

3. **Install Templ CLI** (for template generation):
```bash
go install github.com/a-h/templ/cmd/templ@latest
```

4. **Generate templates** (if needed):
```bash
templ generate
```

5. **Run the application**:
```bash
go run cmd/app/main.go
```

6. **Access the application**:
Open your browser and navigate to `http://localhost:8080`

## 📁 Project Structure

```
portfolio-tracker/
├── cmd/app/main.go              # Application entry point
├── internal/
│   ├── handler/                 # HTTP handlers
│   │   ├── api.go              # API endpoints
│   │   ├── auth.go             # Authentication handlers
│   │   ├── portfolio.go        # Portfolio management
│   │   └── pages.go            # Page handlers
│   ├── model/                   # Database models
│   │   ├── user.go             # User model
│   │   ├── portfolio.go        # Portfolio model
│   │   ├── activities.go       # Transaction model
│   │   └── models.go           # Yahoo Finance response models
│   ├── util/                    # Utility functions
│   │   ├── currency.go         # Currency conversion utilities
│   │   └── yahoo-utils.go      # Yahoo Finance API utilities
│   ├── session/                 # Session management
│   └── web/templates/          # Templ templates
├── docs/                        # Documentation
├── data/                        # SQLite database (auto-created)
├── go.mod                       # Go module file
└── README.md                    # This file
```

## 🎯 Usage

### Getting Started

1. **Register an Account**: Create a new user account or login with existing credentials
2. **Create a Portfolio**: Set up your first portfolio with a name, base currency, and description
3. **Add Transactions**: Start tracking your investments by adding buy, sell, or dividend transactions
4. **Search Stocks**: Use the search functionality to find stocks and add them to your portfolio
5. **Monitor Performance**: View your portfolio summary and track performance across currencies

### Currency Conversion

The application automatically:
- Detects the currency of stocks from Yahoo Finance
- Converts transaction amounts using historical exchange rates from the transaction date
- Displays both original and converted amounts for transparency
- Falls back to current rates when historical rates are unavailable (marked with *)
- Provides accurate historical portfolio valuation

### Stock Data

- **Real-time Prices**: Current stock prices and market data
- **Historical Charts**: Price movement over time
- **Dividend History**: Track dividend payments and history
- **Company Information**: Basic company details and metrics

## 🔑 API Endpoints

### Public Endpoints
- `GET /` - Dashboard
- `POST /user/register` - User registration
- `POST /user/login` - User login
- `POST /user/logout` - User logout

### Portfolio Management
- `GET /portfolio/{id}` - View portfolio details
- `POST /portfolio/create` - Create new portfolio
- `POST /portfolio/transaction` - Add transaction
- `POST /portfolio/transaction/edit` - Edit transaction
- `POST /portfolio/transaction/delete` - Delete transaction

### API Endpoints
- `GET /api/yahoo` - Get stock data from Yahoo Finance
- `GET /api/stocksearch` - Search for stocks
- `GET /api/yahoomaxdividends` - Get dividend data
- `POST /api/admin/clear-currency-cache` - Clear currency cache
- `GET /api/admin/currency-cache-info` - Get cache information

## 🌍 Currency Support

The application supports 160+ currencies including:

| Currency | Code | Symbol |
|----------|------|--------|
| US Dollar | USD | $ |
| Euro | EUR | € |
| British Pound | GBP | £ |
| Japanese Yen | JPY | ¥ |
| Swiss Franc | CHF | CHF |
| Canadian Dollar | CAD | C$ |
| Australian Dollar | AUD | A$ |
| And many more... | | |

## 🚦 Development

### Running Tests
```bash
go test ./internal/util/ -v
```

### Generating Templates
```bash
templ generate
```

### Database
The application uses SQLite and automatically creates the database file at `data/portfolio.db` on first run. Database migrations are handled automatically by GORM.

## 📊 Features in Detail

### Multi-Currency Portfolio Management
- Create portfolios in different base currencies
- Automatic historical currency conversion using transaction-date exchange rates
- Historical and real-time exchange rate fetching with smart caching
- Clear indication of converted vs. original amounts with fallback indicators

### Transaction Management
- Support for Buy, Sell, and Dividend transactions
- Automatic stock currency detection
- Edit and delete capabilities
- Transaction history and audit trail

### Stock Integration
- Yahoo Finance API integration
- Real-time stock prices and data
- Stock search functionality
- Price and dividend charts
- Company information display

## 🤝 Contributing

1. Fork the repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add some amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request

## 📝 License

This project is licensed under the MIT License - see the LICENSE file for details.

## 🔗 External APIs

- **Yahoo Finance**: Stock data, prices, and company information
- **ExchangeRate API**: Historical and current currency exchange rates (free tier, no API key required)
- **Frankfurter API**: Fallback for historical exchange rates when primary API is unavailable

## ⚠️ Disclaimer

This application is for educational and personal use only. Stock prices and financial data are provided for informational purposes. Always consult with financial professionals before making investment decisions.
