-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtriple_momentum.py
More file actions
394 lines (304 loc) · 12.8 KB
/
Copy pathtriple_momentum.py
File metadata and controls
394 lines (304 loc) · 12.8 KB
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
# %%
from trading.common import utils
logger = utils.get_logger('triple-momentum', use_rich=True, should_add_ts=True)
import os, sys, json, argparse
import subprocess
import re
import pandas as pd
import time
import datetime
import plotly
import plotly.express as px
import numpy as np
import yfinance as yf
import matplotlib.pyplot as plt
from typing import Tuple, Dict
from trading.services import telegram_runner
'''
Usage
python trading/strategies/triple_momentum.py \
--main-col NIFTY \
--main-ticker ^NSEI \
--alt-col USDINR \
--alt-ticker USDINR=X \
--output-dir data/triple-momentum \
--initial-capital 100000
python trading/strategies/triple_momentum.py \
--main-col INDA \
--main-ticker INDA \
--alt-col GOLD \
--alt-ticker GC=F
'''
def parse_arguments() -> argparse.Namespace:
"""Parse command line arguments."""
parser = argparse.ArgumentParser(
description='Triple Momentum Trading Strategy')
# what is the main ticker
parser.add_argument('--main-col',
type=str,
default='NIFTY',
help='Column name for NIFTY data')
parser.add_argument('--main-ticker',
type=str,
default='^NSEI',
help='Main ticker symbol')
# what is the alternate ticker
parser.add_argument('--alt-ticker',
type=str,
default='USDINR=X',
help='Alt ticker symbol')
# what is the third ticker
parser.add_argument('--third-ticker',
type=str,
default='GLD',
help='Third ticker symbol')
parser.add_argument('--alt-col',
type=str,
default='USDINR',
help='Column name for alt data')
parser.add_argument('--third-col',
type=str,
default='GLD',
help='Column name for third data')
parser.add_argument('--initial-capital',
type=float,
default=100000,
help='Initial capital amount')
parser.add_argument('--output-dir',
type=str,
required=False,
default='data/triple-momentum',
help='Directory to store output data')
# add an arg for notifications
parser.add_argument('--notify',
action='store_true',
help='Send notifications')
return parser.parse_args()
def run_cmd(cmds):
proc = subprocess.Popen(
cmds,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
stdout, stderr = proc.communicate(timeout=1000)
if stderr:
stderr_s = stderr.decode('utf-8').split('\n')
for s in stderr_s:
logger.info(f'stderr = {s}')
return stdout.decode('utf-8')
def read_data(ticker):
df = yf.download(ticker,
progress=False,
period='5y',
multi_level_index=False)
logger.info(f'df = \n{df}')
return df
def setup_directory(output_dir: str) -> None:
"""Create output directory if it doesn't exist."""
os.makedirs(output_dir, exist_ok=True)
def calc_returns(df, suffix=''):
"""Calculate returns and normalized returns metrics with optional suffix."""
df = df.copy() # Ensure we don't modify the original dataframe
# Add suffix to all columns except the original price columns
rename_dict = {col: f"{col}{suffix}" for col in df.columns}
df = df.rename(columns=rename_dict)
returns_col = f'returns{suffix}'
mean_col = f'mean{suffix}'
std_col = f'std{suffix}'
norm_returns_col = f'norm_returns{suffix}'
logger.info(f'df = \n{df}')
logger.info(f'df columns found = {df.columns}; suffix={suffix}')
df[returns_col] = df[f'Close{suffix}'].pct_change(21)
df[mean_col] = df[returns_col].rolling(4).mean()
df[std_col] = df[mean_col].rolling(4).std()
df[norm_returns_col] = df[mean_col] / df[std_col]
return df
def merge_three_dataframes(df_first: pd.DataFrame, df_second: pd.DataFrame,
df_third: pd.DataFrame) -> pd.DataFrame:
"""Merge three dataframes with appropriate suffixes."""
# Calculate returns for each dataframe with appropriate suffixes
df_first = calc_returns(df_first, '_first')
df_second = calc_returns(df_second, '_second')
df_third = calc_returns(df_third, '_third')
# First merge
df_merged = pd.merge(df_first,
df_second,
left_index=True,
right_index=True,
how='left')
# Second merge
df_merged = pd.merge(df_merged,
df_third,
left_index=True,
right_index=True,
how='left')
return df_merged.iloc[::-1] # Reverse order
def clean_merged_data(df_merged: pd.DataFrame) -> pd.DataFrame:
"""Clean and prepare merged dataframe for three assets."""
# Create aligned series for comparisons
norm_first = df_merged['norm_returns_first']
norm_second = df_merged['norm_returns_second']
norm_third = df_merged['norm_returns_third']
# Calculate highest returns using aligned comparisons
df_merged['norm_returns_first_is_highest'] = ((norm_first > norm_second) &
(norm_first > norm_third))
df_merged['norm_returns_second_is_highest'] = ((norm_second > norm_first) &
(norm_second > norm_third))
df_merged['norm_returns_third_is_highest'] = ((norm_third > norm_first) &
(norm_third > norm_second))
# Drop unnecessary columns
columns_to_drop = []
for suffix in ['_first', '_second', '_third']:
columns_to_drop.extend(
[f'{s}{suffix}' for s in ['Open', 'High', 'Low', 'Volume']])
return df_merged.drop(columns_to_drop, axis=1)
def get_parsed_dataframe(ticker, suffix=''):
"""Get dataframe with calculated returns using specified suffix."""
df = read_data(ticker)
df = calc_returns(df, suffix)
return df
def process_status_changes(df: pd.DataFrame,
col_mappings: Dict[str, str]) -> pd.DataFrame:
"""Process status changes for three assets."""
# Detect any change in position
df['status_changed'] = (df.norm_returns_first_is_highest.ne(
df.norm_returns_first_is_highest.shift())
| df.norm_returns_second_is_highest.ne(
df.norm_returns_second_is_highest.shift())
| df.norm_returns_third_is_highest.ne(
df.norm_returns_third_is_highest.shift()))
d_filtered = df[df['status_changed']].iloc[::-1].round(2)
columns_to_drop = [
'returns_first',
'mean_first',
'std_first',
'returns_second',
'mean_second',
'std_second',
'returns_third',
'mean_third',
'std_third',
# 'Adj Close_first', 'Adj Close_second', 'Adj Close_third'
]
d_filtered.drop(columns_to_drop, axis=1, inplace=True)
# Rename columns
d_filtered.rename(columns=col_mappings, inplace=True)
# Calculate previous values
d_filtered['prev_first'] = d_filtered.shift(1)[col_mappings['Close_first']]
d_filtered['prev_second'] = d_filtered.shift(1)[col_mappings['Close_second']]
d_filtered['prev_third'] = d_filtered.shift(1)[col_mappings['Close_third']]
col_names = d_filtered.columns.tolist()
logger.info(f'd_filtered cols = \n{col_names}')
return d_filtered
def calculate_positions_and_pl(data: pd.DataFrame, initial_capital: float,
first_col: str, second_col: str,
third_col: str) -> pd.DataFrame:
"""Calculate positions and profit/loss for three assets."""
data = data.copy()
logger.info(f'data = \n{data}')
# Calculate positions based on highest normalized returns
data['first_position'] = data['norm_returns_first_is_highest'].astype(int)
data['second_position'] = data['norm_returns_second_is_highest'].astype(int)
data['third_position'] = data['norm_returns_third_is_highest'].astype(int)
# Calculate returns for each asset
data['first_returns'] = data[first_col].pct_change() * 100
data['second_returns'] = data[second_col].pct_change() * 100
data['third_returns'] = data[third_col].pct_change() * 100
# Calculate P/L for each asset
for position, col, pl_name in [('first_position', first_col, 'first_pl'),
('second_position', second_col, 'second_pl'),
('third_position', third_col, 'third_pl')]:
data[pl_name] = ((data[col] - data[col].shift(1)) * initial_capital *
data[position] / data[col].shift(1))
# Apply P/L limits (adjust these as needed)
data["first_pl"] = data["first_pl"].apply(lambda x: max(x, -5000))
data["second_pl"] = data["second_pl"].apply(lambda x: max(x, -1000))
data["third_pl"] = data["third_pl"].apply(lambda x: max(x, -1000))
# Calculate cumulative P/L
data['cumulative_first_pl'] = data['first_pl'].cumsum()
data['cumulative_second_pl'] = data['second_pl'].cumsum()
data['cumulative_third_pl'] = data['third_pl'].cumsum()
data["total_pl"] = (data["cumulative_first_pl"] +
data["cumulative_second_pl"] +
data["cumulative_third_pl"])
return data
def calculate_portfolio_metrics(df: pd.DataFrame,
initial_capital: float) -> pd.DataFrame:
"""Calculate portfolio metrics for three assets."""
df = df.copy()
# Set positions based on previous period's signals
df['first_position'] = df['norm_returns_first_is_highest'].shift(1)
df['second_position'] = df['norm_returns_second_is_highest'].shift(1)
df['third_position'] = df['norm_returns_third_is_highest'].shift(1)
# Calculate returns for each asset
df['first_returns'] = df['Close_first'].pct_change()
df['second_returns'] = df['Close_second'].pct_change()
df['third_returns'] = df['Close_third'].pct_change()
# Calculate strategy returns (only one position will be active at a time)
df['strategy_returns'] = (
df['first_position'].shift(1) * df['first_returns'] +
df['second_position'].shift(1) * df['second_returns'] +
df['third_position'].shift(1) * df['third_returns'])
df['cumulative_returns'] = (1 + df['strategy_returns']).cumprod()
df['portfolio_value'] = initial_capital * df['cumulative_returns']
return df
def main():
# Parse arguments
args = parse_arguments()
setup_directory(args.output_dir)
# Get data (assuming get_parsed_dataframe is defined elsewhere)
df_main = get_parsed_dataframe(args.main_ticker)
df_alt = get_parsed_dataframe(args.alt_ticker)
df_third = get_parsed_dataframe(args.third_ticker)
# Process data
df_merged = merge_three_dataframes(df_main, df_alt, df_third)
# Clean and process the data
col_mappings = {
'Close_first': args.main_col,
'Close_second': args.alt_col,
'Close_third': args.third_col
}
df_merged = clean_merged_data(df_merged)
# col_mappings = {'Close_main': args.main_col, 'Close_alt': args.alt_col}
d_filtered = process_status_changes(df_merged, col_mappings)
# Calculate positions and P/L
data = calculate_positions_and_pl(d_filtered, args.initial_capital,
args.main_col, args.alt_col,
args.third_col)
# Calculate portfolio metrics
portfolio_data = calculate_portfolio_metrics(df_merged, args.initial_capital)
# Prepare and log results
logger.info(f'Filtered data = \n{data.iloc[-20:].round(2)}')
logger.info(f'Portfolio data = \n{portfolio_data.iloc[:10]}')
# sample_results(data)
# Prepare telegram update
telegram_text = prepare_telegram_update(args, data)
logger.info(telegram_text)
if args.notify:
telegram_runner.send_text([telegram_text])
else:
logger.info('Notifications disabled')
def prepare_telegram_update(args, data: pd.DataFrame) -> str:
"""Prepare text for Telegram update."""
# remove rows containing NaN values
data = data.dropna()
# Select the last 10 rows and the relevant columns
final = data[[
args.main_col, args.alt_col, args.third_col,
'norm_returns_first_is_highest', 'norm_returns_second_is_highest',
'norm_returns_third_is_highest'
]][-10:].round(2)
# Create a BUY column that shows which asset to buy
final['BUY'] = None
final.loc[final['norm_returns_first_is_highest'], 'BUY'] = args.main_col
final.loc[final['norm_returns_second_is_highest'], 'BUY'] = args.alt_col
final.loc[final['norm_returns_third_is_highest'], 'BUY'] = args.third_col
# Drop the boolean columns
final = final.drop([
'norm_returns_first_is_highest', 'norm_returns_second_is_highest',
'norm_returns_third_is_highest'
],
axis=1)
return f'''Triple Momentum = \n```\n{final}\n```'''
if __name__ == '__main__':
main()