Answered step by step
Verified Expert Solution
Question
1 Approved Answer
temp_df = pd.read_csv(fhttps://query1.finance.yahoo.com/v8/finance/chart/symbol}?' f'period1={start_date}&period2={end_date}&interval=1d&events=history') risk_free_df = pd.read_csv(f'https://finance.yahoo.com/quote/%5EIRX/history?p=%5EIRX' f'period1={start_date}&period2={end_date}&interval=1d&events=history') have problem please import yfianance as yf and use yahoo finance package to fix the problem This
temp_df = pd.read_csv(f"https://query1.finance.yahoo.com/v8/finance/chart/symbol}?' f'period1={start_date}&period2={end_date}&interval=1d&events=history')
risk_free_df = pd.read_csv(f'https://finance.yahoo.com/quote/%5EIRX/history?p=%5EIRX' f'period1={start_date}&period2={end_date}&interval=1d&events=history')
have problem please import yfianance as yf and use yahoo finance package to fix the problem This is the orginal programming mport pandas as pd import numpy as np import matplotlib.pyplot as plt # Step 1: Download daily prices for the five stocks symbols = ['AAPL', 'AMZN', 'GOOG', 'MSFT', 'TSLA'] start_date = '2010-01-01' end_date = '2022-12-31' prices_df = pd.DataFrame() for symbol in symbols: temp_df = pd.read_csv(f"https://query1.finance.yahoo.com/v8/finance/chart/symbol}?' f'period1={start_date}&period2={end_date}&interval=1d&events=history') temp_df = temp_df[['Date', 'Close']].rename(columns={'Close': symbol}).set_index('Date') prices_df = pd.concat([prices_df, temp_df], axis=1, sort=True) # Step 2: Calculate daily returns of the stocks returns_df = np.log(prices_df) - np.log(prices_df.shift(1)) returns_df.dropna(inplace=True) # Step 3: Download risk-free rates risk_free_df = pd.read_csv(f'https://finance.yahoo.com/quote/%5EIRX/history?p=%5EIRX' f'period1={start_date}&period2={end_date}&interval=1d&events=history') risk_free_df['Date'] = pd.to_datetime(risk_free_df['Date']) risk_free_df.set_index('Date', inplace=True) risk_free_df = risk_free_df.resample('D').last().ffill().pct_change() risk_free_df = risk_free_df * 252 # Annualize risk-free rates risk_free_df.dropna(inplace=True) # Step 4: Compute excess returns excess_returns_df = returns_df.sub(risk_free_df['^IRX'], axis=0) # Step 5: Allocate portfolio based on 200-day moving average moving_averages_df = prices_df.rolling(window=200).mean().shift(1) portfolio_weights_df = np.where(prices_df > moving_averages_df, 0.2, 0) portfolio_weights_df['Cash'] = 1 - portfolio_weights_df.sum(axis=1) portfolio_returns_df = (excess_returns_df * portfolio_weights_df).sum(axis=1) # Step 6: Compute mean and standard deviation of the portfolio portfolio_mean = portfolio_returns_df.mean() portfolio_std = portfolio_returns_df.std() print(f"Mean of the portfolio: {portfolio_mean:.6f}") print(f"Standard deviation of the portfolio: {portfolio_std:.6f}") # Step 7: Compute mean and standard deviation of equally-weighted portfolio equal_weights_df = pd.DataFrame(np.ones((len(prices_df), len(symbols))) / len(symbols), index=prices_df.index, columns=symbols) equal_returns_df = (excess_returns_df * equal_weights_df).sum(axis=1) equal_mean = equal_returns_df.mean() equal_std = equal_returns_df.std() print(f" Mean of equally-weighted portfolio: {equal_mean:.6f}") print(f"Standard deviation of equally-weighted portfolio: {equal_std:.6f}") # Step 8: Plot cumulative performance of both strategies portfolio_cumulative_returns = (1 + portfolio_returns_df).cumprod() equal_cumulative_returns = (1 + equal_returns_df).cumprod() plt.plot(portfolio_cumulative_returns, label='Portfolio') plt.plot(equal_cumulative_returns, label='Equal weights') plt.legend() plt.title('Cumulative Returns of Portfolio Strategies') plt.xlabel('Date') plt.ylabel('Cumulative Returns') plt.show() portfolio_cumulative_returns = (1 + portfolio_returns_df).cumprod() equal_cumulative_returns = (1 + equal_returns_df).cumprod() plt.plot(portfolio_cumulative_returns, label='Portfolio') plt.plot(equal_cumulative_returns, label='Equal weights') plt.legend() plt.title('Cumulative Returns of Portfolio Strategies') plt.xlabel('Date') plt.ylabel('Cumulative Returns') plt.show()
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started