Created
September 7, 2023 20:31
-
-
Save 18182324/600a4e91efd0d09bb11527c74cb7f7e1 to your computer and use it in GitHub Desktop.
Portfolio Allocatgion 1_N Factor Investing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import yfinance as yf | |
import pandas as pd | |
import numpy as np | |
import matplotlib.pyplot as plt | |
# Define a list of stock tickers for the portfolio | |
tickers = ['AAPL', 'MSFT', 'GOOGL', 'AMZN', 'TSLA'] | |
# Set the date range for historical data | |
start_date = '2010-01-01' | |
end_date = '2020-12-31' | |
# Download historical stock price data from Yahoo Finance | |
data = yf.download(tickers, start=start_date, end=end_date)['Adj Close'] | |
# Calculate daily returns | |
returns = data.pct_change().dropna() | |
# Define the number of assets in the portfolio | |
num_assets = len(tickers) | |
# Define initial portfolio weights (e.g., equal weights) | |
initial_weights = np.array([1.0 / num_assets] * num_assets) | |
# Define initial investment amount | |
initial_investment = 1000000 # $1,000,000 | |
# Create an empty DataFrame to store portfolio values | |
portfolio_values = pd.DataFrame(index=returns.index, columns=['Portfolio Value']) | |
# Initialize portfolio value with the initial investment | |
portfolio_values.iloc[0] = initial_investment | |
# Simulate portfolio construction and rebalancing | |
for i in range(1, len(returns)): | |
# Calculate portfolio values at each time step | |
portfolio_values.iloc[i] = portfolio_values.iloc[i - 1] * (1 + returns.iloc[i]) | |
# Calculate portfolio returns | |
portfolio_returns = (portfolio_values['Portfolio Value'] / initial_investment) - 1 | |
# Calculate portfolio volatility (standard deviation of returns) | |
portfolio_volatility = portfolio_returns.std() | |
# Calculate the Sharpe ratio (assuming a risk-free rate of 0%) | |
risk_free_rate = 0.0 | |
sharpe_ratio = (portfolio_returns.mean() - risk_free_rate) / portfolio_volatility | |
# Print portfolio performance metrics | |
print("Portfolio Performance Metrics:") | |
print("Cumulative Returns:", portfolio_returns[-1]) | |
print("Annualized Portfolio Return:", portfolio_returns.mean() * 252) # Assuming 252 trading days per year | |
print("Annualized Portfolio Volatility (Risk):", portfolio_volatility * np.sqrt(252)) | |
print("Sharpe Ratio:", sharpe_ratio) | |
# Plot portfolio value over time | |
plt.figure(figsize=(12, 6)) | |
plt.plot(portfolio_values.index, portfolio_values['Portfolio Value'], label='Portfolio Value') | |
plt.xlabel('Date') | |
plt.ylabel('Portfolio Value') | |
plt.title('Portfolio Value Over Time') | |
plt.legend() | |
plt.grid(True) | |
plt.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment