Sign up, and you can customize which countdowns you see. Sign up
Jul 24, 2024
4:03:01pm
Dark Forest Green All-American
Does this python code work?
pip install pandas numpy yfinance
import pandas as pd
import yfinance as yf

# List of sector ETFs (some ETFs were introduced later)
etfs = ["XLK", "XLV", "XLF", "XLY", "XLP", "XLE", "XLI", "XLU", "XLB", "XLRE"]

# Download historical data for the ETFs from 1992-01-01 to 2021-12-31
start_date = "1992-01-01"
end_date = "2021-12-31"
data = yf.download(etfs, start=start_date, end=end_date)

# Adjusted Close prices for total return calculations (including dividends)
adj_close = data["Adj Close"]

# Initialize investment
initial_investment = 1000
investment = {etf: initial_investment for etf in etfs}
portfolio_value = [sum(investment.values())]

# Perform annual rebalancing
for year in range(1992, 2021):
yearly_returns = adj_close[str(year):str(year+1)].pct_change().sum()
best_performer = yearly_returns.idxmax()
worst_performer = yearly_returns.idxmin()

# Sell best performer and buy worst performer
cash = investment[best_performer] * (1 + yearly_returns[best_performer])
investment[best_performer] = 0
investment[worst_performer] += cash

# Record portfolio value at the end of the year
portfolio_value.append(sum(investment[etf] * (1 + yearly_returns[etf]) for etf in etfs))

# Calculate final portfolio value
final_value = portfolio_value[-1]

# Output the results
print(f"Final portfolio value after 30 years: ${final_value:.2f}")
Dark Forest Green
Previous username
BYUALWAYSNUM1
Bio page
Dark Forest Green
Joined
Oct 18, 2011
Last login
Dec 20, 2024
Total posts
27,857 (948 FO)
Messages
Author
Time

Posting on CougarBoard

In order to post, you will need to either sign up or log in.