Repository navigation
Expand file tree
/
Copy pathCode
More file actions
62 lines (51 loc) · 1.8 KB
/
Copy pathCode
File metadata and controls
62 lines (51 loc) · 1.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import yfinance as yf
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score
# ----------------------------
# Step 1: Fetch Stock Data
# ----------------------------
ticker = "AAPL" # You can change this (e.g., 'TSLA', 'MSFT', 'GOOG')
print(f"Fetching stock data for {ticker}...")
data = yf.download(ticker, start="2020-01-01", end="2025-01-01")
data = data[["Close"]] # Keep only Closing price
data.dropna(inplace=True)
print(data.head())
# ----------------------------
# Step 2: Prepare Dataset
# ----------------------------
data["Days"] = np.arange(len(data)) # Numerical index as feature
X = data[["Days"]]
y = data["Close"]
# Train-test split (80-20 split)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, shuffle=False)
# ----------------------------
# Step 3: Train Model
# ----------------------------
model = LinearRegression()
model.fit(X_train, y_train)
# ----------------------------
# Step 4: Make Predictions
# ----------------------------
y_pred = model.predict(X_test)
# ----------------------------
# Step 5: Evaluate Model
# ----------------------------
rmse = np.sqrt(mean_squared_error(y_test, y_pred))
r2 = r2_score(y_test, y_pred)
print(f"Root Mean Squared Error (RMSE): {rmse:.2f}")
print(f"R² Score: {r2:.2f}")
# ----------------------------
# Step 6: Plot Results
# ----------------------------
plt.figure(figsize=(12,6))
plt.plot(data.index, y, label="Actual Prices", color="blue")
plt.plot(X_test.index, y_pred, label="Predicted Prices", color="red", linestyle="--")
plt.xlabel("Date")
plt.ylabel("Stock Price")
plt.title(f"{ticker} Stock Price Prediction (Linear Regression)")
plt.legend()
plt.show()