Untitled

 avatar
unknown
plain_text
2 months ago
1.8 kB
2
Indexable
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures

# Load the dataset
file_path = "/mnt/data/Nat_Gas.csv"
df = pd.read_csv(file_path)

# Convert Dates column to datetime format
df["Dates"] = pd.to_datetime(df["Dates"], format="%m/%d/%y")

# Convert dates to ordinal format (numerical representation for modeling)
df["Date_Ordinal"] = df["Dates"].map(lambda x: x.toordinal())

# Prepare training data
X = df["Date_Ordinal"].values.reshape(-1, 1)
y = df["Prices"].values

# Fit a polynomial regression model (degree 3 for trend capturing)
poly = PolynomialFeatures(degree=3)
X_poly = poly.fit_transform(X)
model = LinearRegression()
model.fit(X_poly, y)

# Function to predict price for a given date
def predict_price(input_date):
    date_ordinal = pd.to_datetime(input_date).toordinal()
    price_pred = model.predict(poly.transform([[date_ordinal]]))
    return round(price_pred[0], 2)

# Generate future predictions for 12 months (1-year extrapolation)
future_dates = pd.date_range(df["Dates"].max(), periods=13, freq='M')[1:]
future_ordinals = future_dates.map(lambda x: x.toordinal()).values.reshape(-1, 1)
future_prices = model.predict(poly.transform(future_ordinals))

# Plot past data with future predictions
plt.figure(figsize=(12, 6))
plt.plot(df["Dates"], df["Prices"], marker='o', linestyle='-', label="Actual Prices")
plt.plot(future_dates, future_prices, marker='o', linestyle='--', color='red', label="Forecasted Prices")
plt.xlabel("Date")
plt.ylabel("Price ($)")
plt.title("Natural Gas Price Forecast")
plt.legend()
plt.grid(True)
plt.show()

# Display predicted prices for the next year
future_df = pd.DataFrame({"Date": future_dates, "Predicted Price": np.round(future_prices, 2)})
print(future_df)
Editor is loading...
Leave a Comment