-
Notifications
You must be signed in to change notification settings - Fork 38
Expand file tree
/
Copy pathtest_nifty_hedge_margin.py
More file actions
361 lines (307 loc) Β· 12.7 KB
/
Copy pathtest_nifty_hedge_margin.py
File metadata and controls
361 lines (307 loc) Β· 12.7 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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
NIFTY Futures and Hedged Options Margin Analysis
This script tests margin requirements for various NIFTY futures and options strategies
"""
from openalgo import api
from datetime import datetime
import json
# Initialize the API client
API_KEY = "7371cc58b9d30204e5fee1d143dc8cd926bcad90c24218201ad81735384d2752"
client = api(api_key=API_KEY, host="http://127.0.0.1:5000")
def format_margin(amount):
"""Format margin amount in Indian style"""
if amount is None:
return "N/A"
return f"βΉ{amount:,.2f}"
def test_nifty_futures_standalone():
"""Test margin for standalone NIFTY futures"""
print("\n" + "="*80)
print("1. STANDALONE NIFTY FUTURES (NIFTY25NOV25FUT)")
print("="*80)
try:
# Long futures position
print("\nπ LONG FUTURES (Buy 1 lot = 75 qty)")
result = client.margin(positions=[{
"symbol": "NIFTY25NOV25FUT",
"exchange": "NFO",
"action": "BUY",
"product": "NRML",
"pricetype": "MARKET",
"quantity": "75"
}])
if result.get('status') == 'success':
data = result.get('data', {})
print(f" Total Margin Required: {format_margin(data.get('total_margin_required'))}")
print(f" SPAN Margin: {format_margin(data.get('span_margin'))}")
print(f" Exposure Margin: {format_margin(data.get('exposure_margin'))}")
long_futures_margin = data.get('total_margin_required', 0)
else:
print(f" β Error: {result.get('message')}")
long_futures_margin = 0
# Short futures position
print("\nπ SHORT FUTURES (Sell 1 lot = 75 qty)")
result = client.margin(positions=[{
"symbol": "NIFTY25NOV25FUT",
"exchange": "NFO",
"action": "SELL",
"product": "NRML",
"pricetype": "MARKET",
"quantity": "75"
}])
if result.get('status') == 'success':
data = result.get('data', {})
print(f" Total Margin Required: {format_margin(data.get('total_margin_required'))}")
print(f" SPAN Margin: {format_margin(data.get('span_margin'))}")
print(f" Exposure Margin: {format_margin(data.get('exposure_margin'))}")
short_futures_margin = data.get('total_margin_required', 0)
else:
print(f" β Error: {result.get('message')}")
short_futures_margin = 0
return long_futures_margin, short_futures_margin
except Exception as e:
print(f" β Error: {str(e)}")
return 0, 0
def test_long_futures_with_put_hedge():
"""Test margin for long futures hedged with long put (protective put on futures)"""
print("\n" + "="*80)
print("2. LONG FUTURES + LONG PUT (Protective Put Strategy)")
print("="*80)
print("Strategy: Buy NIFTY Futures + Buy ATM Put for downside protection")
try:
# Assuming NIFTY spot around 25000, using 25000 strike put
positions = [
{
"symbol": "NIFTY25NOV25FUT",
"exchange": "NFO",
"action": "BUY", # Long futures
"product": "NRML",
"pricetype": "MARKET",
"quantity": "75"
},
{
"symbol": "NIFTY25NOV2525000PE", # ATM Put
"exchange": "NFO",
"action": "BUY", # Long Put for protection
"product": "NRML",
"pricetype": "MARKET",
"quantity": "75"
}
]
result = client.margin(positions=positions)
if result.get('status') == 'success':
data = result.get('data', {})
print(f"\n Combined Margin Required: {format_margin(data.get('total_margin_required'))}")
print(f" SPAN Margin: {format_margin(data.get('span_margin'))}")
print(f" Exposure Margin: {format_margin(data.get('exposure_margin'))}")
print("\n π Strategy Benefits:")
print(" β’ Limited downside risk (max loss = futures entry - put strike + put premium)")
print(" β’ Unlimited upside potential")
print(" β’ Lower margin due to hedging benefit")
return data.get('total_margin_required', 0)
else:
print(f" β Error: {result.get('message')}")
return 0
except Exception as e:
print(f" β Error: {str(e)}")
return 0
def test_short_futures_with_call_hedge():
"""Test margin for short futures hedged with long call (protective call on short futures)"""
print("\n" + "="*80)
print("3. SHORT FUTURES + LONG CALL (Protective Call Strategy)")
print("="*80)
print("Strategy: Sell NIFTY Futures + Buy ATM Call for upside protection")
try:
positions = [
{
"symbol": "NIFTY25NOV25FUT",
"exchange": "NFO",
"action": "SELL", # Short futures
"product": "NRML",
"pricetype": "MARKET",
"quantity": "75"
},
{
"symbol": "NIFTY25NOV2525000CE", # ATM Call
"exchange": "NFO",
"action": "BUY", # Long Call for protection
"product": "NRML",
"pricetype": "MARKET",
"quantity": "75"
}
]
result = client.margin(positions=positions)
if result.get('status') == 'success':
data = result.get('data', {})
print(f"\n Combined Margin Required: {format_margin(data.get('total_margin_required'))}")
print(f" SPAN Margin: {format_margin(data.get('span_margin'))}")
print(f" Exposure Margin: {format_margin(data.get('exposure_margin'))}")
print("\n π Strategy Benefits:")
print(" β’ Limited upside risk (max loss = call strike - futures entry + call premium)")
print(" β’ Profit from downward movement")
print(" β’ Lower margin due to hedging benefit")
return data.get('total_margin_required', 0)
else:
print(f" β Error: {result.get('message')}")
return 0
except Exception as e:
print(f" β Error: {str(e)}")
return 0
def test_synthetic_long():
"""Test margin for synthetic long (Long Call + Short Put at same strike)"""
print("\n" + "="*80)
print("4. SYNTHETIC LONG (Long Call + Short Put at 25000)")
print("="*80)
print("Strategy: Replicates long futures using options")
try:
positions = [
{
"symbol": "NIFTY25NOV2525000CE",
"exchange": "NFO",
"action": "BUY", # Long Call
"product": "NRML",
"pricetype": "MARKET",
"quantity": "75"
},
{
"symbol": "NIFTY25NOV2525000PE",
"exchange": "NFO",
"action": "SELL", # Short Put
"product": "NRML",
"pricetype": "MARKET",
"quantity": "75"
}
]
result = client.margin(positions=positions)
if result.get('status') == 'success':
data = result.get('data', {})
print(f"\n Combined Margin Required: {format_margin(data.get('total_margin_required'))}")
print(f" SPAN Margin: {format_margin(data.get('span_margin'))}")
print(f" Exposure Margin: {format_margin(data.get('exposure_margin'))}")
print("\n π Strategy Characteristics:")
print(" β’ Behaves exactly like long futures")
print(" β’ P&L profile identical to futures")
print(" β’ May have different margin requirements than futures")
return data.get('total_margin_required', 0)
else:
print(f" β Error: {result.get('message')}")
return 0
except Exception as e:
print(f" β Error: {str(e)}")
return 0
def test_collar_strategy():
"""Test margin for collar strategy (Long Futures + Long OTM Put + Short OTM Call)"""
print("\n" + "="*80)
print("5. COLLAR STRATEGY (Long Futures + Long Put + Short Call)")
print("="*80)
print("Strategy: Long Futures + Buy 24500 Put + Sell 25500 Call")
try:
positions = [
{
"symbol": "NIFTY25NOV25FUT",
"exchange": "NFO",
"action": "BUY", # Long futures
"product": "NRML",
"pricetype": "MARKET",
"quantity": "75"
},
{
"symbol": "NIFTY25NOV2524500PE", # OTM Put
"exchange": "NFO",
"action": "BUY", # Long Put for protection
"product": "NRML",
"pricetype": "MARKET",
"quantity": "75"
},
{
"symbol": "NIFTY25NOV2525500CE", # OTM Call
"exchange": "NFO",
"action": "SELL", # Short Call to finance put
"product": "NRML",
"pricetype": "MARKET",
"quantity": "75"
}
]
result = client.margin(positions=positions)
if result.get('status') == 'success':
data = result.get('data', {})
print(f"\n Combined Margin Required: {format_margin(data.get('total_margin_required'))}")
print(f" SPAN Margin: {format_margin(data.get('span_margin'))}")
print(f" Exposure Margin: {format_margin(data.get('exposure_margin'))}")
print("\n π Strategy Benefits:")
print(" β’ Limited downside (protected by put at 24500)")
print(" β’ Limited upside (capped by call at 25500)")
print(" β’ Very low margin due to full hedge")
print(" β’ Often used for low-cost protection")
return data.get('total_margin_required', 0)
else:
print(f" β Error: {result.get('message')}")
return 0
except Exception as e:
print(f" β Error: {str(e)}")
return 0
def main():
"""Run all margin tests and compare results"""
print("\n" + "="*80)
print("NIFTY FUTURES AND OPTIONS MARGIN ANALYSIS")
print("Testing Date: " + datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
print("="*80)
# Store results for comparison
results = {}
# Test standalone futures
long_fut, short_fut = test_nifty_futures_standalone()
results['Long Futures'] = long_fut
results['Short Futures'] = short_fut
# Test hedged strategies
results['Long Futures + Put'] = test_long_futures_with_put_hedge()
results['Short Futures + Call'] = test_short_futures_with_call_hedge()
results['Synthetic Long'] = test_synthetic_long()
results['Collar Strategy'] = test_collar_strategy()
# Summary comparison
print("\n" + "="*80)
print("MARGIN COMPARISON SUMMARY")
print("="*80)
print("\nπ Margin Requirements Comparison:")
print("-" * 60)
for strategy, margin in results.items():
if margin > 0:
print(f" {strategy:<25}: {format_margin(margin):>20}")
# Calculate savings compared to naked futures
if strategy == 'Long Futures + Put' and long_fut > 0:
savings = ((long_fut - margin) / long_fut) * 100
print(f" {'':25} Savings vs naked long: {savings:.1f}%")
elif strategy == 'Short Futures + Call' and short_fut > 0:
savings = ((short_fut - margin) / short_fut) * 100
print(f" {'':25} Savings vs naked short: {savings:.1f}%")
print("\n" + "="*80)
print("KEY INSIGHTS:")
print("="*80)
print("""
1. NAKED FUTURES:
β’ Highest margin requirement
β’ Unlimited risk in adverse direction
β’ Simple to execute
2. HEDGED FUTURES (with protective options):
β’ Significantly lower margin (often 30-50% less)
β’ Limited risk due to option protection
β’ Small premium cost for protection
3. SYNTHETIC POSITIONS:
β’ Can replicate futures payoff using options
β’ May have different margin requirements
β’ Useful when futures liquidity is low
4. COLLAR STRATEGY:
β’ Lowest margin due to full hedge
β’ Both upside and downside are limited
β’ Cost-effective protection strategy
π‘ IMPORTANT NOTES:
β’ Margin benefits vary by broker (Angel One, Zerodha, etc.)
β’ SPAN margin calculation considers portfolio risk
β’ Hedged positions get margin benefit due to lower risk
β’ Always check real-time margin before placing orders
""")
print("="*80)
print("Analysis Complete!")
print("="*80)
if __name__ == "__main__":
main()