Sharpe Ratio Optimizer

GPT4 Generated Code Summary

This code performs financial analysis and portfolio optimization using historical stock data from Yahoo Finance. Here's a summary of its main components and steps:

  1. Import Libraries: It imports necessary libraries: yfinance for fetching financial data, numpy and scipy.optimize for numerical operations and optimization, matplotlib.pyplot for plotting, and datetime for date manipulations.

  2. Define Stock Tickers and Lookback Period: The script defines a list of stock tickers (tickers) and sets a lookback period (lookback) of 400 days.

  3. Fetch Historical Stock Data: It fetches adjusted close prices for the defined tickers from Yahoo Finance starting from a date calculated based on the lookback period.

  4. Split Data into Two Halves: The historical data is split into two halves – the first half covers the initial 200 days, and the second half covers the remaining period.

  5. Calculate Daily Returns for the First Half: It computes daily returns for the stocks in the first half of the data.

  6. Define Optimization Function: A function calculate_sharpe_ratio is defined to calculate the negative Sharpe ratio of a portfolio. The Sharpe ratio is a measure of risk-adjusted return.

  7. Optimization Constraints and Bounds: It sets up constraints (portfolio weights sum to 1) and bounds (weights are between 0 and 1) for the optimization.

  8. Initial Guess for Optimization: An initial guess for the portfolio weights is provided (equally distributed across all stocks).

  9. Optimize Portfolio for the First Half: The script uses the minimize function from scipy.optimize to find the portfolio weights that minimize the negative Sharpe ratio based on the first half's data.

  10. Apply Optimized Weights to Second Half: It calculates the daily returns for the second half using the optimized portfolio weights.

  11. Plotting Cumulative Returns: The script plots cumulative returns for both halves of the data, using the optimized portfolio weights, to visualize the performance of the optimized portfolio.

The code essentially aims to find an optimized portfolio based on historical returns and then tests the performance of this portfolio in a subsequent time period.