import yfinance as yf import pandas as pd import numpy as np from sklearn.linear_model import LinearRegression from sklearn.model_selection import train_test_split import matplotlib.pyplot as plt # Fetch historical data for the stock stock_symbol = "DKNG" # Replace with your stock symbol df = yf.download(stock_symbol, start="2020-01-01", end="2024-01-01") # Calculate Simple Moving Average df['SMA'] = df['Close'].rolling(window=20).mean() # Calculate Exponential Moving Average df['EMA'] = df['Close'].ewm(span=20, adjust=False).mean() # Calculate RSI delta = df['Close'].diff() gain = (delta.where(delta > 0, 0)).rolling(window=14).mean() loss = (-delta.where(delta < 0, 0)).rolling(window=14).mean() rs = gain / loss df['RSI'] = 100 - (100 / (1 + rs)) # Calculate MACD exp1 = df['Close'].ewm(span=12, adjust=False).mean() exp2 = df['Close'].ewm(span=26, adjust=False).mean() df['MACD'] = exp1 - exp2 df['Signal_Line'] = df['MACD'].ewm(span=9, adjust=False).mean() # Selecting Features df = df.dropna() X = df[['SMA', 'EMA', 'RSI', 'MACD', 'Signal_Line']] y = df['Close'] # Splitting the data into training and testing sets X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, shuffle=False) # Create and train the model model = LinearRegression() model.fit(X_train, y_train) # Predict the stock price predicted_price = model.predict(X_test) # Plotting the results plt.figure(figsize=(14, 7)) plt.plot(df.index[-len(y_test):], y_test, color='blue', label='Actual Price') plt.plot(df.index[-len(y_test):], predicted_price, color='red', linestyle='--', label='Predicted Price') plt.title(f'Stock Price Prediction for {stock_symbol}') plt.xlabel('Date') plt.ylabel('Price') plt.legend() plt.show()