Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Traceback (most recent call last): File pandas_libstslibsparsing.pyx, line 440, in pandas._libs.tslibs.parsing.parse_datetime_string_with_reso File pandas_libstslibsparsing.pyx, line 649, in pandas._libs.tslibs.parsing.dateutil_parse ValueError: Unknown datetime string format, unable to parse:

Traceback (most recent call last): File "pandas\_libs\tslibs\parsing.pyx", line 440, in pandas._libs.tslibs.parsing.parse_datetime_string_with_reso File "pandas\_libs\tslibs\parsing.pyx", line 649, in pandas._libs.tslibs.parsing.dateutil_parse ValueError: Unknown datetime string format, unable to parse: ^IRX During handling of the above exception, another exception occurred:  raise KeyError(key) from err KeyError: '^IRX' How to solve the problem? import pandas as pd import numpy as np import matplotlib.pyplot as plt import yfinance as yf # 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 = yf.download(symbols, start=start_date, end=end_date)['Adj Close'] # 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 = yf.download('^IRX', start=start_date, end=end_date)['Adj Close'] 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()

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Oracle 11G SQL

Authors: Joan Casteel

2nd Edition

1133947360, 978-1133947363

More Books

Students also viewed these Databases questions

Question

Explain the method signature syntax on design classes.

Answered: 1 week ago

Question

a. What is the immediate effect on the balance sheet? LOP8

Answered: 1 week ago