Untitled

 avatar
unknown
plain_text
a month ago
5.5 kB
5
Indexable
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# Assume result_df and prices are already loaded from your simulation code.
# Load Benchmark data from Excel (adjust file path as needed)
benchmark_filepath = r"\\asiapac.nom\data\MUM\IWM\India_IWM_IPAS\Reet\Momentum Strategy\Research Paper Implementation\Research Paper Implementation.xlsx"
benchmark = pd.read_excel(benchmark_filepath, sheet_name='Benchmark', index_col=0)
benchmark.index = pd.to_datetime(benchmark.index)
benchmark.columns = ['Benchmark']


# Define colors array (example colors, change as needed)
colors = ['#CA2420', '#737373', '#80A9AE', '#00305C', '#80003F', '#CC8D19', '#AEADB0', '#00713B', '#DCB940', '#00677A', '#9A9500', '#8F3336', '#5A7400', '#B0CAD0', '#6077A3', '#995E7A', '#DCB172', '#D4D4D4', '#6B9977', '#E5CC89', '#649CB3', '#B7B56B', '#BF8B79', '#8F9D66', '#000000']

###############################################################################
# 1. Cumulative Returns: Strategy vs Benchmark
###############################################################################

# Compute cumulative returns for the strategy.
# We assume the 'Total AUM' column in result_df represents the strategy value.
strategy_cumret = result_df['Total AUM'] / result_df['Total AUM'].iloc[0] - 1

# For the benchmark, assume we started investing on the same start date as the simulation.
benchmark = benchmark.reindex(result_df.index).ffill()  # align benchmark with simulation dates
benchmark_cumret = benchmark['Benchmark'] / benchmark['Benchmark'].iloc[0] - 1
result_df = result_df.set_index("Date")
plt.figure(figsize=(10, 6))
plt.plot(result_df.index, strategy_cumret, label='Strategy', color=colors[0])
plt.plot(result_df.index, benchmark_cumret, label='Benchmark', color=colors[1])
plt.xlabel('Date')
plt.ylabel('Cumulative Return')
plt.title('Cumulative Returns: Strategy vs Benchmark')
plt.legend()
plt.grid(True)
plt.tight_layout()
plt.show()

###############################################################################
# 2. Correlation Matrix of Historic Prices
###############################################################################

# Compute correlation matrix of the historical prices DataFrame.
corr_matrix = prices.corr().round(2)

# Plot correlation matrix as a heatmap.
fig, ax = plt.subplots(figsize=(8, 6))
cax = ax.matshow(corr_matrix, cmap='coolwarm')
plt.xticks(range(len(corr_matrix.columns)), corr_matrix.columns, rotation=45)
plt.yticks(range(len(corr_matrix.index)), corr_matrix.index)
# Annotate the heatmap with correlation values
for (i, j), val in np.ndenumerate(corr_matrix):
    ax.text(j, i, f'{val:.2f}', va='center', ha='center', color='black')
fig.colorbar(cax)
plt.title('Correlation Matrix of Historic Prices', pad=20)
plt.tight_layout()
plt.show()

###############################################################################
# 3. Drawdown Plot: Strategy vs Benchmark
###############################################################################

def compute_drawdown(series):
    """Compute drawdown series given cumulative returns series."""
    cumulative = series + 1  # convert return to equity curve (starting at 1)
    rolling_max = cumulative.cummax()
    drawdown = (cumulative - rolling_max) / rolling_max
    return drawdown

strategy_drawdown = compute_drawdown(strategy_cumret).round(2)
benchmark_drawdown = compute_drawdown(benchmark_cumret).round(2)

plt.figure(figsize=(10, 6))
plt.plot(result_df.index, strategy_drawdown, label='Strategy Drawdown', color=colors[2])
plt.plot(result_df.index, benchmark_drawdown, label='Benchmark Drawdown', color=colors[3])
plt.xlabel('Date')
plt.ylabel('Drawdown')
plt.title('Drawdown: Strategy vs Benchmark')
plt.legend()
plt.grid(True)
plt.tight_layout()
plt.show()

###############################################################################
# 4. 100% Stacked Area Chart: Cash + Notional of Each Asset
###############################################################################

# We assume that result_df contains a 'CASH' column and for each asset there is a
# 'notional_{ticker}' column. Here we extract those columns.
# For example, if your tickers are: 'SPY US Equity', 'TLT US Equity', 'GLD US Equity', 'SHV US Equity'
tickers = ['SPY US Equity', 'TLT US Equity', 'GLD US Equity', 'SHV US Equity', 'HYG US Equity', 'VNQ US Equity']
notional_cols = [f'notional_{ticker}' for ticker in tickers]
# Include CASH as another component
components = ['CASH'] + notional_cols

# Compute percentages for each component relative to Total AUM.
stack_data = result_df[components].div(result_df['Total AUM'], axis=0) * 100  # in percentage

# Create the 100% stacked area plot
plt.figure(figsize=(10, 6))
plt.stackplot(result_df.index, 
              stack_data['CASH'],
              stack_data[f'notional_{tickers[0]}'],
              stack_data[f'notional_{tickers[1]}'],
              stack_data[f'notional_{tickers[2]}'],
              stack_data[f'notional_{tickers[3]}'],
              stack_data[f'notional_{tickers[4]}'],
              stack_data[f'notional_{tickers[5]}'],
              labels=['CASH'] + tickers,
              colors=colors[:len(components)])
plt.xlabel('Date')
plt.ylabel('Percentage of Total AUM (%)')
plt.title('Portfolio Composition: CASH & Notionals of Each Asset')
plt.legend(loc='upper left')
plt.tight_layout()
plt.show()
Editor is loading...
Leave a Comment