Stock Market Prediction: Train a neural network to predict stock prices

How to train a neural network to predict stock prices logo


During the month of December last year, I started researching on the stock market and I stumbled upon helpful information I thought I would share. I learned about the analysis needed in order to excel as the 1% of stock traders. I asked myself, “But what if I combined some machine learning to predict stock prices?” Now, we are ready to cram years worth of work in weeks! Strap on and let’s start the journey.

Season 1 Yes GIF by Final Space - Find & Share on GIPHY
Yes By Final Space

History and Background of The Stock Markets

A stock is simply a theoretical percentage of ownership of a company’s value. The concept of trading commodities and debts started out in the 16th Century. Even so, the modern concept of the stock markets was started by the Dutch later on. In those days, large amounts of capital was needed to start large companies. This amount was impossible to be raised by a single individual . Thus, investors pulled funds together and divided the company’s value among themselves. The percentages were in order of their contributions, of course.

Stock market quotes
Stock Market Price Quotes at the London Stock Exchange

The Modern Stock Markets

Thereafter, the concept of shares became widely adopted and thus a centralized marketplace was needed. A group of stock traders met at a London coffee shop to do the trades. Soon in 1773, they bought the coffee shop and converted it into the London Stock Exchange we know of today. The idea of a stock market spread to other countries and it has now become global.

Basically, in order for your investment to be profitable it means that the price of the overall shares must be higher than the invested amount. However, it is very difficult to know when the price will go up. The price of stocks is controlled by a number of factors that makes it complex to predict. That is why I named the title ‘predict stock prices’ and not ‘make money from the stock market.’ Either way, you will see how you can predict stock prices with minutes of training.

Analysis of the Stock Market

In stock market analysis, there is three key things that you need to follow:

Fundamental analysis: It entails assessing the monetary value of the organization. It keeps in mind the economic conditions of where the company is. It is also dependent on the financial conditions and the overall performance of the company. A thorough investigator would most definitely look into the reports, budgetary proportions and other information that could be utilized to anticipate the eventual fate of an organization. The technique utilizes incomes, profit, future development, return on value, overall revenues and other information to decide an organization’s fundamental esteem and potential for future development.

Technical Analysis: In contrast to fundamental analysis, the expert basically examines the pattern and trends in the shares’ prices. The basic presumption is that market prices are a function of the supply and demand for the stock, which thus mirrors the value of the organization. This strategy additionally trusts that past patterns are a sign of future trends.

Sentimental Analysis: Market sentiment is the general speculation towards a specific security or stock available in the stock market. The attitude of the investors influence this highly and it could be triggered by the news or just a report released by the company.

Training the Neural Network

Happy Animation GIF by Tony Babel - Find & Share on GIPHY
Happy Robot by Tony Babel

Artificial Intelligence has progressed over the years. Typical AI’s can do years worth of work in weeks depending on the computational power provided. In this article, we will be focusing on technical analysis. To see sentimental analysis in use check out this article.

We will use a subset of Machine Learning called Deep Learning which is based on learning data representations. We will then try to make educated guesses by using probability calculations and training our model to spot the patterns in our dataset. Our deep learning model will be supervised in that we will give it inputs and set the parameters. We will also provide it with an expected output to train on.

We will obtain our dataset from the Investing website which has data ranging from economic calendars to past opening and closing prices in the stock market. After scraping the stock market closing prices, we will train an LSTM Network to find long-term patterns in our dataset. The dataset should be a continuous column of closing prices. Do not add any heading. Add zeros to blank data (normalization). If by any chance you are not aware of web scraping, follow this article.

The Code:

The link to the LSTM Network I used can be found here. Otherwise, let’s jump in to the actual code used to predict the stock market quotes.

#Importing the dependencies needed for the project.
from keras.layers.core import Dense, Activation, Dropout
from keras.models import Sequential
from keras.layers.recurrent import LSTM
import lstm, time #helper libraries

#Loading the data. You may need to convert the XLS to CSV
X_train, y_train, X_test, y_test = lstm.load_data('eur/usd.csv', 50, True)
#Building the model
model = Sequential()




start = time.time()
model.compile(loss='mse', optimizer='rmsprop')
print 'compilation time : ', time.time() - start

#Step 3 Train the model

#Step 4 - Plot the predictions!
predictions = lstm.predict_sequences_multiple(model, X_test, 50, 50)
lstm.plot_results_multiple(predictions, y_test, 50)

The prediction

As you can see, the model worked with some degree of success. It predicted the big leaps successfully. However, it had problems with the small leaps. The training data was at least seven years long and the test data was two years long. For better results, you could either train the model longer or use more test data. Either way, I will repeat by saying that the stock market is highly volatile and is driven by a lot of factors.

In the next article, we will be combining sentiment analysis and technical analysis. The sentiment analysis will include designing a bot which scrapes news data from Investopedia and The data obtained will be fed through a model that uses NLP (Natural Language Processing) to discern alerting news that can influence prices in the stock market.

Hope this article has helped you in one way or another. Feel free to comment if you get stuck.

More Resources on stock market predictions:

Stock Price Prediction | AI in Finance | Siraj Raval

Reference: Siraj Raval – How to train a neural network to predict stock prices #7

How to train a neural network to predict stock prices | Mark Gacoka
Article Name
How to train a neural network to predict stock prices | Mark Gacoka
Artificial Intelligence has progressed over the years. Typical AI's can do years worth of work in weeks depending on the computational power provided. In this article, we will be focusing on technical analysis.
Publisher Name
Mark Gacoka Website
Publisher Logo

78 thoughts on “Stock Market Prediction: Train a neural network to predict stock prices

  1. Heya great blog! Does running a blog such as this take a lot
    of work? I have no understanding of programming but I was hoping
    to start my own blog soon. Anyways, if you have any suggestions or
    tips for new blog owners please share. I know this is
    off topic nevertheless I just needed to ask. Appreciate

  2. Online dating can be the perfect solution in case you want to satisfy singles within your area.
    If things walk out of hand then leave immediately and change your username.
    The choice ‘s all yours, can you wants to share your existing
    email, your telephone numbers, your address and in many cases your surname.

  3. If you have a personality you will subsequently be intriquing, notable and that is what the audience or public wish to see.
    Learning piano online offers value and flexibility that merely aren’t available with an individual piano teacher.
    One rule of all graphic identity programs is that institutions
    have to have their logos standardized; if the institution doesn’t standardize logo marks, people will have trouble recognizing the logos
    and what it represents.

  4. If you want something changed, cropped differently, or perhaps in any manner altered, you
    might have someone who will do this in your case (often times included at no extra cost).

    But before you take time for exercising before your TV; it’s going to greatly help if you achieve to understand your body’s mechanism.
    During this time, Beck tirelessly searched out venues that might allow
    him on stage to execute, with his fantastic tireless efforts eventually led to .

  5. If you have a personality then you will be intriguing and that’s what the crowd or public
    need to see. If you like money then I would be a rapper and
    rhyme regarding the streets as a one who reflect the path scene with the rhymes.

    One rule of most graphic identity programs is that institutions have to have their logos standardized; if an institution doesn’t standardize logo marks,
    the public may have a hard time recognizing the logos and what it really represents.

  6. Of course, if you choose a free site, you’ll have a lot more than social contact based on your mood as well as the friends
    you’re making on each site. Now, nothing is to think about because internet world and online dating sites services have eradicated this trouble.
    By it is quite nature, however, online dating as
    you may know it, is infested with scammers and syndicates,
    and that means you are advised to apply some wise practice and use some extra
    caution when joining those hitherto unknown online dating sites websites that most
    of your sudden spring up and they are boasting of the veritable selection of Russian women coming from all ages
    and from all regions.

  7. To do your very best, all of your mental energy must
    be concentrated within the present. Certain things that particular should take into account while selecting a picture are:
    . During this time, Beck tirelessly searched out venues that will allow him on stage to complete,
    and his awesome tireless efforts eventually generated .

  8. Good post. I learn something new and challenging on blogs I stumbleupon on a daily basis.

    It’s always helpful to read through articles from other writers and use something from
    their websites.

  9. Image editors are also helpful to create backgrounds, edit looks of subjects, so that the overall album looks nicer and brighter.

    Some Wedding Dance lessons Melbourne offer these trainings at best rate
    you are able to imagine and also some ones offer discounts
    as well. The Wedding Photography Las Vegas therefore ends up being most
    questionable photography as the photographer offers this extra duty and responsibility to take out
    the loved ones along with their loving activities with the photography other than highlighting the bride as
    well as the bridegroom.

  10. Hashtags are able to be familiar with create “groupings” on Twitter,
    without needing to alter the basic service. Since city courses
    never allow refunds, everybody thought we would put it out a
    bit further. The minimalist approach for the driveway actually
    accentuates the home’s entrance.

  11. After all, it’s not difficult for website visitors to detect what you’re considering on the Internet just by intercepting the signals.

    Answer: Arcada, California – Useless Fact: Brothers Dick and Mac Mc –
    Donald open a hot dog stand referred to as the Airdome in Arcadia, California.
    Those who are thinking about participating only at that level must audition first prior to accepted to the program.

  12. The online on-line games makes its market around the globe and entertaining many players of every age group.
    One of the hottest sites that the teens may wish to
    visit is liven up the portals which contain games for teens that they will enjoy.
    There are a lot of people who start using these games as being a stress buster for themselves and the others find then fun from a long day
    of work.

  13. There is much help accessible to you in terms of understanding how to play guitar so you needs
    to be using this. Alicia Silverstone was provided the
    part of Valerie Malone but turned it lower before
    getting given to Tiffani Thiessen. The child sits on his
    mother’s right knee, but the left knee will be really hard to deal with.

  14. Kindly remember that they you might be expecting to win is referred to as the favourite while the team you might be hoping to
    lose is known as the underdog. It is extremely latest internet betting,
    that’s getting a lot of popularity among youngsters from all avenues of
    life, teenagers and older people. On another hand, Queensland has also
    shown a massive course of spending in past few years.

  15. To do your very best self, all of your mental energy needs to be concentrated in the present.
    Excellent teachers are in demand and in most cases curently have lots
    of students. For the Dalai Lama, the spiritual leader in the Gelug sect of Tibetan Buddhism, to become so thought
    to be probably the most influential person of the year inside the
    western world is a great example from the respect we ought to all show toward other religions along
    with the acceptance of views which do not always mirror our own.

  16. Make your profile as appealing as is possible, use catchy phrases and prevent being boring.
    The online dating sites arena is growing immensely as more and more individuals are relying on internet to satisfy new people,
    find their special someone, friendship and more activities.
    You have complete control you want to make contact with and which team you
    need to block from.

  17. What’s Taking place i am new to this, I stumbled upon this I have discovered It absolutely useful and it has aided me out loads.
    I am hoping to contribute & assist different users like its helped me.
    Good job.

  18. I am sure this post has touched all the internet people, its really really nice piece of
    writing on building up new webpage.

  19. Unquestionably believe that which you said. Your favorite justification seemed to be on the net the simplest thing to be aware of.
    I say to you, I definitely get annoyed while people consider
    worries that they just do not know about. You managed to hit the nail
    upon the top and defined out the whole thing without having side-effects , people can take
    a signal. Will probably be back to get more.

  20. Right here is the perfect web site for anybody who wants to understand this topic.
    You understand a whole lot its almost hard to argue with you
    (not that I personally will need to…HaHa).
    You certainly put a new spin on a topic that has been discussed for years.
    Excellent stuff, just wonderful!

  21. Oh my goodness! Incredible article dude! Thanks,
    However I am having difficulties with your RSS.

    I don’t know the reason why I am unable to join it.
    Is there anybody having identical RSS issues? Anyone that knows the solution can you kindly
    respond? Thanx!!

  22. Excellent blog right here! Additionally your site a lot up very
    fast! What host are you using? Can I get your affiliate hyperlink
    on your host? I desire my site loaded up as quickly as yours lol

  23. Make your profile as appealing as possible, use catchy phrases
    and steer clear of being boring. Now, to acquire quite near to see your face,
    you just need an ideal date with them o concerning produce a comfortable
    invest his or her heart. You have complete control you want to make contact with and which you desire
    to block from.

  24. Hey There. I discovered your weblog the usage of msn. This is a very well
    written article. I’ll make sure to bookmark it and come back to read more of your
    useful info. Thank you for the post. I’ll certainly comeback.

  25. Hey Folks….Listen, If you’re just plain FED-UP THEN YOU REALLY SHOULD READ THIS….We have developed a True Long Term Business and
    removed ALL of the roadblocks for ANYONE to make a
    Great Online Income. Roadblock 1. One time $10 Returned as Commissions
    Instantly! Roadblock 2. No Nagging Monthly Payments.

    Roadblock 3. Guaranteed to at least Break Even Your Very First Day.
    Roadblock 4. If you can copy & paste you can sponsor others and Grow Your Business (and
    Earn $5.00 for each). Roadblock 5. You don’t have
    to talk with anyone. Roadblock 6. Both Basic and High level
    Marketing Training Included; Products that Make You Money.
    If you have never made a dime online that will change, Guaranteed.
    Just Imagine for a minute the Security and Freedom you will have being
    able to make Great Money Online where ever you are and whenever
    you want. See for Yourself Sincerely, Ronald Kerr

  26. It’s a shame you don’t have a donate button! I’d definitely donate to this excellent blog!

    I guess for now i’ll settle for bookmarking and adding your RSS feed to my Google account.
    I look forward to fresh updates and will talk about this
    blog with my Facebook group. Chat soon!

  27. We are a bunch of volunteers and starting a new scheme
    in our community. Your web site offered us with useful info to work on.
    You’ve done an impressive task and our whole community will likely be thankful
    to you.

  28. When I originally commented I clicked the “Notify me when new comments are added” checkbox
    and now each time a comment is added I get four emails with the same comment.
    Is there any way you can remove people from that service? Thanks!

  29. Hi terrific blog! Does running a blog similar to this take a massive amount work?
    I’ve virtually no knowledge of programming however I was
    hoping to start my own blog in the near future. Anyhow, should you have any recommendations or tips for new blog owners
    please share. I understand this is off subject nevertheless I just
    needed to ask. Thanks a lot!

  30. My brother recommended I might like this web site.

    He was totally right. This post truly made my day. You cann’t
    imagine just how much time I had spent for this information! Thanks!

  31. Hello there! This post couldn’t be written any better!
    Reading through this post reminds me of my good old room mate!
    He always kept chatting about this. I will forward this article to him.

    Fairly certain he will have a good read. Thanks for sharing!

  32. If you are looking for a credit card with one of those banks, and
    cash advances matter to you, we recommend you
    keep watch over their variations. Other issuers mostly provide the identical rates of interest on all the playing cards they
    supply. US Bank is the one exception.

  33. Taking money advance in on-line retailers would imply a difference for the reason that utility course of there is simple.
    You’ll endure the method very merely not like financial institution transactions
    which are very strict.

  34. These with unfavorable credit ratings historical past comparable to CCJs, IVA, arrears,
    may also apply for service provider cash advance for his or her small businesses, as lenders
    approve the quantity without any credit check.
    The rate of curiosity levied is comparatively larger, however
    with stiff competition among the many lenders, you do have great chances to obtain money advance at aggressive charges.

  35. You need to learn the way the systwm is powered and internet site
    a support system in case there is failure, it’s not good being locked from your gun safe because the battery
    died. These both have the purpose of attrzcting the animals
    to some select spot. Drugs, Sex, and Alcohol are some in the infamous cliches that flood our culture.

  36. If an overall improvement in health insurance and conditioning can be your aim, then go for it get yourself a treadmill to the home.
    All of the methods are intended for those people who are adequately fit and healthy.
    Even if your place is small, you cann still comfortably possess the
    collapsible treadmill set up mainly because it helps save space.

  37. Hi there, I found your blog by the use of Google whilst searching for a similar
    topic, your web site came up, it appears good. I’ve bookmarked it in my google bookmarks.

    Hi there, just become alert to your weblog through
    Google, and located that it’s truly informative. I’m gonna watch out for brussels.
    I will be grateful should you continue this in future.
    A lot of people will probably be benefited out of your writing.

  38. A capacitor is oftentimes oval but a majority
    of usually round currently and appears a little like an easy tin can with terminals on top.
    We just cannot get caught up with everything, no knowing whether or not
    to placed on a supplementary layer or please take a layer off.
    If any problems are found, they are often repaired before they become serious.

Leave a Reply

Your email address will not be published.