Update app.py
Browse files278 unmodified lines27928028128228328428528628728828929025 unmodified lines31631731831932032132221 unmodified lines3443453463473483493504 unmodified lines3553563573583593603613623633643653661 unmodified line368369370371372373374278 unmodified linesst.error(f"Error fetching news: {str(e)}")return []def get_table_download_link(df):csv = df.to_csv(index=False)b64 = base64.b64encode(csv.encode()).decode()href = f'<a href="data:file/csv;base64,{b64}" download="stock_data.csv">Download CSV File</a>'return hrefdef main():st.set_page_config(page_title="Stock Price Predictor", layout="wide")st.title("Advanced Stock Price Predictor using Prophet")25 unmodified linesst.subheader("Stock Data Information")st.write(data.info())st.write(data.describe())st.dataframe(data.head())split_index = int(len(data) * (1 - test_split))train_data = data.iloc[:split_index]21 unmodified lines# Cross-validation resultsst.subheader("Cross-Validation Results")cv_results = predictor.cross_validate_model()st.dataframe(cv_results)# Calculate and display average metricsavg_mse = cv_results['mse'].mean()4 unmodified linesst.write(f"Average RMSE: {avg_rmse:.4f}")st.write(f"Average MAPE: {avg_mape:.4f}")# Feature importancest.subheader("Feature Importance")feature_importance = pd.DataFrame(predictor.model.params['regressor_coefficients'].items(), columns=['Feature', 'Importance'])feature_importance = feature_importance.sort_values('Importance', ascending=False)fig = px.bar(feature_importance, x='Feature', y='Importance', title='Feature Importance')st.plotly_chart(fig, use_container_width=True)else:st.error("Failed to evaluate the model. The evaluation metrics are None.")else:1 unmodified lineelse:st.error("Failed to train the Prophet model. Please try a different dataset.")else:st.error("Failed to fetch stock data. Please try again.")def predict_stock_prices():st.header("Predict Stock Prices with Enhanced Model")278 unmodified lines27928028128228328428528628728828929029129225 unmodified lines31831932032132232332432532632732832933021 unmodified lines3523533543553563573583593603613623634 unmodified lines3683693703713723733743753763773783793803813823833843853861 unmodified line388389390391392393394278 unmodified linesst.error(f"Error fetching news: {str(e)}")return []def get_table_download_link(df, filename, text):"""Generates a link to download the given dataframe as a CSV file."""csv = df.to_csv(index=False)b64 = base64.b64encode(csv.encode()).decode()href = f'<a href="data:file/csv;base64,{b64}" download="{filename}">{text}</a>'return hrefdef main():st.set_page_config(page_title="Stock Price Predictor", layout="wide")st.title("Advanced Stock Price Predictor using Prophet")25 unmodified linesst.subheader("Stock Data Information")st.write(data.info())st.write(data.describe())# Display interactive dataframest.subheader("Stock Data Preview")st.dataframe(data.head(100), use_container_width=True)# Provide download link for full datasetst.markdown(get_table_download_link(data, f"{ticker}_stock_data.csv", "Download full stock data CSV"), unsafe_allow_html=True)split_index = int(len(data) * (1 - test_split))train_data = data.iloc[:split_index]21 unmodified lines# Cross-validation resultsst.subheader("Cross-Validation Results")cv_results = predictor.cross_validate_model()# Display interactive dataframest.dataframe(cv_results, use_container_width=True)# Provide download link for cross-validation resultsst.markdown(get_table_download_link(cv_results, f"{ticker}_cv_results.csv", "Download cross-validation results CSV"), unsafe_allow_html=True)# Calculate and display average metricsavg_mse = cv_results['mse'].mean()4 unmodified linesst.write(f"Average RMSE: {avg_rmse:.4f}")st.write(f"Average MAPE: {avg_mape:.4f}")# Display predictionsst.subheader("Predictions")predictions_df = pd.DataFrame({'Date': test_pred['ds'],'Predicted': test_pred['yhat'],'Lower Bound': test_pred['yhat_lower'],'Upper Bound': test_pred['yhat_upper']})st.dataframe(predictions_df, use_container_width=True)# Provide download link for predictionsst.markdown(get_table_download_link(predictions_df, f"{ticker}_predictions.csv", "Download predictions CSV"), unsafe_allow_html=True)else:st.error("Failed to evaluate the model. The evaluation metrics are None.")else:1 unmodified lineelse:st.error("Failed to train the Prophet model. Please try a different dataset.")else:st.error("Failed to fetch stock data. Please try again."def predict_stock_prices():st.header("Predict Stock Prices with Enhanced Model")
app.py+31-11