### Example Start Date Configuration Source: https://github.com/10mohi6/portfolio-backtest-python/blob/main/_autodocs/README.md Specifies the start date for the backtest period in YYYY-MM-DD format. ```python "2015-01-01" ``` -------------------------------- ### Install portfolio-backtest Source: https://github.com/10mohi6/portfolio-backtest-python/blob/main/README.md Install the portfolio-backtest library using pip. This command installs the core library. ```bash pip install portfolio-backtest ``` -------------------------------- ### Install Portfolio Backtest Source: https://github.com/10mohi6/portfolio-backtest-python/blob/main/_autodocs/README.md Install the portfolio-backtest and PyPortfolioOpt libraries using pip. ```bash pip install portfolio-backtest PyPortfolioOpt ``` -------------------------------- ### Install PyPortfolioOpt Source: https://github.com/10mohi6/portfolio-backtest-python/blob/main/README.md Install the PyPortfolioOpt library, which is a dependency for portfolio-backtest. Use pip for installation. ```bash pip install PyPortfolioOpt ``` -------------------------------- ### Full Portfolio Review Workflow Source: https://github.com/10mohi6/portfolio-backtest-python/blob/main/_autodocs/api-reference/usage-examples.md This example demonstrates a comprehensive workflow for portfolio analysis and optimization. It includes setting up a backtest with target return and CVaR constraints, running the backtest, analyzing performance metrics for both the user's portfolio and an optimized tangency portfolio, and calculating discrete share allocations for a given investment amount. Ensure the 'portfolio_backtest' library is installed and necessary data is available in the 'portfolio_analysis' directory. ```python from portfolio_backtest import Backtest from datetime import datetime import pprint # Define your current portfolio my_allocation = { "VTI": 0.50, # US large cap "VEA": 0.20, # International developed "AGG": 0.20, # Bonds "GLD": 0.10, # Gold } print("=" * 70) print("PORTFOLIO ANALYSIS AND OPTIMIZATION") print("=" * 70) print(f"\nDate: {datetime.now().strftime('%Y-%m-%d')}") print(f"\nYour Current Allocation:") pprint.pprint(my_allocation) # Run backtest print("\n" + "-" * 70) print("Running 5-year backtest (2019-2024)...") print("-" * 70) bt = Backtest( tickers=my_allocation, start="2019-01-01", end="2024-06-23", target_return=0.07, # 7% target target_cvar=0.03, # 3% CVaR constraint data_dir="portfolio_analysis" ) results = bt.run(plot=True) # Analyze results print("\n" + "-" * 70) print("RESULTS") print("-" * 70) your_portfolio = next(r for r in results if r['portfolio'] == 'Your Portfolio') tangency = next(r for r in results if r['portfolio'] == 'Tangency Portfolio') print(f"\nYour Portfolio Performance:") print(f" Expected Annual Return: {your_portfolio['Expected annual return']}") print(f" Annual Volatility: {your_portfolio['Annual volatility']}") print(f" Sharpe Ratio: {your_portfolio['Sharpe Ratio']}") print(f" Cumulative Return: {your_portfolio['Cumulative Return']}") print(f"\nOptimized Tangency Portfolio:") print(f" Expected Annual Return: {tangency['Expected annual return']}") print(f" Annual Volatility: {tangency['Annual volatility']}") print(f" Sharpe Ratio: {tangency['Sharpe Ratio']}") print(f" Cumulative Return: {tangency['Cumulative Return']}") print(f" Recommended Weights: {tangency['tickers']}") # Calculate discrete allocation for $100,000 print(f"\n" + "-" * 70) print("DISCRETE ALLOCATION FOR $100,000") print("-" * 70) allocation = bt.discrete_allocation(total_portfolio_value=100000) print(f"\nShares to purchase:") for ticker, shares in allocation['Discrete allocation'].items(): print(f" {ticker}: {shares} shares") print(f"\nFunds remaining: {allocation['Funds remaining']}") print("\n" + "=" * 70) print(f"Analysis complete. Charts saved to portfolio_analysis/") print("=" * 70) ``` -------------------------------- ### Minimal Backtest Configuration Source: https://github.com/10mohi6/portfolio-backtest-python/blob/main/_autodocs/api-reference/usage-examples.md Create a backtest with just a list of tickers and run it to get performance results. This is the simplest way to start using the library. ```python from portfolio_backtest import Backtest # Create backtest with just tickers bt = Backtest(tickers=["VTI", "AGG", "GLD"]) # Run backtest and get results results = bt.run() # Print results for portfolio in results: print(f"Portfolio: {portfolio['portfolio']}") print(f" Expected return: {portfolio['Expected annual return']}") print(f" Sharpe Ratio: {portfolio['Sharpe Ratio']}") print() ``` -------------------------------- ### Example Target Return Configuration Source: https://github.com/10mohi6/portfolio-backtest-python/blob/main/_autodocs/README.md Sets a target annual return for portfolio optimization, expressed as a decimal. ```python 0.10 ``` -------------------------------- ### Example Data Directory Configuration Source: https://github.com/10mohi6/portfolio-backtest-python/blob/main/_autodocs/README.md Specifies the directory where backtesting data will be stored or read from. ```python "backtest_data" ``` -------------------------------- ### Configure Backtest for Last 10 Years Source: https://github.com/10mohi6/portfolio-backtest-python/blob/main/_autodocs/configuration.md Specify a start date to retrieve historical data for a defined period, defaulting to the current date for the end. This example sets the start date to approximately 10 years prior. ```python Backtest( tickers=["VTI", "AGG"], start="2014-06-23", # 10 years back from current date end="" ) ``` -------------------------------- ### Minimal Backtest Example Source: https://github.com/10mohi6/portfolio-backtest-python/blob/main/_autodocs/README.md Create and run a basic backtest with specified tickers and print the expected annual return for each portfolio. ```python from portfolio_backtest import Backtest # Create and run backtest bt = Backtest(tickers=["VTI", "AGG", "GLD"]) results = bt.run() # View results for portfolio in results: print(f"{portfolio['portfolio']}: {portfolio['Expected annual return']}") ``` -------------------------------- ### Example Tickers Configuration Source: https://github.com/10mohi6/portfolio-backtest-python/blob/main/_autodocs/README.md Demonstrates how to specify tickers for backtesting. Can be a list of strings or a dictionary mapping ticker symbols to weights. ```python ["VTI", "AGG"] ``` ```python {"VTI": 0.32901, "AGG": 0.67099} ``` -------------------------------- ### Basic Backtest Run Source: https://github.com/10mohi6/portfolio-backtest-python/blob/main/README.md Initiates a basic backtest with a list of tickers. This is a straightforward way to get started with the library. ```python from portfolio_backtest import Backtest Backtest(tickers=["VTI", "AGG", "GLD"]).run() ``` -------------------------------- ### Optimization Target Configuration Example Source: https://github.com/10mohi6/portfolio-backtest-python/blob/main/_autodocs/configuration.md Configure targets for portfolio optimization. `target_return` is for semi-variance optimization, and `target_cvar` is for Conditional Value at Risk optimization. Both must be non-negative. ```python 0.1 ``` ```python 0.025 ``` -------------------------------- ### Data Directory Configuration Example Source: https://github.com/10mohi6/portfolio-backtest-python/blob/main/_autodocs/configuration.md Specify the directory for caching price data and saving plots. This path must be valid and will be created if it does not exist. ```python "." ``` ```python "backtest_data" ``` ```python "./output" ``` -------------------------------- ### Configure Backtest for a Specific Period Source: https://github.com/10mohi6/portfolio-backtest-python/blob/main/_autodocs/configuration.md Define both start and end dates to backtest over a precise historical interval. This example covers the period of the financial crisis. ```python Backtest( tickers=["VTI", "AGG"], start="2008-01-01", # Start of financial crisis end="2009-12-31" # End of recovery period ) ``` -------------------------------- ### Date String Format Examples Source: https://github.com/10mohi6/portfolio-backtest-python/blob/main/_autodocs/types.md Date strings must be in 'YYYY-MM-DD' format for Backtest initialization. Empty strings serve as default values with specific behaviors for start and end dates. ```text "2011-04-10" ``` ```text "2021-04-10" ``` ```text "2020-12-31" ``` -------------------------------- ### Date Range Configuration Example Source: https://github.com/10mohi6/portfolio-backtest-python/blob/main/_autodocs/configuration.md Set the start and end dates for the historical data. Dates should be in 'YYYY-MM-DD' format. An empty string for either uses default values. ```python "2011-04-10" ``` ```python "2021-04-10" ``` -------------------------------- ### Configure Backtest with Target Annual Return (7.5%) Source: https://github.com/10mohi6/portfolio-backtest-python/blob/main/_autodocs/configuration.md Specify a target annual return for semi-variance optimization. This example sets the target to 7.5% per year. ```python Backtest( tickers=["VTI", "AGG"], target_return=0.075 # 7.5% per year ) ``` -------------------------------- ### Data Caching Example Source: https://github.com/10mohi6/portfolio-backtest-python/blob/main/_autodocs/INDEX.md Demonstrates how data caching speeds up subsequent Backtest initializations. The first call downloads data, while calls within an hour reuse cached data. ```python # First call: downloads data (slow, ~10-30 seconds) bt1 = Backtest(tickers=["VTI", "AGG"]) # Second call within 1 hour: uses cache (fast, <1 second) bt2 = Backtest(tickers=["VTI", "AGG"]) ``` -------------------------------- ### Example Target CVaR Configuration Source: https://github.com/10mohi6/portfolio-backtest-python/blob/main/_autodocs/README.md Sets a target Conditional Value at Risk (CVaR) for portfolio optimization, expressed as a decimal. ```python 0.025 ``` -------------------------------- ### Example End Date Configuration Source: https://github.com/10mohi6/portfolio-backtest-python/blob/main/_autodocs/README.md Specifies the end date for the backtest period in YYYY-MM-DD format. ```python "2024-06-23" ``` -------------------------------- ### Configure Backtest with Target Annual Return (10%) Source: https://github.com/10mohi6/portfolio-backtest-python/blob/main/_autodocs/configuration.md Set a target annual return to enable semi-variance portfolio optimization, aiming to minimize downside risk for a specific return goal. This example targets 10% annual return. ```python Backtest( tickers=["VTI", "AGG", "GLD"], target_return=0.10 # 10% per year ) ``` -------------------------------- ### Discrete Allocation Result Example Source: https://github.com/10mohi6/portfolio-backtest-python/blob/main/_autodocs/types.md An example of the discrete allocation result dictionary, showing integer share counts for each ticker and remaining cash formatted as currency. ```python {"VTI": 28, "AGG": 21, "GLD": 9} ``` ```python "$109.45" ``` -------------------------------- ### Configure 5-Year Backtest Source: https://github.com/10mohi6/portfolio-backtest-python/blob/main/_autodocs/configuration.md Specify both start and end dates to perform a backtest over a fixed duration, such as the last five years. ```python Backtest( tickers=["VTI", "AGG"], start="2019-06-23", end="2024-06-23" ) ``` -------------------------------- ### Tickers Configuration Example Source: https://github.com/10mohi6/portfolio-backtest-python/blob/main/_autodocs/configuration.md Specify assets using a list of ticker symbols or a dictionary mapping symbols to their respective weights. If using a dictionary, the weights must sum to 1.0. ```python ["VTI", "AGG"] ``` ```python {"VTI": 0.6, "AGG": 0.4} ``` -------------------------------- ### Cache Hit Example Source: https://github.com/10mohi6/portfolio-backtest-python/blob/main/_autodocs/configuration.md Demonstrates how the library uses cached data. The first initialization downloads data, while subsequent calls within the cache expiration period load data quickly from a local CSV file. ```python from portfolio_backtest import Backtest # First call: downloads data (slow) bt1 = Backtest(tickers=["VTI", "AGG"], data_dir="cache") results1 = bt1.run() # Second call (within 1 hour): uses cached CSV (fast) bt2 = Backtest(tickers=["VTI", "AGG"], data_dir="cache") results2 = bt2.run() # Uses same cached data ``` -------------------------------- ### Configure Year-to-Date Backtest Source: https://github.com/10mohi6/portfolio-backtest-python/blob/main/_autodocs/configuration.md Set the start date to the beginning of the current year and use a dynamically determined end date (today) for a year-to-date backtest. ```python from datetime import datetime today = datetime.now().strftime("%Y-%m-%d") Backtest( tickers=["VTI", "AGG"], start="2024-01-01", end=today ) ``` -------------------------------- ### Provide Valid Tickers as List Source: https://github.com/10mohi6/portfolio-backtest-python/blob/main/_autodocs/errors.md This example demonstrates the correct way to initialize the Backtest class with a valid list of tickers. This avoids the 'Invalid Ticker Type' error. ```python from portfolio_backtest import Backtest # Valid: list bt = Backtest(tickers=["VTI", "AGG", "GLD"]) ``` -------------------------------- ### Configure Backtest for Maximum Available Data Source: https://github.com/10mohi6/portfolio-backtest-python/blob/main/_autodocs/configuration.md Leave both start and end dates empty to download the maximum available historical data from Yahoo Finance. ```python Backtest( tickers=["VTI", "AGG"], start="", end="" ) ``` -------------------------------- ### Direct Dependencies for setup.py Source: https://github.com/10mohi6/portfolio-backtest-python/blob/main/_autodocs/api-reference/module-overview.md Lists the primary Python packages required for the portfolio-backtest module, as specified in the setup.py file. ```python install_requires=[ "pandas", "yfinance", "matplotlib", "scikit-learn", ] ``` -------------------------------- ### Typical Portfolio Backtest Workflow Source: https://github.com/10mohi6/portfolio-backtest-python/blob/main/_autodocs/INDEX.md Illustrates the complete workflow for using the portfolio backtest library, from initialization and running the backtest to analyzing results and executing trades. ```python from portfolio_backtest import Backtest # 1. Initialize bt = Backtest( tickers={"VTI": 0.6, "AGG": 0.4}, start="2019-01-01", end="2024-06-23" ) # 2. Run results = bt.run(plot=True) # 3. Analyze for r in results: print(f"{r['portfolio']}: Sharpe {r['Sharpe Ratio']}") # 4. Get allocation allocation = bt.discrete_allocation(total_portfolio_value=100000) # 5. Execute for ticker, shares in allocation['Discrete allocation'].items(): print(f"BUY {shares} x {ticker}") ``` -------------------------------- ### Configure Backtest with Ticker-to-Weight Mapping Source: https://github.com/10mohi6/portfolio-backtest-python/blob/main/_autodocs/configuration.md Use a dictionary to map tickers to desired allocation weights. Weights must sum to 1.0. This enables the 'Your Portfolio' strategy and provides a benchmark for your allocation. ```python Backtest(tickers={"VTI": 0.6, "AGG": 0.25, "GLD": 0.15}) ``` -------------------------------- ### Backtest with User Portfolio Weights Source: https://github.com/10mohi6/portfolio-backtest-python/blob/main/_autodocs/configuration.md Sets up a Backtest using a dictionary to define specific weights for each ticker, representing a user-defined portfolio. The output includes comparisons against optimal portfolios. ```python from portfolio_backtest import Backtest bt = Backtest( tickers={ "VTI": 0.6, # 60% US total market "AGG": 0.25, # 25% bonds "GLD": 0.15, # 15% gold } ) results = bt.run() # Results include "Your Portfolio" vs. optimal portfolios for result in results: print(f"{result['portfolio']}: {result['Sharpe Ratio']}") ``` -------------------------------- ### Get Discrete Share Allocation Source: https://github.com/10mohi6/portfolio-backtest-python/blob/main/_autodocs/README.md Calculate the discrete share allocation for a given total portfolio value based on the backtest results. ```python allocation = bt.discrete_allocation(total_portfolio_value=10000) print(allocation['Discrete allocation']) # {'VTI': 28, 'AGG': 21, 'GLD': 9} ``` -------------------------------- ### Run Backtest Source: https://github.com/10mohi6/portfolio-backtest-python/blob/main/_autodocs/INDEX.md Executes all portfolio optimizations based on the initialized configuration. ```APIDOC ## Backtest.run() ### Description Execute all portfolio optimizations. ### Parameters - **plot** (bool) - Optional - Whether to generate plots for the results. Defaults to True. ### Returns - **list[dict]** - A list of dictionaries containing the results of the portfolio optimizations. ``` -------------------------------- ### Initialize Backtest with Target Return and CVaR Source: https://github.com/10mohi6/portfolio-backtest-python/blob/main/_autodocs/INDEX.md Configure a Backtest instance to optimize for a specific target annual return and a maximum Conditional Value at Risk (CVaR). ```python bt = Backtest( tickers=["VTI", "AGG", "GLD"], target_return=0.10, # 10% annual return target_cvar=0.025, # 2.5% CVaR limit ) results = bt.run() ``` -------------------------------- ### Initialize Backtest with Dictionary Weights Source: https://github.com/10mohi6/portfolio-backtest-python/blob/main/_autodocs/INDEX.md Initialize a Backtest instance with a dictionary specifying ticker weights. This allows for a user-defined portfolio allocation. ```python bt = Backtest(tickers={"VTI": 0.6, "AGG": 0.25, "GLD": 0.15}) results = bt.run() ``` -------------------------------- ### run Source: https://github.com/10mohi6/portfolio-backtest-python/blob/main/_autodocs/api-reference/backtest.md Executes the backtest by computing optimal portfolios and returns performance metrics. Optionally generates plots for visualization. ```APIDOC ## run(plot: bool = True) -> list ### Description Executes the backtest by computing optimal portfolios and returns performance metrics. If `plot` is `True`, generates pie charts and cumulative return line plots for all portfolios. ### Method `run` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **plot** (`bool`) - Optional - Default: `True` - If `True`, generates pie charts and cumulative return line plot for all portfolios. If `False`, skips plotting. ### Return Type `list[dict]` — List of dictionaries, one per portfolio strategy. Each dictionary contains: - `portfolio`: string name of the portfolio strategy - `tickers`: dict mapping ticker symbol to allocation weight - `Expected annual return`: string formatted as percentage (e.g., "9.6%") - `Annual volatility`: string formatted as percentage or empty string if not applicable - `Sharpe Ratio`: string formatted to 2 decimal places or empty string if not applicable - `Conditional Value at Risk`: string formatted as percentage or empty string if not applicable - `Cumulative Return`: string formatted as percentage ### Throws `ValueError` may be raised and the process exits if `target_return` is unreachable with the given assets. ### Example ```python from portfolio_backtest import Backtest # Basic run with default tickers bt = Backtest(tickers=["VTI", "AGG", "GLD"]) results = bt.run() # Iterate through results for portfolio_result in results: print(f"Portfolio: {portfolio_result['portfolio']}") print(f"Tickers: {portfolio_result['tickers']}") print(f"Expected return: {portfolio_result['Expected annual return']}") print(f"Sharpe Ratio: {portfolio_result['Sharpe Ratio']}") # Skip plotting for programmatic use results = bt.run(plot=False) ``` ```python # Advanced example with date range and target metrics bt = Backtest( tickers={ "VTI": 0.6, "AGG": 0.25, "GLD": 0.15, }, target_return=0.1, target_cvar=0.025, data_dir="backtest_data", start="2011-04-10", end="2021-04-10", ) results = bt.run(plot=True) for portfolio_result in results: print(portfolio_result) ``` ``` -------------------------------- ### Calculate Shares for Different Portfolio Sizes Source: https://github.com/10mohi6/portfolio-backtest-python/blob/main/_autodocs/api-reference/usage-examples.md Demonstrates how to calculate discrete allocation for various portfolio sizes, including calculating the percentage of portfolio utilization. This is useful for understanding how allocation changes with scale. ```python from portfolio_backtest import Backtest bt = Backtest( tickers={ "VTI": 0.6, "AGG": 0.25, "GLD": 0.15, } ) # Calculate for multiple portfolio sizes portfolio_sizes = [10000, 50000, 100000] for size in portfolio_sizes: allocation = bt.discrete_allocation(total_portfolio_value=size) total_invested = size - float(allocation['Funds remaining'].lstrip('$')) print(f"\n${size:,} Portfolio:") print(f" Shares: {allocation['Discrete allocation']}") print(f" Remaining: {allocation['Funds remaining']}") print(f" Utilization: {100 * total_invested / size:.1f}%") ``` -------------------------------- ### Get Discrete Allocation for $10,000 Source: https://github.com/10mohi6/portfolio-backtest-python/blob/main/_autodocs/api-reference/backtest.md Calculates the discrete number of shares to purchase for a $10,000 portfolio based on predefined ticker weights. Includes remaining funds. ```python from portfolio_backtest import Backtest bt = Backtest( tickers={ "VTI": 0.6, "AGG": 0.25, "GLD": 0.15, } ) # Get discrete allocation for $10,000 allocation = bt.discrete_allocation(total_portfolio_value=10000) print(allocation) # Output: { # 'Discrete allocation': {'VTI': 28, 'AGG': 21, 'GLD': 9}, # 'Funds remaining': '$109.45' # } ``` -------------------------------- ### Basic Backtest Configuration Source: https://github.com/10mohi6/portfolio-backtest-python/blob/main/_autodocs/configuration.md Initializes a Backtest with default settings, using a list of tickers. It downloads maximum available historical data and saves results to the current directory. ```python from portfolio_backtest import Backtest bt = Backtest(tickers=["VTI", "AGG", "GLD"]) results = bt.run() ``` -------------------------------- ### Get Discrete Allocation with Custom Weights Source: https://github.com/10mohi6/portfolio-backtest-python/blob/main/_autodocs/api-reference/backtest.md Calculates discrete share allocation for a $10,000 portfolio using custom ticker weights provided directly to the `discrete_allocation` method. ```python # Use custom weights (does not require tickers in constructor) allocation = bt.discrete_allocation( total_portfolio_value=10000, tickers={"AAPL": 0.5, "MSFT": 0.5} ) ``` -------------------------------- ### User Portfolio Comparison Source: https://github.com/10mohi6/portfolio-backtest-python/blob/main/_autodocs/README.md Run a backtest with a user-defined portfolio allocation and compare its Sharpe Ratio against optimized strategies. ```python bt = Backtest(tickers={"VTI": 0.6, "AGG": 0.25, "GLD": 0.15}) results = bt.run() # Results include "Your Portfolio" vs 6 optimized strategies for r in results: print(f"{r['portfolio']}: Sharpe={r['Sharpe Ratio']}") ``` -------------------------------- ### Backtest with Custom Date Range Source: https://github.com/10mohi6/portfolio-backtest-python/blob/main/_autodocs/configuration.md Configures a Backtest for a specific date range using start and end dates. The results are cached to a CSV file named after the tickers and dates. ```python from portfolio_backtest import Backtest bt = Backtest( tickers=["VTI", "AGG", "GLD"], start="2011-04-10", end="2021-04-10" ) results = bt.run() ``` -------------------------------- ### Package Structure Source: https://github.com/10mohi6/portfolio-backtest-python/blob/main/_autodocs/api-reference/module-overview.md Illustrates the directory structure of the portfolio_backtest package. ```text portfolio_backtest/ ├── __init__.py └── portfolio_backtest.py ``` -------------------------------- ### Configure Historical Period with Known End Date Source: https://github.com/10mohi6/portfolio-backtest-python/blob/main/_autodocs/configuration.md Define a specific historical start and end date to analyze a particular market event or period, like the financial crisis. ```python Backtest( tickers=["VTI", "AGG"], start="2008-09-15", # Lehman Brothers collapse end="2009-03-09" # Market bottom ) ``` -------------------------------- ### Complete Backtest Configuration Source: https://github.com/10mohi6/portfolio-backtest-python/blob/main/_autodocs/configuration.md Demonstrates a comprehensive Backtest configuration, specifying portfolio weights, date range, risk targets, and an output directory. The `run` method is called with plotting enabled. ```python from portfolio_backtest import Backtest bt = Backtest( tickers={ "VTI": 0.6, "AGG": 0.25, "GLD": 0.15, }, start="2011-04-10", end="2021-04-10", target_return=0.1, target_cvar=0.025, data_dir="backtest_output" ) results = bt.run(plot=True) # All options explicitly configured ``` -------------------------------- ### Create and Use Custom Data Directory Source: https://github.com/10mohi6/portfolio-backtest-python/blob/main/_autodocs/api-reference/usage-examples.md Demonstrates how to specify a custom directory for storing backtest data. This is useful for organizing data or using pre-existing datasets. ```python from portfolio_backtest import Backtest import os # Create and use custom data directory data_dir = "my_backtest_data" os.makedirs(data_dir, exist_ok=True) bt = Backtest( tickers=["VTI", "AGG", "GLD"], data_dir=data_dir ) results = bt.run(plot=True) # Check generated files import glob print(f"Files created in {data_dir}:") for file in glob.glob(f"{data_dir}/*"): print(f" {os.path.basename(file)}") ``` -------------------------------- ### Fixing 'Missing Ticker' Error: Tickers in Constructor Source: https://github.com/10mohi6/portfolio-backtest-python/blob/main/_autodocs/errors.md This example shows how to fix the 'Missing Ticker' error by providing tickers as a dictionary to the `Backtest` constructor. This allows `discrete_allocation` to function correctly. ```python from portfolio_backtest import Backtest bt = Backtest( tickers={ "VTI": 0.6, "AGG": 0.25, "GLD": 0.15, } ) # Now discrete_allocation() works allocation = bt.discrete_allocation(total_portfolio_value=10000) ``` -------------------------------- ### Get Share Counts for Discrete Allocation Source: https://github.com/10mohi6/portfolio-backtest-python/blob/main/_autodocs/INDEX.md Calculate the number of shares to buy for each ticker based on a total portfolio value using discrete allocation. This ensures whole shares are purchased. ```python allocation = bt.discrete_allocation(total_portfolio_value=50000) for ticker, shares in allocation['Discrete allocation'].items(): print(f"Buy {shares} shares of {ticker}") ``` -------------------------------- ### Method Call Graph for run() Source: https://github.com/10mohi6/portfolio-backtest-python/blob/main/_autodocs/api-reference/module-overview.md Illustrates the execution flow when the `run()` method is called, showing the sequence of internal method calls and optimization strategy executions. ```pseudocode run(plot=True) ├── If tickers is dict: │ └── _your_portfolio() │ ├── Constraint optimization │ └── _plot_pie(...) → saves pie chart ├── _tangency_portfolio() │ ├── EfficientFrontier.max_sharpe() │ └── _plot_pie(...) → saves pie chart ├── _minimum_variance_portfolio() │ ├── EfficientFrontier.min_volatility() │ └── _plot_pie(...) → saves pie chart ├── _hrp_portfolio() │ ├── HRPOpt.optimize() │ └── _plot_pie(...) → saves pie chart ├── _minimum_cvar_portfolio() │ ├── EfficientCVaR.min_cvar() │ └── _plot_pie(...) → saves pie chart ├── If target_return > 0: │ └── _semi_variance_portfolio() │ ├── EfficientSemivariance.efficient_return(target_return) │ └── _plot_pie(...) → saves pie chart ├── If target_cvar > 0: │ └── _return_maximize_cvar_portfolio() │ ├── EfficientCVaR.efficient_risk(target_cvar) │ └── _plot_pie(...) → saves pie chart ├── If plot=True: │ └── _cumulative_return() │ └── Saves cumulative-return.png └── Return self.result (list of dicts) ``` -------------------------------- ### Configure Backtest with Ticker List Source: https://github.com/10mohi6/portfolio-backtest-python/blob/main/_autodocs/configuration.md Use a list of ticker symbols for simple asset selection. The library optimizes allocation and generates standard portfolio strategies, excluding 'Your Portfolio'. ```python Backtest(tickers=["VTI", "AGG", "GLD"]) ``` -------------------------------- ### Price Data CSV File Naming Convention Source: https://github.com/10mohi6/portfolio-backtest-python/blob/main/_autodocs/types.md Generated price data CSV files follow the pattern {ticker1}-{ticker2}-{ticker3}-{start}-{end}.csv. Empty start/end dates are represented by double hyphens. ```text {ticker1}-{ticker2}-{ticker3}-{start}-{end}.csv ``` ```text VTI-AGG-GLD--.csv ``` ```text VTI-AGG-GLD-2011-04-10-2021-04-10.csv ``` -------------------------------- ### Fixing 'Missing Ticker' Error: Tickers in Method Call Source: https://github.com/10mohi6/portfolio-backtest-python/blob/main/_autodocs/errors.md This example demonstrates an alternative fix for the 'Missing Ticker' error by passing tickers as a dictionary directly to the `discrete_allocation` method. This is useful when the constructor uses a list of tickers. ```python from portfolio_backtest import Backtest bt = Backtest(tickers=["VTI", "AGG", "GLD"]) # Pass weights to method allocation = bt.discrete_allocation( total_portfolio_value=10000, tickers={ "VTI": 0.6, "AGG": 0.25, "GLD": 0.15, } ) ``` -------------------------------- ### Specify Data Directory for Backtest Source: https://github.com/10mohi6/portfolio-backtest-python/blob/main/_autodocs/configuration.md Configure the 'data_dir' parameter to set the filesystem directory for storing downloaded price data and generated visualizations. The directory will be created if it does not exist. Price data is cached in CSV files and refreshed if older than one hour. ```python Backtest( tickers=["VTI", "AGG"], data_dir="backtest_data" # Creates ./backtest_data/ ) ``` ```python Backtest( tickers=["VTI", "AGG"], data_dir="/tmp/backtest_output" ) ``` ```python Backtest( tickers=["VTI", "AGG"], data_dir="." ) ``` ```python Backtest( tickers=["VTI", "AGG"], data_dir="results/backtest_2024" # Creates ./results/backtest_2024/ ) ``` -------------------------------- ### Portfolio Optimization Methods Source: https://github.com/10mohi6/portfolio-backtest-python/blob/main/_autodocs/api-reference/module-overview.md Lists the various portfolio optimization strategies available through the pypfopt library, including their algorithms and corresponding methods. ```markdown | Strategy | Algorithm | Method | |---|---|---| | Tangency Portfolio | Efficient Frontier | `EfficientFrontier.max_sharpe()` | | Minimum Variance | Efficient Frontier | `EfficientFrontier.min_volatility()` | | HRP Portfolio | Hierarchical Risk Parity | `HRPOpt.optimize()` | | Minimum CVaR | Efficient CVaR | `EfficientCVaR.min_cvar()` | | Return Max CVaR | Efficient CVaR | `EfficientCVaR.efficient_risk(target_cvar)` | | Semi Variance | Efficient Semivariance | `EfficientSemivariance.efficient_return(target)` | ``` -------------------------------- ### Create Data Directory Safely Source: https://github.com/10mohi6/portfolio-backtest-python/blob/main/_autodocs/configuration.md Ensures the parent directory for backtest results exists before initializing the Backtest object. Use `os.makedirs` with `exist_ok=True` to prevent errors if the directory already exists. ```python import os from portfolio_backtest import Backtest # Ensure parent directory exists data_dir = "my_backtest_results" os.makedirs(data_dir, exist_ok=True) bt = Backtest( tickers=["VTI", "AGG"], data_dir=data_dir ) ``` -------------------------------- ### Backtest Initialization Source: https://github.com/10mohi6/portfolio-backtest-python/blob/main/_autodocs/INDEX.md Initializes the Backtest class with specified configuration parameters for backtesting. ```APIDOC ## Backtest.__init__() ### Description Initialize backtest with configuration. ### Parameters - **tickers** (list[str] or dict[str, float]) - Required - A list of ticker symbols or a dictionary of ticker symbols with their corresponding weights. - **start** (str) - Optional - The start date for the backtest in YYYY-MM-DD format. Defaults to "". - **end** (str) - Optional - The end date for the backtest in YYYY-MM-DD format. Defaults to "". - **target_return** (float) - Optional - The target annual return as a decimal. Defaults to 0. - **target_cvar** (float) - Optional - The target Conditional Value at Risk (CVaR) limit as a decimal. Defaults to 0. - **data_dir** (str) - Optional - The directory to store backtest data. Defaults to ".". ``` -------------------------------- ### Compare User Allocation vs. Optimized Portfolio Source: https://github.com/10mohi6/portfolio-backtest-python/blob/main/_autodocs/api-reference/usage-examples.md Compares a user-defined portfolio allocation against the tangency portfolio. Requires the Backtest class and a dictionary of tickers with weights. ```python from portfolio_backtest import Backtest # Your current allocation my_portfolio = { "VTI": 0.6, # 60% US stocks "AGG": 0.25, # 25% bonds "GLD": 0.15, # 15% gold } bt = Backtest(tickers=my_portfolio) results = bt.run() # Extract your portfolio and tangency portfolio for comparison your_portfolio = next(r for r in results if r['portfolio'] == 'Your Portfolio') tangency = next(r for r in results if r['portfolio'] == 'Tangency Portfolio') print("YOUR PORTFOLIO vs OPTIMIZED") print("-" * 50) print(f"Your allocation: {your_portfolio['tickers']}") print(f"Expected return: {your_portfolio['Expected annual return']}") print(f"Sharpe Ratio: {your_portfolio['Sharpe Ratio']}") print(f"Cumulative Return: {your_portfolio['Cumulative Return']}") print() print(f"Optimized allocation: {tangency['tickers']}") print(f"Expected return: {tangency['Expected annual return']}") print(f"Sharpe Ratio: {tangency['Sharpe Ratio']}") print(f"Cumulative Return: {tangency['Cumulative Return']}") # Calculate difference your_return = float(your_portfolio['Expected annual return'].rstrip('%')) opt_return = float(tangency['Expected annual return'].rstrip('%')) print(f"\nReturn difference: {opt_return - your_return:.1f}% annually") ``` -------------------------------- ### Provide Valid Tickers as Dictionary Source: https://github.com/10mohi6/portfolio-backtest-python/blob/main/_autodocs/errors.md This code shows how to correctly initialize the Backtest class using a dictionary for tickers, including allocation weights. This is a valid input type. ```python from portfolio_backtest import Backtest # Valid: dictionary bt = Backtest( tickers={"VTI": 0.6, "AGG": 0.25, "GLD": 0.15} ) ``` -------------------------------- ### Run Backtest with Custom Parameters Source: https://github.com/10mohi6/portfolio-backtest-python/blob/main/_autodocs/api-reference/backtest.md Executes a backtest with a specified date range, target return, target CVaR, and custom ticker weights. Plotting is enabled. ```python # Advanced example with date range and target metrics bt = Backtest( tickers={ "VTI": 0.6, "AGG": 0.25, "GLD": 0.15, }, target_return=0.1, target_cvar=0.025, data_dir="backtest_data", start="2011-04-10", end="2021-04-10", ) results = bt.run(plot=True) for portfolio_result in results: print(portfolio_result) ``` -------------------------------- ### Method Call Graph for discrete_allocation() Source: https://github.com/10mohi6/portfolio-backtest-python/blob/main/_autodocs/api-reference/module-overview.md Shows the execution flow when the `discrete_allocation()` method is invoked, detailing the steps for obtaining prices and performing greedy portfolio allocation. ```pseudocode discrete_allocation(total_portfolio_value, tickers) ├── Get latest prices via _df or parameter ├── DiscreteAllocation.greedy_portfolio() └── Return allocation dict ``` -------------------------------- ### Tickers Input: Dictionary Format Source: https://github.com/10mohi6/portfolio-backtest-python/blob/main/_autodocs/types.md Use a dictionary mapping ticker symbols to allocation weights when initializing the Backtest constructor. Weights must sum to exactly 1.0. This format generates an additional 'Your Portfolio' strategy. ```python tickers: dict[str, float] ``` ```python tickers={ "VTI": 0.6, "AGG": 0.25, "GLD": 0.15, } ``` -------------------------------- ### Compare Multiple Time Periods Source: https://github.com/10mohi6/portfolio-backtest-python/blob/main/_autodocs/api-reference/usage-examples.md Run backtests for predefined periods and print the return and Sharpe Ratio for the Tangency Portfolio. This is useful for understanding how different market conditions affect portfolio performance. ```python from portfolio_backtest import Backtest periods = [ ("2008-2009 Crisis", "2008-01-01", "2009-12-31"), ("2010-2015 Recovery", "2010-01-01", "2015-12-31"), ("2015-2020 Bull", "2015-01-01", "2020-12-31"), ("2020-2024 Recent", "2020-01-01", "2024-06-23"), ] tickers = ["VTI", "AGG", "GLD"] for period_name, start, end in periods: bt = Backtest( tickers=tickers, start=start, end=end, data_dir="period_analysis" ) results = bt.run(plot=False) # Get tangency portfolio performance tangency = next(r for r in results if r['portfolio'] == 'Tangency Portfolio') return_pct = tangency['Expected annual return'] sharpe = tangency['Sharpe Ratio'] print(f"{period_name:25} | Return: {return_pct:>6} | Sharpe: {sharpe:>5}") ``` -------------------------------- ### Custom Weights for Discrete Allocation Source: https://github.com/10mohi6/portfolio-backtest-python/blob/main/_autodocs/api-reference/usage-examples.md Shows how to apply custom asset weights to the discrete allocation calculation, even when the Backtest object is initialized with a list of tickers. This allows for flexible portfolio construction. ```python from portfolio_backtest import Backtest # Initialize with list (no weights) bt = Backtest(tickers=["VTI", "AGG", "GLD"]) # Can still use discrete_allocation with custom weights my_weights = { "VTI": 0.7, # Prefer stocks "AGG": 0.2, # Less bonds "GLD": 0.1, # Less gold } allocation = bt.discrete_allocation( total_portfolio_value=25000, tickers=my_weights ) print("Custom allocation for $25,000:") print(allocation['Discrete allocation']) print(f"Remaining: {allocation['Funds remaining']}") ``` -------------------------------- ### Backtest Class Constructor Source: https://github.com/10mohi6/portfolio-backtest-python/blob/main/_autodocs/api-reference/backtest.md Initializes the Backtest class with specified parameters for portfolio backtesting. ```APIDOC ## Backtest Class Constructor ### Description Initializes the Backtest class with specified parameters for portfolio backtesting and optimization. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Constructor Signature ```python Backtest( *, tickers: Any, start: str = "", end: str = "", target_return: float = 0, target_cvar: float = 0, data_dir: str = "." ) ``` ### Parameters Details - **tickers** (`list[str]` or `dict[str, float]`) - Required - Ticker symbols as a list of strings or a dict mapping ticker symbols to allocation weights (values must sum to 1.0 when using dict). - **start** (`str`) - Optional - Start date for historical data in format `YYYY-MM-DD`. Empty string downloads maximum available data. - **end** (`str`) - Optional - End date for historical data in format `YYYY-MM-DD`. Empty string defaults to current date. - **target_return** (`float`) - Optional - Target annual return as decimal (e.g., `0.1` for 10%) for semi-variance portfolio optimization. Set to 0 to skip semi-variance portfolio. - **target_cvar** (`float`) - Optional - Target Conditional Value at Risk as decimal (e.g., `0.025` for 2.5%) for CVaR optimization. Set to 0 to skip CVaR portfolio. - **data_dir** (`str`) - Optional - Directory for storing downloaded price data and generated plots. Created automatically if not present. ```