-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstock.py
More file actions
114 lines (78 loc) · 2.02 KB
/
Copy pathstock.py
File metadata and controls
114 lines (78 loc) · 2.02 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import yfinance as yf
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error, r2_score
from xgboost import XGBRegressor
import streamlit as st
from testapidata import df
print(df)
print(df.isnull())
# Create previous 30 month features
for i in range(1, 31):
df[f'prev_{i}'] = df['value'].shift(i)
# Features
X = df[[f'prev_{i}' for i in range(1, 31)]]
X = X.astype(float)
df['value'] = pd.to_numeric(df['value'], errors='coerce')
# Target
y = df['value']
# Train Test Split
X_train, X_test, y_train, y_test = train_test_split(
X,
y,
test_size=0.2,
shuffle=False
)
# XGBoost Model
model = XGBRegressor(
n_estimators=300,
learning_rate=0.05,
max_depth=5,
subsample=0.8,
colsample_bytree=0.8,
random_state=42
)
# Train Model
model.fit(X_train, y_train)
# Predictions
predictions = model.predict(X_test)
# Metrics
mse = mean_squared_error(y_test, predictions)
r2 = r2_score(y_test, predictions)
print("Mean Squared Error:", mse)
print("R2 Score:", r2)
# Show predictions
results = pd.DataFrame({
'Actual': y_test.values,
'Predicted': predictions
})
print(results)
# Function for future prediction
def predict_future():
latest_values = df['value'].tail(30).values
# Reverse values
latest_values = latest_values[::-1]
# Create input dataframe
future_input = pd.DataFrame(
[latest_values],
columns=[f'prev_{i}' for i in range(1, 31)]
)
# Predict
prediction = model.predict(future_input)
return prediction[0]
# Plot graph
plt.figure(figsize=(12,6))
plt.plot(y_test.values, label='Actual')
plt.plot(predictions, label='Predicted')
plt.title('Actual vs Predicted Stock Values')
plt.xlabel('Time')
plt.ylabel('Stock Value')
plt.legend()
plt.grid(True)
plt.savefig("data.png")
# Predict next value
latest_data = X.tail(1)
next_prediction = model.predict(latest_data)
print("Next Predicted Value:", next_prediction[0])