[go: up one dir, main page]

0% found this document useful (0 votes)
330 views18 pages

Estimate Support and Resistance of A Stock With Python

Estimate Support and Resistance of a Stock with Python

Uploaded by

FabioSantos
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
330 views18 pages

Estimate Support and Resistance of A Stock With Python

Estimate Support and Resistance of a Stock with Python

Uploaded by

FabioSantos
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 18
tat Supt rR ta Sok th Pye y Sahn Sa Pon a Fae rh, 221 ae Estimate Support and Resistance ofa Stock with Python How you can estimate a stock’s support and resistance lines using linear regression Soman oiikar (Foicn ] Feb 4: Sinead [iv fm Photo by Chris iverani In this article, I will be showing you how you can estimate a stock's support and resistance lines using the Python programming language. If you are only interested in the code for this project, then you can check out my Githiub repository here. Step 1. Installing the necessary modules First, create a file and title it equi renents ext . Next, you can find the necessary modules for this project over her paste itin your requirenents.txt file, Now in your terminal or command Go ahead and copy them, then prompt, run the following command. oxsinetienconpfnsnghin arlene nepali SE ae ‘moot tat Supt an Reeac ta Se th Pen [5 ar |Pon fo ae rh, 221 aston pip install -r requirenents.tat Step 11. Import the necessary modules Importny hots wth © oy us view Step 2. Getting the closing prices of a stock In this article, we will primary be focusing on the AAPL stock over the time period of January 1, 2019 to April 1, 2019, but you can apply this same algorithm to other stocks over a different time period. To get the closing prices of a stock, be will be using the pandas dataseader. 2 df = web.catoteacer(sybely "yahoo", "28-82-01", *2019-08-02") loc dna. hosted wth O by Gite view oxinediniptorssinarlseoaime.getarsnesasndtrtwtheorongenaptn an itd we stat Sino ars Rese fa Soh Pyn Stan Oar |Pson nae rn F221 etn The result of this will be a pa.2a:aesane object, with 6 columns. High, low, open, close, volume, and adj close. Since we only want to look at the closing prices, we can do this. 1 series = df'chose'] 2 rerloe-tndox = np.arang(series-rhape(o]) antes py hota with © by Gita evr In these lines of code, we are creating a ps.ceries object and storing the closing prices of the API stock inside that variable, Next we are setting the index of the series to be an array of consecutive numbers between 0 and the number of closing prices we have. If you print the series, you will get this. 39 35.5 6.982498 37.687500 st 46.697498, 5847-11750, 47180000 471487499 Moxinedinoiporbinarlnesrams.getardnesancndttwtheorongenaptin an itd we 61 47810001 Nane: Close, Length: 62, dtype: float6s 1 tn yn by San ar an Fa Eh | Fa, 204 [Mn You can plot the series and get a visual representation of it by using matplotli pteseittesynol) pttextael 0395") pit.ylabel(“Prsces") pitoplot(series, 1adelsymbot) it.) pit.ehoat) ot anplpy hosed wth © by tub view AAPL e{— 46 a 42 Prices 40 Moxinediniporsinarlnesramsigetandnesacndtntewtheorongenaptn in itd woe oa Pion nae nn | F221 etn 38 36 o 10 20 30 40 50 60 Days So far, our code looks like this. 10 df = weboatoeader(syaboty “yateo", "2039-01-01, “2018-86-81°) 12 sertes = de('cose'] 12. serfes.tndex = op.arange(serses, shapes) step2 py hosted wth © by Sb view Step 3. Smoothening our graph Moxinedincoiporrsinerlnesras.gestarnesancndttwthorongenapt in ited we aman Spot Rance ef Sa th yn Right now, our data on the graph looks quite bumpy and doesn't look good to do any computer analysis on. In this step, we are going to try to smoothen our graph using the savgoi_citter function from the scipy.signa: module. oa Pion nae nn F221 etn ‘The savgo1_¢titer function takes in 3 parameters. Your array, a window length, and a polyorder. I won't be going to deep into these, however, feel free to check out their documentation on this function over here. Our array is obviously going to be our series, You can think of the window length as the level of smoothness you want in your data. The higher window length the more smooth your graph will be and the lower the window length, the less smooth your graph will be. To determine, the window length we want to use, [have created a small algorithm, which I will show you in just a minute. For this project, we will keep the polyorder equal to a constant, number as 3. Step 31. Determine the smoothness To determine the smoothness we want, we need to find the amount of months worth of data we have. Since each month has approximately 30 days, we will intergern divide the amount of prices we have by 30. We will store this in a variable called montn_a: ©. If sonth_ais® is equal to 0 then we will edit the value to 1, Now to determine the smoothness of a graph, we multiply our monch_aier by 2 and add it with 3. Moxinedinoiporbinarlnesrams.getardnesancndttwtheorongenaptin an itd we pt reece tS th Pyen ySahn Sa [Pon ae Eri, 221 aes orem stff = serter.tape[8] // 28 Tateger divide the nuber of prices we have Oy 30 4 smooth = Soe(2 * nonLehft 4 3) # Sinple algo co determine encothess pts = savgol_tilter(serses, snot, 3) # Get the smoothed price dt ‘We can visualize this once again using matplotlib. 2 pteittetsymet) 2 pitaataber(oys") 3 pttaylobel(riees") 4 pttcoloctets, 1abel-Fsosoth (synbo1)") 5 pitstegend(> pit show) plot moet hosted wih © by Givi ow AAPL, 48) — smooth AAPL. 46 44 oxinedinciporsbinarlnestrasigestardnesancndtrtwtheorongenaptin an tid 1 tn yn by Stan ar an Fa Eh | Fe, 204 [Mn oar = 40 38 36 0 10 20 30 40 50 60 Days We can visualize these in comparison like this. plestttletsyio}) pitexlabe( 055") pit-ylabl(‘Prsces') pit.plot(sriee, Iabel-syntol) pltplot(pts, Zabel snaoth (sytbal)") pue-tegendt) pit.showt) ot py honed wih © ty Gia view re AAPL AAPL, 8 ‘Smooth AAPL. Moxinedincoiporsinerlsesrasigestardnesacndtnscwtheorongenaptn in ited oe ‘moot stat Sino ars Resse fa Sn ih Py oy Stan Oar |Pson nae Er F221 an 0 10 20 30 40 50 60 Days Step 4. Identifying local minimum and local maximum points To identify the local minimum and maximum points of a graph, I have created a simple function. or pytnagiona, ta) ssa = (peale] = peony * 2 bsg = (pats) + peasy) oa Moxinedinoiporsbinerlnetranagetarsnenandtntocwtheorongeneaptin in ited sone or sn Retre Sc th yn [iy Sha ar tan Fa Eh | Fe, 04 [Mn 7 lwalsin = 1 © eest am = 11 8 prev.sts = ((, st8[8D. Cs BLEED 20 for E La rageta, Leaots) ~ 2) a spend. = 2 + ptstial > ttt « ptstta 3 sopendto = “nin “ ute ots{ina) € atsit) > pts = provstatance = pythogtorev ps[®], prev pte[:]) * 8.5 » cure stanee = ythagtorevpts(2], (i, pts{iI)) 2 rev pta(0) © arevt3(2] 2 prev tata) = CL ptst8D) 2 6 pend. to oa ni cel plnvappend((y pt5{4))> 26 ocl.nax.oppend((y ots)? » prev pts(0) > prevptst3] » ev ts{3] = Ue otsti)) 2 cal ran apsend((s, 83400) toc min many hs wih © by itis ior Moxinedincoiporrsinerlnesras.gestarnesancndttwthorongenapt in ited tat Supt an Resac ta Sc th Pen [yS Essentially, this function loops through the given p:s from indexes 1 to nar Jon Pan Ere Fee, 27 |Men If the point is less than the point behind it and less than the point ahead of it, then itis a local minimum. Similarly, if the point in greater than the point be and greater than the point ahead of it, isa local maximum. However, if we simply do this, then the algorithm will detect many local minimums and maximums. Therefore, I have used the Pythagorean theorem to determine the distance between the previous point and current point, as well as the distance between the current point and next point. I made sure to only consider a point as a local maximum or minimum if the distance between it and the next point was greater than half of the distance between it and the previous point. Here is the result of plotting the local maximum and minimum points. AAPL — Smooth AAPL Moxinedincoiporssbinarlnesramsigestardnesancndttwtheorongenaptin in itd sae ‘moot stat Sint ars Resse ta Sn ih Py Stan Oar |Pson a ae rn | F221 etn 40 38 36 0 10 20 30 40 50 60 Days Step 5. Line of best fit between local minimum and maximum Now we are going to find two lines of best fit. One for the local minimums and one for the local maximums. To do this, we will be using the sKlearn LinearRegression model. As you might already know, the equation for a linear line is y = mx + b, where mis the slope and bis the y intercept. We will create a function that will return the slope and y-intercept of a set of points et regression ceo(ss) ‘be eiven points Moxinedinciporbinerlnesramsigetandnesacndteswtheorongenaptn in itd sane pt resect Sot th Pyne Sabana |For Fae Er, 221 aes oct pln_slope, 1cal_nin_int = repression ceof(10ee nln) 20 cal_pae soe, 200aT_mog_ int « regression ceot(10e1_moe) regression cet py hosted with by Gite view First we need to get the x and y points from pts , $0 to do this, we will be using list comprehension. Remember that ps is a list of a tuple of points. [Oe VDE G2, 2)e Be BP UB ¥4Ie OS) YI A= [otto] sor ot An pts] 2 ¥ = {pt(s] 4or ot An pts] 6x parry 1 y= renareayQ) 9 # Me ned to reshage to (1,19, Because that ds the format thas sklearn wil expect the Jnput 22 Moresnagelt 3) Moxinedinipiorsbinarlsesraia.petaranesandntnetorongwneap tn ted see ‘moot ar |Pon fo ae rh, 221 aston ‘To we just have to create a LinearRegression model and fit our x and y data. 1 det regression ceor(ps) 2 X= mparay(ipeie) for pt £9 atsDseeshope(-L, 3) 3 ye mpasaytipe(a) for wt 29 ats) 6nd = Linear tagressfont) 5 modesty 9} loeal_ninsope, local pin snt = regression cof {local nin) lecl_pax_slope, local_pox int « repression ceof(leel pox) Step 6. Creating support and resistance lines Creating the support and resistance lines will be fairly simple. We will use the equation y = mx + b. 1 otysmenee Moxinedinoiporinerlnesrams.gestantnesacndttwtheorongenaptin nite v8 ‘moot tat Supt an Resac ta Sc th Pen [yS 2 support = (Locl_pin slope * na.arrey(sertes.tndex) + 20ca} nest nar Jon Pan Ee Feo, 27 |Aen ocala slope * npwarray(serses.inéex)) + Local nin Now it’s time to plot our support and resistance lines and see how accurate they are. This is how they look on the smooth graph. AAPL — Smooth AAPL 481 — support — Resistance 46 a4 Ea 40 38 36 0 yw 20S Days Mosman coiporhinerlnesrams.getantnesacndtntwthorongenaptn in iti ‘moot tat Supt an Reeac ta Se th Pen [5 This is how they look on the real graph. nar Jon Pan Ere Fee, 27 |Men pisstle(eymol) ple atel(‘oays") pls ylatel(‘Prices") Lapel-syntol) (eumort, Label'support', ce") plt.plottreststance, label-"Resistance', ce") pits tegendt) AAPL — APL — Support — Resistance Moxinedincoiporinerlnesrasigestansnesacndtntcewtheorongentaptn in itd sme ‘moot tat Supt nese tS ah Pye by Saban Oa [Pon a Fae ri F221 Maen eT 0 10 20 30 40 50 60 Days It looks quite accurate to me. You can get the code and Jupyter Notebook for this project in my GitHub repository over her Python Stocks Algorithms DstaSeionce Programming Learn more. Make Medium yours. Share your thinking. Moxinedincoiporrsinerlnesras.gestarnesancndttwthorongenapt in ited se

You might also like