Hey everyone! I’ve been tinkering with a Python script to predict Tesla’s stock price over the next 14 business days, and I’m excited to share it with you. This isn’t just a basic linear regression—it’s got some cool technical indicators like RSI and Bollinger Bands, skips weekends and U.S. holidays, and even adds a touch of volatility-based noise for realism. Want to see where TSLA might be headed? Let’s dive in!
What’s This Script Do?
- Fetches Data: Grabs Tesla’s historical prices from Yahoo Finance (yfinance).
- Technical Indicators: Uses closing prices, 5-day and 20-day moving averages, RSI (momentum), and Bollinger Bands (volatility).
- Predicts 14 Business Days: Skips Saturdays, Sundays, and U.S. holidays (thanks to the holidays library).
- Adds Noise: Simulates market randomness with reduced noise (half the historical volatility) so it’s not wildly swinging between $160 and $300+ every run.
The result? A forecast that’s more informed than a simple trend line but still acknowledges the chaos of the stock market. Here’s the code:
import yfinance as yf
import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression
from datetime import datetime, timedelta
import matplotlib.pyplot as plt
import holidays
us_holidays = holidays.US()
def fetch_tesla_data():
ticker = "TSLA"
stock = yf.download(ticker, start="2024-01-01", end=datetime.today().strftime('%Y-%m-%d'))
return stock
def calculate_rsi(data, periods=14):
delta = data.diff()
gain = (delta.where(delta > 0, 0)).rolling(window=periods).mean()
loss = (-delta.where(delta < 0, 0)).rolling(window=periods).mean()
rs = gain / loss
rsi = 100 - (100 / (1 + rs))
return rsi
def prepare_data(df):
df = df[['Close']].copy()
df['MA5'] = df['Close'].rolling(window=5).mean()
df['MA20'] = df['Close'].rolling(window=20).mean()
df['RSI'] = calculate_rsi(df['Close'], periods=14)
df['BB_Middle'] = df['Close'].rolling(window=20).mean()
df['BB_Std'] = df['Close'].rolling(window=20).std()
df['BB_Upper'] = df['BB_Middle'] + (df['BB_Std'] * 2)
df['BB_Lower'] = df['BB_Middle'] - (df['BB_Std'] * 2)
df = df.dropna()
df['Target'] = df['Close'].shift(-1)
df = df[:-1]
df['Returns'] = df['Close'].pct_change()
volatility = df['Returns'].std()
return df, volatility
def train_model(df):
X = df[['Close', 'MA5', 'MA20', 'RSI', 'BB_Upper', 'BB_Lower']]
y = df['Target']
model = LinearRegression()
model.fit(X, y)
return model
def is_business_day(date):
return date.weekday() < 5 and date not in us_holidays
def predict_next_14_business_days(model, df, volatility):
last_data = df.tail(1)[['Close', 'MA5', 'MA20', 'RSI', 'BB_Upper', 'BB_Lower']].values[0]
predictions = []
future_dates = []
days_ahead = 0
business_days_count = 0
while business_days_count < 14:
next_date = datetime.today() + timedelta(days=days_ahead + 1)
if is_business_day(next_date):
next_price = model.predict([last_data])[0]
noise = np.random.normal(0, 0.5 * volatility * last_data[0]) # Reduced noise
next_price += noise
predictions.append(max(next_price, 0))
future_dates.append(next_date)
new_close = next_price
new_ma5 = (last_data[0] * 4 + new_close) / 5
new_ma20 = (last_data[2] * 19 + new_close) / 20
delta = new_close - last_data[0]
new_rsi = min(max(last_data[3] + (delta * 2), 0), 100)
new_bb_std = df['BB_Std'].iloc[-1]
new_bb_upper = new_ma20 + (new_bb_std * 2)
new_bb_lower = new_ma20 - (new_bb_std * 2)
last_data = [new_close, new_ma5, new_ma20, new_rsi, new_bb_upper, new_bb_lower]
business_days_count += 1
days_ahead += 1
return future_dates, predictions
def plot_results(historical_df, future_dates, predictions):
plt.figure(figsize=(12, 6))
plt.plot(historical_df.index, historical_df['Close'], label='Historical Close', color='blue')
plt.plot(future_dates, predictions, label='Predicted Close (Next 14 Business Days)', color='red', linestyle='--')
plt.title('Tesla Stock Price Prediction (Next 14 Business Days)')
plt.xlabel('Date')
plt.ylabel('Price (USD)')
plt.legend()
plt.grid()
plt.show()
if __name__ == "__main__":
tesla_data = fetch_tesla_data()
prepared_data, volatility = prepare_data(tesla_data)
model = train_model(prepared_data)
future_dates, predictions = predict_next_14_business_days(model, prepared_data, volatility)
print("Predicted Tesla Stock Prices for the Next 14 Business Days:")
for date, price in zip(future_dates, predictions):
print(f"{date.strftime('%Y-%m-%d')}: ${price:.2f}")
plot_results(tesla_data, future_dates, predictions)
How to Run It
You’ll need these libraries: yfinance, pandas, numpy, scikit-learn, matplotlib, and holidays. Install them with:
bash
pip install yfinance pandas numpy scikit-learn matplotlib holidays
Run the script, and it’ll spit out a 14-day forecast with a plot of historical and predicted prices. The noise is toned down (half the volatility), so you won’t see crazy jumps to $160 or $300+ every time—though it still varies a bit, as stocks should!
Why the Variation?
You might notice the predictions change slightly each run. That’s the np.random.normal noise at work, mimicking market unpredictability. Want consistency? Add np.random.seed(42) at the top or remove the noise entirely by commenting out those lines in predict_next_14_business_days.
What’s Next?
This is a fun starting point, but stock prediction is tricky (no crystal balls here!). I’m thinking of adding MACD or testing a Random Forest model—any suggestions? Try it out, tweak it, and let me know what you think in the comments. Happy coding, and here’s hoping TSLA heads where you want it to!