Stock Market

Neural Networks Stock Market – Predicting Stock Prices in Python

neural-networks-stock-market-predicting-stock-prices-in-python

Neural Networks Stock Market – Highest Rated?

In today’s video we learn how to predict stock prices in Python using recurrent neural network and machine learning.

DISCLAIMER: This is not investing advice. I am not a professional who is qualified in giving any financial advice. This is a video purely about programming using financial data.

Timestamps:
0:00 Intro
0:18 Disclaimer
2:01 Loading Financial Data
4:55 Preparing Data
9:07 Neural Network Model
12:59 Testing The Model
22:19 Visualizing Predictions
23:39 Price Prediction
26:58 Company Predictions
28:41 Outro

◾◾◾◾◾◾◾◾◾◾◾◾◾◾◾◾◾
📚 Programming Books & Merch 📚
💻 The Algorithm Bible Book: https://www.neuralnine.com/books/
🐍 The Python Bible Book: https://www.neuralnine.com/books/
👕 Programming Merch: https://www.neuralnine.com/shop

💻 Exclusive Content 💻
👥 Patreon: https://www.patreon.com/neuralnine

🌐 Social Media & Contact 🌐
📱 Website: https://www.neuralnine.com/
📷 Instagram: https://www.instagram.com/neuralnine
🐦 Twitter: https://twitter.com/neuralnine
🤵 LinkedIn: https://www.linkedin.com/company/neuralnine/
📁 GitHub: https://github.com/NeuralNine

🎵 Outro Music From: https://www.bensound.com/

Thanks for watching the Neural Networks Stock Market video!

Watch the Neural Networks Stock Market video on Youtube

29 Comments
Share

29 Comments

  1. Haydn Beherzt
    July 31, 2021 at 12:09 am

    I am interested in why are you choosing that topology of the neural network. Why 3 LSTM layer each with 50 neurons. It is clear why the last layer is of one neuron. But the previous ones are a mystery.

  2. Mustansir Husain
    July 31, 2021 at 12:09 am

    Thank you for the informative video. 1 question though. I wrote the exact code as shown and tested with 2 companies separately "FB" and "AAPL". Both times I got almost flat line for "Predicted Price". What could be the reason for that?

  3. random guy
    July 31, 2021 at 12:09 am

    Me watching it:
    Dont understand anything:
    Keep watching:

  4. J Flow
    July 31, 2021 at 12:09 am

    Looks like a rolling average to me.

  5. Fox Snips
    July 31, 2021 at 12:09 am

    Source code?

  6. Muhammad Valiallah
    July 31, 2021 at 12:09 am

    Great video, I however think there is an error in the calculation for the next day prediction. When the range function is used earlier the last element is not included in the list. so range(1,5) will return the highest index of 4. So at line 87, it should by real_data=[model_inputs[len(model_inputs)-prediction_days: len(model_inputes), 0]]. This creates 70 input variables

  7. Hari Paudel
    July 31, 2021 at 12:09 am

    You'll surpass 500k within 2022

  8. Sylvio Saraiva
    July 31, 2021 at 12:09 am

    These videos recorded while coding are the best! please keep producing them

  9. Eunchan Nahcnue
    July 31, 2021 at 12:09 am

    import numpy as np
    import matplotlib.pylot as plt
    import pandas as pd
    import pandas_datareader as web
    import datetime as dt

    from sklearn.preprocessing import MinMaxScaler
    from tensorflow.keras.models import Sequential
    from tensorflow.keras.layers import Dense, Dropout, LSTM

    company = 'FB'

    start = dt.datetime(2012, 1, 1)
    end = dt.datetime(2021, 1, 1)

    data = web.DataReader(company, 'yahoo', start, end)

    scaler = MinMaxScaler(feature_range=(0, 1))
    scaled_data = scaler.fit_transform(data['Close'].values.reshape(-1, 1))

    prediction_days = 60

    x_train = []
    y_train = []

    for x in range(prediction_days, len(scaled_data)):
    x_train.append(scaled_data[x-prediction_days:x, 0])
    y_train.append((scaled_data[x, 0]))

    x_train, y_train = np.array(x_train), np.array(y_train)
    x_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], 1))

    model = Sequential()

    model.add(LSTM(untis=50, return_sequences=True, input_shape=(x_train.shape[1], 1)))
    model.add(Dropout(0.2))
    model.add(LSTM(untis=50, return_sequences=True))
    model.add(Dropout(0.2))
    model.add(LSTM(untis=50))
    model.add(Dropout(0.2))
    model.add(Dense(units=1))

    model.compile(optimizer='adam', loss='mean_squared_error')
    model.fit(x_train , y_train, epochs=25, batch_size=32)

    test_start = dt.datetime(2021, 1, 1)
    test_end = dt.datetime.now()

    test_data = web.DataReader(company, 'yahoo', test_start, test_end)
    actual_prices = test_data['Close'].values

    total_dataset = pd.concat((data['Close'], test_data['Close']), axis=0)

    model_inputs = total_dataset[len(total_dataset)-len(test_data)-prediction_days:].values
    model_inputs = model_inputs.reshape(-1, 1)
    model_inputs = scaler.transform(model_inputs)

    x_test = []

    for x in range(prediction_days, len(model_inputs)):
    x_test.append(model_inputs[x-prediction_days:x, 0])

    x_test = np.array(x_test)
    x_test = np.reshape(x_test, (x_test.shape[0], x_test.shape[1], 1))

    predicted_prices = model.predict(x_test)
    predicted_prices = scaler.inverse_transform(predicted_prices)

    plt.plot(actual_prices, color="black", labels=f"Actual {company} price")
    plt.plot(predicted_prices, color="green", label=f"Predicted {company} price")
    plt.titile(f"{company} Share Price")
    plt.xlabel('Time')
    plt.ylabel(f'{company} Share Price')
    plt.legend()
    plt.show()

    real_data = [model_inputs[len(model_inputs)+1-prediction_days:len(model_inputs+1), 0]]
    real_data = np.array(real_data)
    real_data = np.reshape(real_data, (real_data.shape[0], real_data.shape[1], 1))

    prediction = model.predict(real_data)
    prediction = scaler.inverse_transform(prediction)
    print(f"prediction: {prediction}")

  10. Hayath Basha
    July 31, 2021 at 12:09 am

    Hi,

    Is it possible to convert below the input

    Customer_Name,Product_1,Price_1,Product_2,Price_2
    Zayn,Milk,30,Chocolate,40
    Peter,Cheese,190,Oil,80
    Andrew,Coconut,10,Milk,60
    Dwayne,Soya,100,Butter,120

    to this output where the Product name should be ascending and it should also have its price in the next column

    Customer_Name,Product_1,Price_1,Product_2,Price_2
    Zayn,Chocolate,40,Milk,30
    Peter,Cheese,190,Oil,80
    Andrew,Coconut,10,Milk,60
    Dwayne,Butter,120,Soya,100

    Can you please help

  11. Sajid Ahamed
    July 31, 2021 at 12:09 am

    Hey I'm a new coder and I would like to know how to feed our own data from sheets to this code..??
    Thanks in advance

  12. Fabian Z
    July 31, 2021 at 12:09 am

    Nice tutorial. But please put your facecam to another place 🙂

  13. C0dak W0lfgaang
    July 31, 2021 at 12:09 am

    Which yahoo api is that ? Complete name of the Api and its author ? Would be easier that way to find it in the list of packages.

  14. Stan Suen
    July 31, 2021 at 12:09 am

    Thanks! Love your videos. Wonder if there is a good way to detect pattern (instead of predict future prices) such as inverse head-and-shoulder and cup-and-handle?

  15. Mubashir Hasan
    July 31, 2021 at 12:09 am

    Awesome hands on tutorials! Best place to find quick python projects

  16. Varun Naharia
    July 31, 2021 at 12:09 am

    I followed the video but I am getting this error can you please explain the reason

    Traceback (most recent call last):
    File "/Users/Varun/PycharmProjects/StockPrediction/main.py", line 17, in <module>
    data = web.DataReader(company)
    File "/Users/Varun/StockPrediction/lib/python3.6/site-packages/pandas/util/_decorators.py", line 199, in wrapper
    return func(*args, **kwargs)
    File "/Users/Varun/StockPrediction/lib/python3.6/site-packages/pandas_datareader/data.py", line 373, in DataReader
    raise NotImplementedError(msg)
    NotImplementedError: data_source=None is not implemented

  17. Leo Liu
    July 31, 2021 at 12:09 am

    Oh my god it’s just serial correlation

  18. Yori Coppens
    July 31, 2021 at 12:09 am

    This is crazy, exactly what I needed.

  19. Damian Games
    July 31, 2021 at 12:09 am

    I am interested in the theory and maths! Also, top quality video.

  20. Parth Anand
    July 31, 2021 at 12:09 am

    can anyone write line 59 :- model_inputs = total_dataset[len(total_datase – len(test_voice – prediction_days:]).value)]

  21. nakul goswami
    July 31, 2021 at 12:09 am

    G8 work man
    👍👍👍👍👍👍👍👍👍👍👍
    👍👍👍👍👍👍👍👍👍👍👍

  22. superoriginalname
    July 31, 2021 at 12:09 am

    not sure how this is much better than a moving average

  23. Zulfadli Zein
    July 31, 2021 at 12:09 am

    I immediately hit the subscribe button. Nice content, keep up the good work.

  24. Wudda
    July 31, 2021 at 12:09 am

    I decided to take your advise and invest big on the results of my program….LETS GOOOO 😎🚀

    Edit: I've had 4 days of constant losses. Hmm… Maybe I need to make riskier investments??

    Edit2: I've spent my almost my entire life savings…$400,350 so far.

    Edit 3: I wasted my sons college money. Feel kind of bad but honestly he's not that smart so he probably would have dropped out.

    Edit 4: Wife left me.

    Edit 5: Got some shady loan shark to lend me $5k …. we got this 😎😎🚀🚀🚀🚀

    Edit 6: This is all satire in case that wasn't obvious. Excellent video btw! Don't be silly with your money.

  25. Reza Javadzadeh
    July 31, 2021 at 12:09 am

    thank you

  26. Dante Silvia
    July 31, 2021 at 12:09 am

    Title: Predicting Stock Prices

    "This is not a video about predicting stock prices."

  27. MrJegerjeg
    July 31, 2021 at 12:09 am

    How the price of the share can affect the model? Does it make a difference $1 per share to $100 per share? I guess the optimizer won't behave the same with different scales.

  28. Yundong Cai
    July 31, 2021 at 12:09 am

    Line 87 should be

    real_data = [model_inputs[len(model_inputs) + 1 – prediction_days: len(model_inputs) + 1, 0]]

  29. Regele IONESCU
    July 31, 2021 at 12:09 am

    For those in need, here is the entire code, tested and working in Python 3.8.5:

    import numpy as np
    import matplotlib.pyplot as plt
    import pandas as pd
    import pandas_datareader as web
    import datetime as dt

    from sklearn.preprocessing import MinMaxScaler
    from tensorflow.keras.models import Sequential
    from tensorflow.keras.layers import Dense, Dropout, LSTM

    #Load Data
    company = 'FB'

    start = dt.datetime(2012, 1, 1)
    end = dt.datetime.(2020, 1, 1)

    data = web.DataReader(company, 'yahoo', start, end)

    #Prepare Data
    scaler=MinMaxScaler(feature_range=(0,1))
    scaled_data=scaler.fit_transform(data['Close'].values.reshape(-1,1))

    prediction_days = 60

    x_train=[]
    y_train=[]

    for x in range(prediction_days, len(scaled_data)):
    x_train.append(scaled_data[x-prediction_days:x, 0])
    y_train.append(scaled_data[x, 0])

    x_train, y_train = np.array(x_train), np.array(y_train)
    x_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], 1))

    #Build the Model
    model = Sequential()

    model.add(LSTM(units=50, return_sequences=True, input_shape=(x_train.shape[1], 1)))
    model.add(Dropout(0.2))
    model.add(LSTM(units=50, return_sequences=True))
    model.add(Dropout(0.2))
    model.add(LSTM(units=50))
    model.add(Dropout(0.2))
    model.add(Dense(units=1)) #prediction of the next closing value

    model.compile(optimizer='adam', loss='mean_squared_error')
    model.fit(x_train, y_train, epochs=25, batch_size=32)

    '''Test the model accuracy on existing data'''

    #Load Test Data
    test_start=dt.datetime(2020, 1, 1)
    test_end=dt.datetime.now()

    test_data = web.DataReader(company, 'yahoo', test_start, test_end)
    actual_prices=test_data['Close'].values

    total_dataset=pd.concat((data['Close'], test_data['Close']), axis=0)

    model_inputs=total_dataset[len(total_dataset)-len(test_data)-prediction_days:].values
    model_inputs = model_inputs.reshape(-1, 1)
    model_inputs = scaler.transform(model_inputs)

    # Make Predictions on Test Data
    x_test=[]

    for x in range(prediction_days, len(model_inputs)):
    x_test.append(model_inputs[x-prediction_days:x, 0])

    x_test=np.array(x_test)
    x_test=np.reshape(x_test, (x_test.shape[0], x_test.shape[1], 1))

    predicted_prices=model.predict(x_test)
    predicted_prices=scaler.inverse_transform(predicted_prices)

    # Plot the test predictions
    plt.plot(actual_prices, color = "black", label=f"Actual {company} Price")
    plt.plot(predicted_prices, color="green", label=f"Predicted {company} Price")
    plt.title(f"{company} Share Price")
    plt.xlabel("Time")
    plt.ylabel(f"{company} Share Price")
    plt.legend()
    plt.show()

    #Predict Next Day

    real_data = [model_inputs[len(model_inputs)+1-prediction_days:len(model_inputs+1), 0]]
    real_data = np.array(real_data)
    real_data=np.reshape(real_data, (real_data.shape[0], real_data.shape[1],1))

    prediction=model.predict(real_data)
    prediction = scaler.inverse_transform(prediction)
    print(f"Prediction: {prediction}")