File size: 1,801 Bytes
4cda7a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# Read the price data from the Excel file
price_data = pd.read_excel('Momentum II.xlsx', index_col=0, parse_dates=True)

# Calculate the 120 trading day momentum for each stock
momentum = price_data.pct_change(120)

def get_long_short_positions(df, long_percentile, short_percentile):
    long_criteria = df > np.percentile(df.dropna(), long_percentile)
    short_criteria = df < np.percentile(df.dropna(), short_percentile)
    return long_criteria, short_criteria

# Loop through each day and stock, and calculate long and short positions
portfolio = pd.DataFrame(index=momentum.index, columns=momentum.columns)

for date, row in momentum.iterrows():
    long_pos, short_pos = get_long_short_positions(row, 85, 15)
    portfolio.loc[date, long_pos] = 1
    portfolio.loc[date, short_pos] = -1

# Calculate the daily P&L for long and short positions separately
daily_returns = price_data.pct_change().shift(-1)
long_pnl = (portfolio * daily_returns).where(portfolio == 1).sum(axis=1)
short_pnl = (portfolio * -daily_returns).where(portfolio == -1).sum(axis=1)

# Calculate the total daily P&L by adding the long and short P&L
daily_pnl = long_pnl + short_pnl

# Calculate the cumulative P&L by summing up daily PnL values
cumulative_pnl = daily_pnl.cumsum()

# Plot the cumulative P&L curve
fig, ax = plt.subplots(figsize=(10, 6))

ax.plot(cumulative_pnl)
ax.set_title('Cumulative P&L Curve')
ax.set_xlabel('Date')
ax.set_ylabel('Portfolio Value')
ax.grid()

plt.tight_layout()
plt.show()

with pd.ExcelWriter('trade_details.xlsx') as writer:
    daily_pnl.to_excel(writer, sheet_name='Daily PnL')
    cumulative_pnl.to_excel(writer, sheet_name='Cumulative PnL')
    portfolio.to_excel(writer, sheet_name='Portfolio Positions')