Homepage Forums Get Help Predicting upcoming stock prices using Python. Can you show me an example?

  • Satya Mukherjee

    Administrator
    April 12, 2023 at 11:40 pm
    Upvote
    Up
    1
    Down
    Downvote
    ::

    Of course it is possible. Now the accuracy is somewhat debatable, but for the sake of it, let me demonstrate using yFinance data.

    To plot the predicted stock price for Apple using yfinance data for the next 7 days, we will need to use a machine learning model that can make predictions based on historical data. One popular machine learning model used for predicting stock prices is the Long Short-Term Memory (LSTM) model.

    To use the LSTM model, we will first need to retrieve historical data using the yfinance package. We will then use this data to train the LSTM model and use the trained model to make predictions for the next 7 days.

    Here is some sample code to retrieve the historical data and train the LSTM model:

    import yfinance as yf

    import pandas as pd

    import numpy as np

    from datetime import datetime, timedelta

    from sklearn.preprocessing import MinMaxScaler

    from tensorflow.keras.models import Sequential

    from tensorflow.keras.layers import Dense, LSTM

    from matplotlib import pyplot as plt

    apple = yf.download('AAPL', period='1y')

    data = apple.filter(['Close'])

    data.index = pd.to_datetime(data.index).tz_localize('UTC')

    dataset = data.values

    training_data_len = int(len(dataset) * 0.8)

    scaler = MinMaxScaler(feature_range=(0, 1))

    scaled_data = scaler.fit_transform(dataset)

    x_train = []

    y_train = []

    for i in range(60, training_data_len):

    x_train.append(scaled_data[i - 60:i, 0])

    y_train.append(scaled_data[i, 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(50, return_sequences=True, input_shape=(x_train.shape[1], 1)))

    model.add(LSTM(50, return_sequences=False))

    model.add(Dense(25))

    model.add(Dense(1))

    model.compile(optimizer='adam', loss='mean_squared_error')

    model.fit(x_train, y_train, batch_size=1, epochs=1)

    test_data = scaled_data[training_data_len - 60:, :]

    x_test = []

    y_test = dataset[training_data_len:, :]

    for i in range(60, len(test_data)):

    x_test.append(test_data[i - 60:i, 0])

    x_test = np.array(x_test)

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

    predictions = model.predict(x_test)

    predictions = scaler.inverse_transform(predictions)

    preds_df = pd.DataFrame(predictions, index=data.index[training_data_len + 60:], columns=['Prediction'])

    actuals_df = pd.DataFrame(y_test, index=data.index[training_data_len:], columns=['Actual'])

    merged_df = pd.merge(actuals_df, preds_df, how='left', left_index=True, right_index=True)

    plt.figure(figsize=(16, 8))

    plt.title('Predicted vs Actual Stock Price for Apple')

    plt.xlabel('Date')

    plt.ylabel('Price (USD)')

    plt.plot(merged_df['Actual'], label='Actual')

    plt.plot(merged_df['Prediction'], label='Prediction')

    plt.legend()

    plt.show()