KnapSackCapital – The only open-source portfolio balancer that uses a multi-dimensional Knapsack DP to guarantee optimal discrete allocations. Perfect for retail investors who want Markowitz-level optimization without the black-box math.
- Dynamic Programming – guaranteed optimal allocation over a discrete grid of percentages.
- Risk‑Aware – you set a maximum volatility tolerance; the algorithm maximises return under that constraint.
- Flexible Input – load asset data from a JSON file or use the built‑in random generator.
- Clean Output – displays allocations, expected return, volatility, and Sharpe ratio.
- Short & Readable – entire logic fits in one file, well‑commented and type‑hinted.
- Each asset is defined by its expected return and volatility (standard deviation).
- The investor provides a risk tolerance (maximum acceptable volatility) and a budget.
- Allocations are considered in discrete steps (e.g., 5% increments).
- A multi‑dimensional DP table
dp[percentage][risk]stores the maximum return achievable for each combination. - After processing all assets, the algorithm backtracks to recover the optimal allocation.
git clone https://github.com/theinsidecoder
cd dynafolio
pip install -r requirements.txt
Usage
bash
# Use a JSON file
python main.py --assets sample_assets.json --budget 100000 --risk_tolerance 0.12
# Or generate random assets
python main.py --num_assets 8 --budget 50000 --risk_tolerance 0.15 --step 5
Sample JSON Format (sample_assets.json)
json
[
{"name": "AAPL", "return": 0.18, "volatility": 0.22},
{"name": "MSFT", "return": 0.16, "volatility": 0.20},
{"name": "GOOGL", "return": 0.14, "volatility": 0.19},
{"name": "AMZN", "return": 0.20, "volatility": 0.25},
{"name": "TSLA", "return": 0.25, "volatility": 0.35}
]
Example Output
text
Optimal Allocation:
AAPL 25.0%
MSFT 30.0%
GOOGL 20.0%
AMZN 15.0%
TSLA 10.0%
Portfolio Statistics:
Expected Return: 17.45%
Volatility: 14.92%
Sharpe Ratio: 1.04 (risk‑free = 2.0%)
Total Investment: $100,000
Repository
Name: dynafolio
Description: Automated Financial Portfolio Balancer using Dynamic Programming – optimally allocate funds to maximise return under a volatility constraint.
License
MIT
text
---
### 3. `requirements.txt`
numpy
text
*(We only need `numpy` for optional performance; the core algorithm uses pure Python.)*
---
### 4. `sample_assets.json`
```json
[
{"name": "AAPL", "return": 0.18, "volatility": 0.22},
{"name": "MSFT", "return": 0.16, "volatility": 0.20},
{"name": "GOOGL", "return": 0.14, "volatility": 0.19},
{"name": "AMZN", "return": 0.20, "volatility": 0.25},
{"name": "TSLA", "return": 0.25, "volatility": 0.35}
]