├── README.md
├── Section-2
└── TRIN.py
├── Section-3
└── PCR.py
└── Section-4
└── VIX.py
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Learn A to Z of Algorithmic and Quantitative Trading
5 | Quantra® is an e-learning portal by QuantInsti® that specializes in Algorithmic & Quantitative Trading. Quantra offers the best self-paced courses that are a mix of videos, audios, presentations, multiple choice questions and highly interactive exercises.
6 |
7 |
8 |
9 |
32 |
33 |

34 |
35 |
36 |
37 |
38 | > Made on Python version 2.7
39 |
40 | ### Table of contents
41 | - [About the course](#about-the-course)
42 | - [Breadth Measures](#breadth-measures)
43 | - [Option Trading Measures](#option-trading-measures)
44 | - [Volatility Measures](#volatility-measures)
45 | - [Download](#download)
46 | - [Contact Us](#contact-us)
47 |
48 | ## About the course
49 | [(Back to top)](#table-of-contents)
50 |
51 | This course will help you to understand the two major emotions that drive the entire market - Fear and Greed and help you to capitalize on these emotions to make profits.
52 |
53 | #### Highlights of the course are:
54 |
55 | 1. Creation of a strong foundation for the concepts on sentiment trading, sentiment indicators such as TRIN or Arms index or Short term Trading Index, Put/Call ratio and Volatility Index.
56 | 2. How to interpret the sentiment indicators and devise trading strategies using sentiment indicators.
57 | 3. Develop a trading logic by using signals from the sentiment indicators and code it using Python programming language.
58 | 4. Analyze the strategy in Microsoft Excel using 2 years of historical data for backtesting.
59 | 5. Unserstand the various risks involved in while trading using sentiment indicators.
60 |
61 | #### What do I learn in this course
62 | - Market sentiments and how they influence your trade
63 | - About sentiment indicators, how to interpret them and devise trading strategies based on these interpretations
64 | - Code trading strategies in Python using sentiment indicators and analyze the trading signals generated by the strategy in Microsoft Excel
65 | - Understand how to think logically about the entry and exit points in a trade, while creating an algorithm for trading
66 | - Code trading strategies algorithmically and backtest on historical data to gauge your strategy’s performance in markets
67 | - The Various risks which can influence your trade and how to mitigate them
68 |
69 | Want to know more? Check out the course [here](https://quantra.quantinsti.com/course/trading-using-options-sentiment-indicators).
70 |
71 | ## Breadth Measures
72 | [(Back to top)](#table-of-contents)
73 |
74 | The folder contains the following topics:
75 |
76 | **Fetching data:**
77 | An [exercise](https://quantra.quantinsti.com/startCourseDetails?cid=39§ion_no=2&unit_no=11) where you will learn how to fetch data for S&P 500 futures contracts, advancing stocks and declining stocks on NYSE from Quandl.
78 |
79 | **Defining Bollinger Bands:**
80 | An [exercise](https://quantra.quantinsti.com/startCourseDetails?cid=39§ion_no=2&unit_no=12) where you will learn to define the upper and lower Bollinger bands.
81 |
82 | **Identifying crossovers:**
83 | An [exercise](https://quantra.quantinsti.com/startCourseDetails?cid=39§ion_no=2&unit_no=13) where you will learn to set values for flags/boolean variables (variables storing either True or False) for moving average and stop loss band crossovers.
84 |
85 | **Generating Buy Signals:**
86 | An [exercise](https://quantra.quantinsti.com/startCourseDetails?cid=39§ion_no=2&unit_no=14) where you will learn to check the condition for opening a Buy position when the upper Bollinger band is crossed and assign an appropriate value to the variable ‘flag’.
87 |
88 |
89 | ## Option Trading Measures
90 | [(Back to top)](#table-of-contents)
91 |
92 | The folder contains the following topics:
93 |
94 | **Generating a Sell Signal:**
95 | An [exercise](https://quantra.quantinsti.com/startCourseDetails?cid=39§ion_no=3&unit_no=13) where you will learn how to place a 'SELL' order if PCR crosses below the lower Bollinger band since it is a sign of an overbought market. We will take a contrarian position amid this bullish sentiment.
96 |
97 | **Closing an open sell position 1:**
98 | An [exercise](https://quantra.quantinsti.com/startCourseDetails?cid=39§ion_no=3&unit_no=14) where you will learn to place a buy order to close the open short position.
99 |
100 | **Closing an open sell position 2:**
101 | An [exercise](https://quantra.quantinsti.com/startCourseDetails?cid=39§ion_no=3&unit_no=15) where you will learn to close the open short position if PCR crosses the Lower Stoploss Band, i.e. PCR continues to fall after crossing the LBB, by placing a 'BUY' order, booking a loss.
102 |
103 | **Closing an open sell position 3:**
104 | An [exercise](https://quantra.quantinsti.com/startCourseDetails?cid=39§ion_no=3&unit_no=16) where you will learn to close an open short position by placing a buy order if the absolute stop loss value triggers a signal to close the position.
105 |
106 | **Closing an open Buy position:**
107 | An [exercise](https://quantra.quantinsti.com/startCourseDetails?cid=39§ion_no=3&unit_no=17) where you will learn to place a sell order to close the open buy position.
108 |
109 |
110 | ## Volatility Measures
111 | [(Back to top)](#table-of-contents)
112 |
113 |
114 | **Generating a buy order:**
115 | An [exercise](https://quantra.quantinsti.com/startCourseDetails?cid=39§ion_no=4&unit_no=11) where you will learn how to generate an order to buy S&P 500 futures contracts, if the value of VIX exceeds the threshold value (i.e. thresh = 22).
116 |
117 | **Closing an open Buy position 1:**
118 | An [exercise](https://quantra.quantinsti.com/startCourseDetails?cid=39§ion_no=4&unit_no=12) where you will learn to check if the value of VIX exceeds the threshold value (i.e. thresh = 22); we will buy S&P 500 futures. In this exercise, if the S&P 500 futures contract value is trading 5% above its bought price, we will sell the contract and book a profit. We will then update the required fields and flags to avoid conflicts in our codes.
119 |
120 | **Closing an open Buy position 2:**
121 | An [exercise](https://quantra.quantinsti.com/startCourseDetails?cid=39§ion_no=4&unit_no=13) where you will learn to check if the value of VIX exceeds the threshold value (i.e. thresh = 22); then we will buy S&P 500 futures. If the S&P 500 futures value is 5% above its bought price, we will sell the futures contract and book a profit. In this exercise, if the S&P 500 futures value is 5% below its bought price, we will sell the futures contract and book a loss (our stoploss condition). We will then update the required fields and flags to avoid conflicts in our codes.
122 |
123 | **Appending trade data:**
124 | An [exercise](https://quantra.quantinsti.com/startCourseDetails?cid=39§ion_no=4&unit_no=14) where you will learn to use the append() method. The append() method adds a single item to an existing list. It does not return a new list, but it rather modifies the original list. We will modify the ‘stoploss' and ‘mtm’ list in this exercise.
125 |
126 | You can understand the concepts by accessing the full [course](https://quantra.quantinsti.com/course/trading-using-options-sentiment-indicators).
127 |
128 | ## Download
129 | [(Back to top)](#table-of-contents)
130 |
131 | You can download the resources [here](https://quantra.quantinsti.com/startCourseDetails?cid=39§ion_no=6&unit_no=3).
132 |
133 |
134 | ## Contact Us
135 | [(Back to top)](#table-of-contents)
136 |
137 | You can get in touch with us at [quantra@quantinsti.com](mailto:quantra@quantinsti.com)
138 |
139 | Alternatively, get in touch on:
140 |
--------------------------------------------------------------------------------
/Section-2/TRIN.py:
--------------------------------------------------------------------------------
1 | #Copyright QuantInsti Quantitative Learning Private Limited
2 |
3 | #importing required libraries
4 | import pandas as pd
5 | import quandl
6 | import matplotlib.pyplot as plt
7 | import math
8 |
9 | def variance_calculator(series,series_average,win_len):
10 | sma = win_len
11 | temp = series.subtract(series_average) # a-b
12 | temp2 = temp.apply(lambda x: x**2) #(a-b)^2
13 | temp3 = temp2.rolling(sma-1).mean() # summation[(a-b)^2 ]/ (sma -1)
14 | sigma = temp3.apply(lambda x : math.sqrt(x)) #sigma is the standard deviation
15 | return sigma
16 |
17 |
18 | Data1 = quandl.get("CHRIS/CME_SP1", authtoken="mq-W7Z-QXBDZ1MxaN-Vy", start_date="2014-12-12")
19 | declining = quandl.get("URC/NYSE_DEC", authtoken = "mq-W7Z-QXBDZ1MxaN-Vy", start_date="2014-12-12")
20 | advancing = quandl.get("URC/NYSE_ADV", authtoken = "mq-W7Z-QXBDZ1MxaN-Vy",start_date="2014-12-12")
21 | adv_vol = quandl.get("URC/NYSE_ADV_VOL", authtoken = "mq-W7Z-QXBDZ1MxaN-Vy",start_date="2014-12-12")
22 | dec_vol = quandl.get("URC/NYSE_DEC_VOL", authtoken = "mq-W7Z-QXBDZ1MxaN-Vy",start_date="2014-12-12")
23 | Data = declining
24 | Data['declining'] = declining['Numbers of Stocks']
25 | Data['advancing'] = advancing['Numbers of Stocks']
26 | Data['dec_vol'] = dec_vol['Numbers of Stocks']
27 | Data['adv_vol'] = adv_vol['Numbers of Stocks']
28 | merged = Data.join(Data1)
29 | merged = merged.fillna(method ='ffill')
30 | Data = merged
31 | #finding the TRIN value using the number and volume of advancing & declining stocks
32 | tem1 = Data['advancing'].divide(Data['declining'])
33 | tem2 = Data['adv_vol'].divide(Data['dec_vol'])
34 | tem = tem1.divide(tem2)#TRIN value
35 | Data['TRIN'] = tem
36 | Data['TRIN'] = Data['TRIN'].apply(lambda x: math.log(x))# applying log to the lopsided TRIN and storing the new TRIN
37 | Data['future'] = Data['Last']
38 | Data.to_csv("tempr_data.csv")
39 | Data = pd.read_csv("tempr_data.csv")
40 |
41 |
42 | sma = 22 #............................the moving average window length
43 | k = 1.5 # ............................constant representing 'k' times sigma away from moving average(for Bollinger Bands)
44 | l = 2 #...............................constant representing 'l' times sigma away from Bollinger bands( for stoploss band)
45 | inv = 0
46 | pro = 0#..............................profit variable
47 | flag = 1 #............................flag is there for the first transaction--- transaction should start with LBB/UBB crossing only
48 | buy_flag = False
49 | sell_flag = False
50 | transaction_start_price = 0
51 | abs_SL = 25
52 | mtm = list()
53 | order_details = list()
54 | order = list()#.......................order is a list which contains the orders:- BUY/SELL/DO_Nothing
55 | profit = list()
56 | buy_sell = list()
57 | stoploss = list()
58 | trade_cause = list()
59 |
60 |
61 | Data['mAvg'] = Data['TRIN'].rolling(sma).mean() #calculating the moving average of the TRIN
62 | Data['TRIN_prev'] = Data['TRIN'].shift(1) #moving average shifted ahead to check for crossover
63 | Data.to_csv("tempr_data.csv") #data stored in tempr_data.csv excel file
64 | Data = pd.read_csv("tempr_data.csv")
65 | #calculating the standard deviation
66 | sigma = variance_calculator(Data['TRIN'],Data['mAvg'],sma)#calculating the standard deviation
67 | k_sigma = k*sigma
68 | l_sigma = l * sigma
69 |
70 | Data['UBB'] = Data['mAvg'].add(k_sigma) #.........upper bollinger band
71 | Data['LBB'] = Data['mAvg'].subtract(k_sigma) #....lower bollinger band
72 | Data['USL'] = Data['UBB'].add(l_sigma) #..........upper stoploss band
73 | Data['LSL'] = Data['LBB'].subtract(l_sigma)#......lower stoploss band
74 | Data['order'] = pd.Series() #.....................order is a list which contains the orders:- BUY/SELL/DO_Nothing
75 |
76 | s = Data['TRIN'].size#..............size of the TRIN series
77 |
78 | # logic to generate 'buy' and 'sell' signals starts here ========================================================================
79 | #--------------------------------------------------------------------------------------------------------------------------------
80 | #this loop checks for TRIN crossing LBB,UBB,MaVG AND PLACES THE BUY/SELL ORDER
81 |
82 | for i in range(s):
83 |
84 | pro = 0 # profit at each trade
85 | #variables to be used for comarison
86 | future_cost = Data['future'][i]#...........cost of big S&P 500 futures bought
87 | TRIN = Data['TRIN'][i]#.............current TRIN ratio value
88 | TRIN_prev = Data['TRIN_prev'][i]#.......previous day's TRIN ratio (for crossover check)
89 | LBB = Data['LBB'][i] #..............lower bollinger band
90 | UBB = Data['UBB'][i]#...............upper bollinger band
91 | mAvg = Data['mAvg'][i]#..............moving average
92 | USL = Data['USL'][i]#...............upper stoploss band
93 | LSL = Data['LSL'][i] #..............lower stoploss band
94 |
95 | #comparisons stored as boolean variables to place order accordingly
96 | UBB_cross = (TRIN > UBB) and (TRIN_prev < UBB)# .......Check if TRIN crosses upper bollinger band
97 | LBB_cross = (TRIN < LBB) and (TRIN_prev > LBB)# .......Check if TRIN crosses lower bollinger band
98 | mAvg_cross_up = (TRIN > mAvg) and (TRIN_prev < mAvg)#......Check if TRIN crosses moving average low to high
99 | mAvg_cross_down = (TRIN < mAvg) and (TRIN_prev > mAvg)#......Check if TRIN crosses moving average high to low
100 | USL_cross = (TRIN > USL) and (TRIN_prev < USL)#......Check if TRIN crosses upper stoploss band
101 | LSL_cross = (TRIN < LSL) and (TRIN_prev > LSL)#......Check if TRIN crosses lower stoploss band
102 |
103 | if(UBB_cross and (not buy_flag) and flag ==1): #...........places "BUY" order if TRIN crosses upper bollinger band to open a trade
104 | flag = 0
105 | buy_flag = True
106 | sell_flag = False
107 | transaction_start_price = future_cost #............price at which S&P 500 future bought when order is placed
108 | order_details = [1,"Buy" , "UBB crossed" , "0" , "position taken"]
109 |
110 | elif (LBB_cross and (not sell_flag) and flag ==1): #.......places "SELL" order if TRIN crosses lower bollinger band to open a trade
111 | flag = 0
112 | sell_flag = True
113 | buy_flag = False
114 | transaction_start_price = future_cost
115 | order_details = [-1,"Sell" , "LBB crossed" , "0" , "position taken"]
116 |
117 | elif (mAvg_cross_up and flag==0 and (not buy_flag)) : #........places "BUY" order if TRIN crosses mAvg from low to high to close a trade
118 | flag = 1
119 | buy_flag = False
120 | sell_flag = False
121 | pro = future_cost -transaction_start_price
122 | order_details = [1,"Buy" , "mAvg crossed" , "0" , "position closed"]
123 |
124 | elif( LSL_cross and flag == 0 and (not buy_flag)): #......places "BUY" order if TRIN crosses lower stoploss band to close a trade
125 | flag = 1
126 | buy_flag = False
127 | sell_flag = False
128 | pro = future_cost - transaction_start_price
129 | order_details = [1,"Buy" , "LSB crossed" , "stoploss executed" , "position closed"]
130 |
131 | elif((future_cost - transaction_start_price) > abs_SL and flag == 0 and (not buy_flag)):#......places "BUY " order if TRIN crosses lower stoploss #absolute value
132 | flag = 1
133 | buy_flag = False
134 | sell_flag = False
135 | pro = future_cost - transaction_start_price
136 | order_details = [1,"Buy" , "LSB crossed" , "stoploss executed abs" , "position closed"]
137 |
138 | elif (mAvg_cross_down and flag==0 and (not sell_flag)):#.....places "SELL" order if TRIN crosses mAvg from high to low to close a trade
139 | flag = 1
140 | sell_flag = False
141 | buy_flag = False
142 | pro = -(future_cost - transaction_start_price)
143 | order_details = [-1,"Sell" , "mAvg crossed (h to l)" , "0" , "position closed"]
144 |
145 | elif(USL_cross and flag==0 and (not sell_flag)):# ..places "SELL" order if TRIN crosses upper stoploss band to close a trade
146 | flag = 1
147 | sell_flag = False
148 | buy_flag = False
149 | pro = -(future_cost - transaction_start_price)
150 | order_details = [-1,"Sell" , "USB crossed" , "stoploss executed" , "position closed"]
151 |
152 | elif((-future_cost + transaction_start_price) > abs_SL and flag==0 and (not sell_flag)): # ..places "SELL" order if PCR crosses upper stoploss absolute #value
153 | flag = 1
154 | sell_flag = False
155 | buy_flag = False
156 | pro = -(future_cost - transaction_start_price)
157 | order_details = [-1,"Sell" , "USB crossed" , "stoploss executed_abs" , "position closed"]
158 |
159 | else:
160 | if(buy_flag==0 and sell_flag==0): tempo = "0"
161 | else:
162 | if(buy_flag==1 and sell_flag==0): tempo = (Data['future'][i] -transaction_start_price) * 500
163 | if(buy_flag==0 and sell_flag==1): tempo= (-Data['future'][i] +transaction_start_price) * 500
164 | order_details = [0,"No trade" , "no trade" , "0" , tempo]
165 |
166 |
167 | profit.append(pro)
168 | order.append(order_details[0])
169 | buy_sell.append(order_details[1])
170 | trade_cause.append(order_details[2])
171 | stoploss.append(order_details[3])
172 | mtm.append(order_details[4])
173 |
174 | #------------------------------------------------------------------------------------------------------------------------------
175 | #buy/sell logic ends================================================================================================================
176 |
177 | Data['placed_order'] = pd.Series(order) #..............................converting list to pandas series
178 | Data['cost'] = -(Data['placed_order'].multiply(Data['future'])) *500# ..cost at each transaction
179 | Data['out'] = Data['cost'].cumsum()# ..................................out is the cumulative cost profit/loss after transactions till now
180 | Data['buy_sell'] = pd.Series(buy_sell)
181 | Data['profit'] = -pd.Series(profit) * 500
182 | Data['stoploss'] = pd.Series(stoploss)
183 | Data['trade_cause'] = pd.Series(trade_cause)
184 | Data['mtm'] = pd.Series(mtm)
185 | print (Data['out'])
186 |
187 | output = pd.DataFrame() #....final output to be stored in excel file
188 | output['date'] = Data['Date']
189 | output['Close'] = Data['future']
190 | output['TRIN'] = Data['TRIN']
191 | output['placed_order'] = Data['placed_order']
192 | output['buy_sell'] = Data['buy_sell']
193 | output['trade_cause'] = Data['trade_cause']
194 | output['PnL'] = Data['profit']
195 | output['mtm'] = Data['mtm']
196 | output['stoploss'] = Data['stoploss']
197 | output['Cash Account'] = Data['out']
198 | output.to_excel('TRIN_SL_output.xlsx', sheet_name='Sheet1')
199 |
200 |
201 | #plt.plot(order)
202 | plt.plot(Data['TRIN'])
203 | plt.plot(Data['mAvg'])
204 | plt.plot(Data['UBB'])
205 | plt.plot(Data['LBB'])
206 | #plt.plot(Data['out'])
207 | plt.show()
208 |
209 | #Copyright QuantInsti Quantitative Learning Private Limited
210 |
--------------------------------------------------------------------------------
/Section-3/PCR.py:
--------------------------------------------------------------------------------
1 | #Copyright QuantInsti Quantitative Learning Private Limited
2 |
3 |
4 | #importing required libraries
5 | import pandas as pd
6 | import quandl
7 | import matplotlib.pyplot as plt
8 | import math
9 |
10 | def variance_calculator(series,series_average,win_len):
11 | sma = win_len
12 | temp = series.subtract(series_average) # a-b
13 | temp2 = temp.apply(lambda x: x**2) #(a-b)^2
14 | temp3 = temp2.rolling(sma-1).mean() # summation[(a-b)^2 ]/ (sma - 1)
15 | sigma = temp3.apply(lambda x : math.sqrt(x)) #sigma is the standard deviation
16 | return sigma
17 |
18 | def fetch_data(string1,string2,string3,filename):
19 | w = quandl.get(string1,authtoken = string2, start_date = string3)
20 | w.to_csv(filename)
21 | w = pd.read_csv(filename)
22 | return w
23 |
24 | #the data pulled from quandl and stored locally for faster execution
25 | Data1 = fetch_data( "CHRIS/CME_SP1", "mq-W7Z-QXBDZ1MxaN-Vy", "2014-12-12" ,"local_future.csv")
26 | Data = fetch_data("CBOE/SPX_PC","mq-W7Z-QXBDZ1MxaN-Vy", "2014-12-12","local_data.csv")
27 |
28 | Data['future'] = Data1['Last']
29 | Data['PCR'] = Data['S&P PUT-CALL RATIO'] # PCR IS Put Call Ratio
30 |
31 | sma = 20 #............................the moving average window length
32 | k = 1 # ..............................constant representing 'k' times sigma away from moving average(for Bollinger Bands)
33 | l = 1 #...............................constant representing 'l' times sigma away from Bollinger bands( for stoploss band)
34 | flag = 1 #............................flag is there to begin first transaction--- transaction should start with LBB/UBB crossing only
35 | pro = 0 #.............................profit variable
36 | transaction_start_price = 0
37 | buy_flag = False
38 | sell_flag = False
39 | abs_SL = 5
40 | mtm = list()
41 | order = list()#...........................order is a list which contains the orders:- BUY/SELL/DO_Nothing
42 | profit = list()
43 | buy_sell = list()
44 | stoploss = list()
45 | trade_cause = list()
46 | order_details = list()
47 |
48 |
49 | Data['mAvg'] = Data['PCR'].rolling(sma).mean() #calculating the moving average of the PCR
50 | Data['PCR_prev'] = Data['PCR'].shift(1) #moving average shifted ahead to check for crossover
51 |
52 |
53 | sigma = variance_calculator(Data['PCR'],Data['mAvg'],sma)#calculating the standard deviation
54 | k_sigma = k*sigma
55 | l_sigma = l*sigma
56 |
57 | Data['UBB'] = Data['mAvg'].add(k_sigma) #.........upper bollinger band
58 | Data['USL'] = Data['UBB'].add(l_sigma)#...........upper stoploss band
59 | Data['LBB'] = Data['mAvg'].subtract(k_sigma)#.....lower bollinger band
60 | Data['LSL'] = Data['LBB'].subtract(l_sigma)#......lower stoploss band
61 | Data['order'] = pd.Series() #.....................order is a list which contains the orders:- BUY/SELL/DO_Nothing
62 |
63 | s = Data['PCR'].size#.................size of the PCR series
64 |
65 | # logic to generate 'buy' and 'sell' signals starts here ==========================================================
66 |
67 | #this loop checks for PCR crossing LBB,UBB,MaVG,stoploss_bands and places the buy/sell order..
68 |
69 | for i in range(s):
70 |
71 | pro = 0 # profit at each trade
72 | #variables to be used for comarison
73 | future_cost = Data['future'][i]#...........cost of big S&P 500 futures bought
74 | PCR = Data['PCR'][i]#...............current putcall ratio value
75 | PCR_prev = Data['PCR_prev'][i]#.........previous day's put call ratio (for crossover check)
76 | LBB = Data['LBB'][i] #..............lower bollinger band
77 | UBB = Data['UBB'][i]#...............upper bollinger band
78 | mAvg = Data['mAvg'][i]#..............moving average
79 | USL = Data['USL'][i]#...............upper stoploss band
80 | LSL = Data['LSL'][i] #..............lower stoploss band
81 |
82 | #comparisons stored as boolean variables to place order accordingly
83 | UBB_cross = (PCR > UBB) and (PCR_prev < UBB)# .......Check if PCR crosses upper bollinger band
84 | LBB_cross = (PCR < LBB) and (PCR_prev > LBB)# .......Check if PCR crosses lower bollinger band
85 | mAvg_cross_up = (PCR > mAvg) and (PCR_prev < mAvg)#......Check if PCR crosses moving average low to high
86 | mAvg_cross_down = (PCR < mAvg) and (PCR_prev > mAvg)#......Check if PCR crosses moving average high to low
87 | USL_cross = (PCR > USL) and (PCR_prev < USL)#......Check if PCR crosses upper stoploss band
88 | LSL_cross = (PCR < LSL) and (PCR_prev > LSL)#......Check if PCR crosses lower stoploss band
89 |
90 | if(UBB_cross and (not buy_flag) and flag ==1): #...........places "BUY" order if PCR crosses upper bollinger band to open a trade
91 | flag = 0
92 | buy_flag = True
93 | sell_flag = False
94 | transaction_start_price = future_cost #............price at which S&P 500 future bought when order is placed
95 | order_details = [1,"Buy" , "UBB crossed" , "0" , "position taken"]
96 |
97 | elif (LBB_cross and (not sell_flag) and flag ==1): #.......places "SELL" order if PCR crosses lower bollinger band to open a trade
98 | flag = 0
99 | sell_flag = True
100 | buy_flag = False
101 | transaction_start_price = future_cost
102 | order_details = [-1,"Sell" , "LBB crossed" , "0" , "position taken"]
103 |
104 | elif (mAvg_cross_up and flag==0 and (not buy_flag)) : #........places "BUY" order if PCR crosses mAvg from low to high to close a trade
105 | flag = 1
106 | buy_flag = False
107 | sell_flag = False
108 | pro = future_cost -transaction_start_price
109 | order_details = [1,"Buy" , "mAvg crossed" , "0" , "position closed"]
110 |
111 | elif( LSL_cross and flag == 0 and (not buy_flag)):#......places "BUY" order if PCR crosses lower stoploss band to close a trade
112 | flag = 1
113 | buy_flag = False
114 | sell_flag = False
115 | pro = future_cost - transaction_start_price
116 | order_details = [1,"Buy" , "LSB crossed" , "stoploss executed" , "position closed"]
117 | elif( (future_cost - transaction_start_price) > abs_SL and flag == 0 and (not buy_flag)):#......places "BUY " order if PCR crosses lower stoploss #absolute value
118 | flag = 1
119 | buy_flag = False
120 | sell_flag = False
121 | pro = future_cost - transaction_start_price
122 | order_details = [1,"Buy" , "LSB crossed" , "stoploss executed abs" , "position closed"]
123 |
124 | elif (mAvg_cross_down and flag==0 and (not sell_flag)):#.....places "SELL" order if PCR crosses mAvg from high to low to close a trade
125 | flag = 1
126 | sell_flag = False
127 | buy_flag = False
128 | pro = -(Data['future'][i] - transaction_start_price)
129 | order_details = [-1,"Sell" , "mAvg crossed (h to l)" , "0" , "position closed"]
130 |
131 | elif(USL_cross and flag==0 and (not sell_flag)):# ..places "SELL" order if PCR crosses upper stoploss band to close a trade
132 | flag = 1
133 | sell_flag = False
134 | buy_flag = False
135 | pro = -(Data['future'][i] - transaction_start_price)
136 | order_details = [-1,"Sell" , "USB crossed" , "stoploss executed" , "position closed"]
137 |
138 | elif((-future_cost + transaction_start_price) > abs_SL and flag==0 and (not sell_flag)):# ..places "SELL" order if PCR crosses upper stoploss #absolute value
139 | flag = 1
140 | sell_flag = False
141 | buy_flag = False
142 | pro = -(Data['future'][i] - transaction_start_price)
143 | order_details = [-1,"Sell" , "USB crossed" , "stoploss executed_abs" , "position closed"]
144 |
145 |
146 | else:
147 | if(buy_flag==0 and sell_flag==0): tempo = "0"
148 | else:
149 | if(buy_flag==1 and sell_flag==0): tempo = (Data['future'][i] -transaction_start_price) * 500
150 | if(buy_flag==0 and sell_flag==1): tempo= (-Data['future'][i] +transaction_start_price) * 500
151 | order_details = [0,"No trade" , "no trade" , "0" , tempo]
152 |
153 |
154 | profit.append(pro)
155 | order.append(order_details[0])
156 | buy_sell.append(order_details[1])
157 | trade_cause.append(order_details[2])
158 | stoploss.append(order_details[3])
159 | mtm.append(order_details[4])
160 |
161 | #------------------------------------------------------------------------------------------------------------------------------
162 | #buy/sell logic ends================================================================================================================
163 |
164 | Data['placed_order'] = pd.Series(order) #...............................converting list to pandas series
165 | Data['cost'] = -(Data['placed_order'].multiply(Data['future'])) *500# ..cost at each transaction
166 | Data['out'] = Data['cost'].cumsum()# ...................................out is the cumulative cost profit/loss after transactions till now
167 | Data['buy_sell'] = pd.Series(buy_sell)
168 | Data['profit'] = -pd.Series(profit) * 500
169 | Data['stoploss'] = pd.Series(stoploss)
170 | Data['trade_cause'] = pd.Series(trade_cause)
171 | Data['mtm'] = pd.Series(mtm)
172 | print Data['out']
173 |
174 |
175 |
176 | output = pd.DataFrame() #....final output to be stored in excel file
177 | output['date'] = Data1['Date']
178 | output['Close'] = Data['future']
179 | output['PCR'] = Data['PCR']
180 | output['placed_order'] = Data['placed_order']
181 | output['buy_sell'] = Data['buy_sell']
182 | output['trade_cause'] = Data['trade_cause']
183 | output['PnL'] = Data['profit']
184 | output['mtm'] = Data['mtm']
185 | output['stoploss'] = Data['stoploss']
186 | output['Cash Account'] = Data['out']
187 | output.to_excel('PCR_SL_output.xlsx', sheet_name='Sheet1')
188 |
189 | #plt.plot(order)
190 | plt.plot(Data['PCR'])
191 | plt.plot(Data['mAvg'])
192 | plt.plot(Data['UBB'])
193 | plt.plot(Data['LBB'])
194 | #plt.plot(Data['out'])
195 | plt.show()
196 |
197 |
198 | #Copyright QuantInsti Quantitative Learning Private Limited
199 |
--------------------------------------------------------------------------------
/Section-4/VIX.py:
--------------------------------------------------------------------------------
1 | #importing required packages
2 | import pandas as pd
3 | import quandl
4 | import matplotlib.pyplot as plt
5 | import math
6 | def fetch_data(string1,string2,string3,filename):
7 | w = quandl.get(string1,authtoken = string2, start_date = string3)
8 | w.to_csv(filename)
9 | w = pd.read_csv(filename)
10 | return w
11 |
12 | #the data pulled from quandl and stored locally for faster execution
13 | Data1 = fetch_data( "CHRIS/CME_SP1", "mq-W7Z-QXBDZ1MxaN-Vy", "2014-12-12" ,"local_future.csv")
14 | Data = fetch_data("CBOE/VIX", "zaYDtiD-pcyPCwWr3_Py", "2014-12-12","VIX_data.csv")
15 |
16 | Data['future'] = Data1['Last']
17 | Data['VIX'] = Data['VIX Close']
18 |
19 | mtm = list()
20 | order_details = list()
21 | order = list()#.........................a list which stores the transactions ( -1:"BUY" , 1:"SELL" , 0:"DO NOTHING")
22 | profit = list()
23 | buy_sell = list() #.....................a list which tells buy/sell in words!
24 | stoploss = list()
25 | pro = 0 # profit( which happens( +/-) at the end of each transaction )
26 | v=0 #.................................. V is the buying price and 3/4 % above v will be the selling price
27 | thresh = 22 #..........................VIX threshold for placing a buy order
28 | change_1 = 5 #..........................% above which to sell for a profit
29 | change_2 = 5 #..........................% below which to sell in a stoploss
30 | buy_flag = False#.......................indicates if last order was a buy
31 | sell_flag = True # ....................indicates if last order is a sell
32 | s = Data['future'].size#................size of the VIX dataset
33 | c_1 = (1 + (change_1)/float(100) ) #....c_1 is the value above which the sell order will execute in a successful trade
34 | c_2 = (1 - (change_2)/float(100) ) #....c_2 is the value below which a sell order will execute in a stoploss
35 |
36 | #buy/sell order logic begins=======================================================================================================
37 | for i in range(s):
38 | pro = 0
39 |
40 | if(Data['VIX'][i] >=thresh and (not buy_flag)): #........IF THRESHOLD IS CROSSED THEN "BUY"
41 | order_details = [-1,"Buy" , "0", "position taken"]
42 | buy_flag = True
43 | sell_flag =False
44 | v = Data['future'][i] #..............................PRICE AT WHICH WE "BUY"
45 |
46 | elif(Data['future'][i] >= (c_1)*v and (not sell_flag)):#...IF future price is c_1 times v, then "SELL" ( profit )
47 | buy_flag = False
48 | sell_flag = True
49 | pro = (Data['future'][i] - v) #profit= (selling price - the buying price)
50 | order_details = [1,"Sell" , "0", "position closed"]
51 |
52 | elif(Data['future'][i] <= (c_2)*v and (not sell_flag)):#...IF future price is c_2 times v , then "SELL" ( loss )
53 | buy_flag = False
54 | sell_flag = True
55 | pro = (Data['future'][i] - v)
56 | order_details = [1,"Sell" , "Stoploss executed", "position closed"]
57 | else:
58 | if(buy_flag ==1): x = (Data['future'][i] - v ) * 500* 2
59 | else: x = "0"
60 | order_details = [0,"No trade" , "0", x]
61 |
62 | profit.append(pro)
63 | order.append(order_details[0])
64 | buy_sell.append(order_details[1])
65 | stoploss.append(order_details[2])
66 | mtm.append(order_details[3])
67 |
68 |
69 | #buy/sell logic ends================================================================================================================
70 |
71 | Data['stoploss'] = pd.Series()
72 | Data['mtm'] = pd.Series(mtm)
73 | Data['placed_order'] = pd.Series(order)
74 | Data['stoploss'] = pd.Series(stoploss)
75 | Data['buy_sell'] = pd.Series(buy_sell)
76 | Data['profit'] = pd.Series(profit) *500*2
77 | Data['cost'] = (Data['placed_order'].multiply(Data['future'])) *500*2 #the cost at each transaction : buy/sell * (future price)
78 | Data['out'] = Data['cost'].cumsum() # out is the cumulative cost... profit/loss after transactions till now
79 | print (Data['out'])
80 |
81 | output = pd.DataFrame() #....final output to be stored in excel file
82 | output['date'] = Data['Date']
83 | output['Close'] = Data['future']
84 | output['VIX'] = Data['VIX']
85 | output['placed_order'] = Data['placed_order']
86 | output['buy_sell'] = Data['buy_sell']
87 | output['profit'] = Data['profit']
88 | output['mtm'] = Data['mtm']
89 | output['account'] = Data['out']
90 | output['stoploss'] = Data['stoploss']
91 | output.to_excel('VIX_SL_output.xlsx', sheet_name='Sheet1')
92 |
93 | #plt.plot(Data['placed_order'] * 1000)
94 | plt.plot(Data['out'])
95 | #plt.plot(Data['future'])
96 | #plt.plot(Data['VIX'])
97 | plt.show()
98 |
--------------------------------------------------------------------------------