Predicting Stock Prices (Python)
- April 11, 2024
- Posted by: MainInstructor
- Category: C Data Science Go Python
Video Title: Predicting Stock Prices – Learn Python for Data Science #4
Hello world it’s Suraj in this episode we’re gonna build a stock price prediction graph using scikit-learn in 40 lines of Python have you ever wanted to get rich quick sir my models are very profitable I always retrain them to prevent overfitting three times a week those are rookie numbers in this racket
Really how often do you retrain I might have to work out and then once ah the stock market allows you to buy and sell units of ownership in a company which we call stocks if the company’s profits go up you own some of those profits if they
Go down you lose profits with them it’s as simple as that so if you were to buy stocks and the right company at the right time you could become rich overnight is there something we could do to predict future stock prices given a data set of past
Prices this sounds like a data science problem but according to the efficient market hypothesis the stock market is random and unpredictable but major financial firms like JP Morgan and Goldman Sachs have been hiring quantitative traders for years to build predictive models on past market data
And you can be sure that if these firms do have profitable models for trading they are not gonna share it with us come at me Wall Street they have no incentive to think about all the features we could incorporate into a financial model sentiment analysis on company opinions past stock prices sales
Growth dividends all the profits Warren be missed for hating on Bitcoin changes in stock prices are not completely random but very close to it good traders will use predictive models as a tool when deciding where to invest and we’re gonna build three different predictive models that predict the prices of Apple
Stock then plot them all on a graph to compare their results our steps will be to install our dependencies collect our data set write our scripts and analyze our graph these are our four dependencies CSV will allow us to read data from the CSV file of stock prices
That we later download numpy will let us perform calculations on our data so IKEA learn will let us build a predictive model and map top live will let us plot our data points with our models on a graph for us to analyze let’s collect our data set we want a list of stock
Prices from the past 30 days and we can get this data easy from Google Finance as you can see it’d be much higher if they didn’t miss the boat on AI next step write our script our four dependencies are here at the top and we’ll use the given names to
Reference them throughout our code one thing to note about map talk live is that since it’s a graphical library it’ll depend on a graphical back-end and there are several options if it doesn’t want to plot a graph on your machine for some reason just use the switch back-end
Option and try out a few different possible backends all right let’s start hacking on our script first let’s initialize two empty lists dates and prices well then write a function called get data that will fill them both with the relevant data we’ll call it get data
And it’s argument will be the name of our stock prices CSV file well use the width as block to open our file and assign it to the CSV file variable the open statement will extract the contents of our CSV file to read it hence the R parameter next we’ll want to create a
File reader variable which the CSV module will create for us using the reader method with our CSV file has the parameter this will allow us to iterate over every row in our CSV file and we can return a string for each line using the next method we’ll call the next
Method first to skip the first row since it’s just column names now for each row in our CSV file reader we’ll add both the date and price values to our respective lists the append function will allow us to add an item to the end of our list we only want the day
Of the month so we’ll say get that first column in our row which is that the index 0 and use the split function to remove the dashes between each of those three values then get that first value in the list which is the day we’ll wrap
That using the in turkey were to convert the day to an integer for prices will append that list as well with the opening price which is in the next column of our row and convert that to a float to be more precise in our later calculations okay not that precise well
Place the return statement at the end to finish our with block let’s move on to our second and last helper function called predict price to build our predictive model and graph it well first use numpy to format our list into an n by 1 matrix the three parameters will be
The list we want to reshape the new shape which will be a one dimensional array the size of our dates list and finally the order of elements let’s create three models each of them will be a type of support vector machine a support vector machine is a linear
Separator it takes data that’s already classified and tries to a set of unclassified data so if we only had two data classes it would look like this it would be the line such that the distances from the closest points and each of the two groups would be farthest
Away when we add a new data point to our graph depending on which side of the line it is we could classify it accordingly with a label but right now we’re not predicting a class label so we don’t need to classify instead we’re predicting the next value in a series
Which means we want to use regression SVM’s can be used for regression as well the support vector regression is a type of SVM that uses the space between data points as a margin of error and predicts the most likely next point in a data set let’s create our first model a linear
Support vector regression well use the svr module we imported from scikit-learn to create it and it’s going to take three parameters the kernel which is a type of SVM then our penalty parameter C of the error term we want two things when using an svr align with the largest
Minimum margin in a line that correctly separates as many instances as possible but we can’t always have both C determines how much we want the latter our next SVR is polynomial in math folklore the no free lunch theorem states that there are no guarantees for one optimization to work better than the
Other so we’ll try both also if you work at Google you actually do get free lunch so take that finally will create one more SVR using a radial basis function our bf defined similarity to be the Euclidean distance between two inputs if both are right on top of each other the
Max similarity is 1 if too far it’s a zero our gamma defines how far to far is and let’s fit or train each of our models on our date and price data using the fit method it’s time to create our graph we’ll plot the initial data points
As black dots with the data label and plot each of our models as well we’ll use the predict method of the svr object in scikit-learn using the dates matrix as our parameter each will be a different color and we’ll give them a distinct label we can set the x axis and
The y axis accordingly and we’ll add a title in a legend the show function will display it on the screen and we’ll want to return the predictions from each of our models now we can call our get data method on our CSV and create a variable to store our predicted price given our
Dates and prices for this date will print out results for each of our models the command line let’s analyze our graph we can see that each of our models shows up in our graph and that the RBF model seems to fit our data the best so we can
Use its prediction in command line to stack dead presidents so to break it down the efficient market hypothesis states that the data needed to set the prices for tomorrow stocks only come from tomorrow but well-tuned machine learning models can give us predictions that are slightly better than random if
We use the right data and support vector machines are a type of ML model that can be used for both classification and regression to predict novel data points in a graph the winner of the coding challenge from last week’s video is Victor Cyrano Victor created a system that recommends artists to users using
The last FM music data set badass of the week and the runner-up is Kevin Nelson he demoed his own recommender algorithm the challenge for this video is to create a financial model to predict stock prices with a neural network using both price history and sentiment analysis has features details are in the
Code readme poster github link in the comments and i’ll announce the winner in the next video please subscribe for more programming videos and for now I’ve got to predict snapchats IPO price so thanks for watching
-
Sale!
Wireless WIFI Repeater Extender Amplifier Booster 300Mbps
$29.99$14.99 Add to cartWireless WIFI Repeater Extender Amplifier Booster 300Mbps
Categories: Electronics, Wi-Fi Router, Wireless Wi-Fi Extender Tags: 300Mbps, 802.11N, Amplifier, Booster, Extender, mobile wi-fi booster, Remote, WIFI, Wireless, Wireless WIFI, Wireless WIFI Repeater, Wireless WIFI Repeater Extender, Wireless WIFI Repeater Extender Amplifier, Wireless WIFI Repeater Extender Amplifier Booster, Wireless WIFI Repeater Extender Amplifier Booster 300Mbps$29.99$14.99 -
Sale!
Full RGB Light Design Gaming Headset Headphones with Mic
$24.99$14.99 Add to cartFull RGB Light Design Gaming Headset Headphones with Mic
Categories: Electronics, Gaming, Gaming Headsets Tags: Design, Full, Full RGB Light Design Gaming Headset, Full RGB Light Design Gaming Headset Headphones, Full RGB Light Design Gaming Headset Headphones with Mic, Gamer, Gaming, Gaming Headset Headphones, gaming headset wireless, Headphone, Headphones, Headset, Light, Mic, Package, RGB$24.99$14.99 -
Sale!
Wireless BlueTooth Multi-Device Keyboard Mouse Combo
$39.99$19.99 Add to cartWireless BlueTooth Multi-Device Keyboard Mouse Combo
Categories: Electronics, Gaming, Gaming Keyboards, Keyboard Mouse Combos Tags: Combo, Keyboard, keyboard mouse combos, Mouse, MultiDevice, Set, WireKeyboard Mouse Combo, Wireless, Wireless BlueTooth Keyboard Mouse Combo, Wireless BlueTooth Keyboard Mouse Combos, Wireless BlueTooth Multi-Device Keyboard Mouse Combo, Wireless BlueTooth Multi-Device Keyboard Mouse Combos$39.99$19.99 -
Sale!
High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar
$199.99$139.99 Add to cartHigh Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar
Categories: Gaming, Gaming Chairs Tags: Adjustable, Chair, computer chairs, Desk, Executive, Gaming, Girl, Headrest, High, High Back Leather Executive Adjustable Swivel Gaming Chair, High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest, High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar, High Back Leather Executive Adjustable Swivel Gaming Chairs, Leather, Lumbar, Office, Racing, Swivel$199.99$139.99 -
Sale!
Professional LED Light Wired Gaming Headphones with Noise Cancelling Microphone
$29.99$19.99 Select optionsProfessional LED Light Wired Gaming Headphones with Noise Cancelling Microphone
SKU: N/A Categories: Electronics, Gaming, Gaming Headsets Tags: Cancelling, Gaming, Gaming Headphones with Noise Cancelling Microphone, gaming headset, Headphones, Headset, LED, Light, Mic, Microphone, Noise, Professional, Professional LED Light Wired Gaming Headphones, Professional LED Light Wired Gaming Headphones with Noise Cancelling Microphone, Wired, Wired Gaming Headphones, Wired Gaming Headphones with Noise Cancelling Microphone$29.99$19.99 -
Sale!
Gaming Desk with LED Lights USB Power Outlets and Charging Ports
$349.99$249.99 Select optionsGaming Desk with LED Lights USB Power Outlets and Charging Ports
SKU: N/A Categories: Computer Desk, Gaming, Gaming Desk Tags: and Charging Ports, Charging, Desk, Desks, Gaming, gaming desk with led lights, Gaming Desks with LED Lights, Home, LED, Lights, Monitor, Office, Outlets, Port, Power, Room, Stand, USB, USB Power Outlets, White, Workstation$349.99$249.99 -
Sale!
Wired Mixed Backlit Anti-Ghosting Gaming Keyboard
$99.99$79.99 Add to cartWired Mixed Backlit Anti-Ghosting Gaming Keyboard
Categories: Electronics, Gaming, Gaming Keyboards Tags: Antighosting, Backlit, Blue, brown, Gaming, Gaming Keyboard, gaming keyboards, gaming keyboards and mouse, Keyboard, Laptop, Switch, Wired, Wired Mixed Backlit Anti-Ghosting Gaming Keyboard, Wired Mixed Backlit Anti-Ghosting Gaming Keyboards, Wired Mixed Backlit Gaming Keyboard$99.99$79.99 -
Sale!
Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset
$119.99$59.99 Add to cartWireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset
Categories: Electronics, Gaming, Gaming Headsets Tags: 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset, ANC, Audio, Bluetooth, Cancellation, Ear, Earphone, gaming headset, Headphones, Headset, Hi-Res Over the Ear Headphones Headset, HiRes, Noise, Wireless, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Headphones, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headsets$119.99$59.99 -
Sale!
Wired Sports Gaming Headset Earbuds with Microphone
$19.99$9.99 Select optionsWired Sports Gaming Headset Earbuds with Microphone
SKU: N/A Categories: Gaming, Gaming Headsets Tags: Accessories, Earbud, Earphone, Earphones, Gaming, gaming headset with microphone, Headphones, Headset, IOS, Microphone, Sports, Wired, Wired Sports Gaming Headset Earbuds, Wired Sports Gaming Headset Earbuds with Microphone, Wired Sports Headset Earbuds$19.99$9.99 -
Sale!
150W Universal Multi USB Fast Charger 16 Port MAX Charging Station
$49.99$29.99 Add to cart150W Universal Multi USB Fast Charger 16 Port MAX Charging Station
Categories: Charging Stations, Electronics Tags: 150W, 150W Charging Station, 150W Universal Multi USB Charging Station, 150W Universal Multi USB Fast Charger 16 Port MAX Charging Station, 150W Universal Multi USB Fast Charger 16 Port MAX Charging Stations, 150W Universal Multi USB MAX Charging Station, 16 Port MAX Charging Station, 3.5A, Charger, Charging, Fast, laptop charging stations, Max, Multi, Port, Stand, Station, Universal, USB$49.99$29.99
Spoiler alert: I am a stock market trader and investor, NOTHING and NO ONE can predict stock prices Period
I like your video. However, I have some questions, so according to your video, you will have a predicted price of over $660 for a certain date. Do you think that's correct? please correct me of I am wrong. I am just learning
Dude, the way you explain the things… easily and with fun. The best teacher ever I know. Thank you for these amazing video lessons.
Can we have techno fund to predict rather than only on price
A great video. Reading the reviews it seems a lot of poeple are missing the point. The value of your output is the enthusiasm and inspirations to seek further knowledge. Those hoping to watch a 6 minute video then make a fortune the following day will always just be dreamers.
it looks overfitting
i couldn't get it to display the graph. don't have any errors. video might be outdated now. or it may be the data csv file.?
Wow that was way past my knowledge. But cool
I know this is an old video, I just wanted to compliment you on your ability to take a very complex topic, and explain it like I'm five. I've heard it said in the past that if you can't Eli 5 a topic then you don't really know it as well as think you do. However, you've displayed that you know this topic very very well. Fantastic job.
This does not work xDDD OMG
dates.append(int[1].split('-')[1])
TypeError: 'type' object is not subscriptable
its throwing me this error
Never use such algorithm and you will never get trap, actual stock market is more than the calculations
it's extremely fast and too hard to follow. Slow down and repeat the steps. Not everyone is a fast learner.
Nice
How did u predict snpachat ipo price when there is no historical stock data?
These new gourp of "technical traders" are so naive but they do have an impact in the market. Real traders also take into account for their behaviour.
The last lines no not work. It appears he intentionally caused a Syntax error using ')' in "predicted_prices." Secondly, you will get an invalid int error if your csv file has a string (such a month July, August, etc.) in the headers of the columns. He doesn't give a workaround. I just changed the column to a 2 Digit month instead of eliminating the column.
Never appeared to me getting rich was soooo easy
Is it racist that your voice REALLY surprised me lol great video man ty!
This is a great video. I am using it in my own website about this topic here: https://binbitforex.site/forecasting-stock-prices/
I learned a lot from your series when I was a student. now I work at a trading fund and use ML for actual trading… it is not your expertise for sure lol and your modeling is completely wrong. please do what you do better
on line 43 I got a bug
what is it? predicted)price = …. predicted_price = ….. or something else?
Where is the prediction? All you did was do the regression of the data. Overfiting the model completly. What I am. Missing?
neat but just play
@@@@@@@@@@@@@@@@Hello, my name is Nagesh Dubey and I am the owner of the "Golden Games" company. I want to talk to you about our company's business cooperation. Please contact me! You will get rich returns, and our company guarantees that you can get commissions every day. (Telegram) APP account +91 70913 55779
This was just regression.
One can't just use regression to "predict" stock prices as everyday the parameters involved are changing.
Stock prices prediction involves a lot of different statistical concepts like Brownian Motion, Random Walk etc.
There are different models in finance like Black-Scholes equation, Monte Carlo Simulation etc. which take into account these parameters.
You have to know a decent amount of math to build a stock prediction algorithm
pete
You need to split the training and testing data bro
So what was the prediction?
Hello Siraj brother, how you become so expert in machine learning and data science stuff. Please guide me how should I learn. You are awesome. You look so confident I don't know how you are doing that. How you easily see problems and solves them in minutes. Please brother I am newbie from India to this field, having experience in programming.
Also, one cool way to get stock data.
symbol = 'MSFT'
df = web.DataReader(symbol, data_source='yahoo', start='2012-01-01', end='2020-01-01')
data = df.filter(items = ['Open'])
One of the best courses I have taken on my career-building Python skills to succeed as a data scientist.
https://www.datacamp.com/tracks/data-scientist-with-python?tap_a=5644-dce66f&tap_s=841152-474aa4
With no prior coding experience in Python, I learn how easily this language allows you to import, clean, manipulate, and visualize data—all integral skills for any aspiring data professional or researcher.
I would recommend all my linked connections with similar interests looking to boost their Python skills and wanting to begin their journey to becoming a confident data scientist should try out this awesome course by DataCamp.
You guys can follow me on my social media profiles for the projects i have done as a data scientist.
Github: https://github.com/abhiwalia15
LinkedIn: https://www.linkedin.com/in/mrinal-walia-b0981b158/
#python #datascience #machinelearning #deeplearning #datacamp #ai #bigdata #covid19 #computervision #artificialintelligence #Datacamp
Search for Trading Bots ?
https://app.proquant.com/shared/strategy/bdb5f119-b267-4b9d-aaa3-13c38a792708
Am I the only lunatic here, or you just can do that in excel without a single line of code.??