Forage 1
Forage 1
import numpy as np
import warnings
warnings.filterwarnings('ignore')
def load_data(filepath):
try:
df = pd.read_csv(filepath)
if len(df.columns) < 2:
print("Error: CSV file must have at least 2 columns (date and price)")
return None
df['Date'] = pd.to_datetime(df['Date'])
# Sort by date
df = df.sort_index()
return df
except Exception as e:
return None
# Visualization function
def visualize_data(df):
axes[0].set_ylabel('Price')
axes[0].grid(True)
if len(df) >= 12: # Need at least 12 data points for seasonal decomposition
seasonal = decomposition.seasonal
axes[1].legend()
axes[1].grid(True)
plt.tight_layout()
plt.show()
monthly_avg = df.groupby(df.index.month)['Price'].mean()
plt.figure(figsize=(10, 6))
plt.xlabel('Month')
plt.ylabel('Average Price')
plt.xticks(range(1, 13), ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
'Oct', 'Nov', 'Dec'])
plt.show()
def build_arima_model(df):
# Split data into training and testing sets (last 6 months for testing)
train_size = len(df) - 6
best_aic = float('inf')
best_params = None
try:
model_fit = model.fit()
best_aic = model_fit.aic
best_params = (p, d, q)
except:
continue
final_model_fit = final_model.fit()
if len(test) > 0:
predictions = final_model_fit.forecast(steps=len(test))
plt.figure(figsize=(12, 6))
plt.legend()
plt.grid(True)
plt.show()
return final_model_fit
date = pd.to_datetime(date)
if date in df.index:
if months_ahead == 0:
months_ahead = 1
forecast = model.forecast(steps=months_ahead)
price = forecast.iloc[-1]
return price
last_date = df.index.max()
# Forecast prices
forecast = model.forecast(steps=12)
forecast_df = forecast_df.set_index('Date')
combined = pd.DataFrame(index=pd.date_range(start=df.index.min(),
end=forecast_df.index.max(), freq='M'))
combined['Historical'] = df['Price']
combined['Forecasted'] = forecast_df['Forecasted_Price']
plt.figure(figsize=(12, 6))
std_dev = df['Price'].std()
mask = ~pd.isna(combined['Forecasted'])
plt.fill_between(combined.index[mask], lower_bound[mask],
upper_bound[mask], color='red', alpha=0.2)
plt.xlabel('Date')
plt.ylabel('Price')
plt.grid(True)
plt.legend()
plt.tight_layout()
plt.show()
return forecast_df
# Main function
def main():
# Get file path from user
file_path = input("Enter the path to the natural gas price CSV file: ")
# Load data
df = load_data(file_path)
if df is None:
return
print("\nBasic Statistics:")
print(df['Price'].describe())
visualize_data(df)
model = build_arima_model(df)
print(forecast)
while True:
if date_input.lower() == 'q':
break
try:
except Exception as e:
print(f"Error: {e}")
if __name__ == "__main__":
main()