{"id":25155460,"url":"https://github.com/ddayto21/stock-forecasting","last_synced_at":"2025-04-30T08:44:56.010Z","repository":{"id":46491974,"uuid":"515297615","full_name":"ddayto21/Stock-Forecasting","owner":"ddayto21","description":"Python repository that uses time-series data from the S\u0026P 500 to train a RandomForestClassifier to predict the probability of a stock price increasing or decreasing. This script is meant for educational purposes only - this is not financial advice. Consult with your financial adviser before making  any investments.","archived":false,"fork":false,"pushed_at":"2025-01-21T03:42:37.000Z","size":285,"stargazers_count":12,"open_issues_count":0,"forks_count":5,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-01-21T04:25:14.758Z","etag":null,"topics":["machine-learning","predictions","python","random-forest","stock-data","stock-market","time-series-forecasting","yahoo-finance"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ddayto21.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2022-07-18T18:27:15.000Z","updated_at":"2025-01-21T03:42:41.000Z","dependencies_parsed_at":"2022-09-01T16:22:45.908Z","dependency_job_id":null,"html_url":"https://github.com/ddayto21/Stock-Forecasting","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ddayto21%2FStock-Forecasting","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ddayto21%2FStock-Forecasting/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ddayto21%2FStock-Forecasting/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ddayto21%2FStock-Forecasting/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ddayto21","download_url":"https://codeload.github.com/ddayto21/Stock-Forecasting/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":237890767,"owners_count":19382564,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["machine-learning","predictions","python","random-forest","stock-data","stock-market","time-series-forecasting","yahoo-finance"],"created_at":"2025-02-09T00:51:53.115Z","updated_at":"2025-02-09T00:51:53.670Z","avatar_url":"https://github.com/ddayto21.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Repository Overview\n\nThis repository demonstrates the application of machine learning techniques to predict the likelihood of stock price movements in the S\u0026P 500 index using historical time-series data. By leveraging the Yahoo Finance API, we acquire and preprocess financial data to train a RandomForestClassifier. This classifier models patterns in stock price behavior, providing insights into market trends and potential price movements.\n\nThe Yahoo Finance API is an exceptional tool for accessing a wide range of market data, including stocks, bonds, currencies, and cryptocurrencies. It also provides global news reports, offering comprehensive insights into various financial markets.\n\n![S\u0026P-500](images/s\u0026p-logo.jpg)\n\n## Installation and Setup\n\n### Install Yahoo Finance API\n\nThe Yahoo Finance API is required to fetch historical data for the S\u0026P 500 index (^GSPC). Install the library using the following command:\n\n```bash\npip install yfinance\n```\n\n### Install Matplotlib\n\nFor data visualization, we use Matplotlib to plot trends and patterns in the S\u0026P 500 data:\n\n```python\npip install matplotlib\n```\n\n### Install Scikit-learn\n\nFor machine learning modeling, we leverage Scikit-learn, a versatile library for predictive analytics:\n\n```bash\npip install scikit-learn\n```\n\n## Data Collection and Preprocessing\n\n### Load S\u0026P 500 Data\n\nUsing the Yahoo Finance API, we retrieve the complete historical price data for the S\u0026P 500 index:\n\n```python\nimport yfinance as yf\n\n# Fetch historical data\nsp500 = yf.Ticker(\"^GSPC\")\nsp500 = sp500.history(period=\"max\")\n```\n\n### Visualize the S\u0026P 500 Index\n\nVisualize the historical closing prices of the S\u0026P 500 index to observe long-term trends:\n\n```python\nimport matplotlib.pyplot as plt\n\n# Plot S\u0026P 500 Closing Prices\nplt.plot(sp500.index, sp500[\"Close\"], label=\"S\u0026P 500 Closing Prices\")\nplt.xlabel(\"Date\")\nplt.ylabel(\"Closing Price\")\nplt.title(\"Historical Trends in S\u0026P 500 Index\")\nplt.legend()\nplt.show()\n```\n\n### Set Up Target Variables\n\nTo predict whether the stock price will increase or decrease, we engineer target variables:\n\n- Tomorrow: Represents the closing price for the following day.\n- Target: A binary variable indicating whether the price increased (1) or decreased (0).\n\n```python\n# Create target variables\nsp500[\"Tomorrow\"] = sp500[\"Close\"].shift(-1)\nsp500[\"Target\"] = (sp500[\"Tomorrow\"] \u003e sp500[\"Close\"]).astype(int)\n\n# Restrict data to post-1990 for a more modern analysis\nsp500 = sp500.loc[\"1990-01-01\":].copy()\n```\n\n## Train a Machine Learning Model\n\n## Random Forest Classifier\n\nThe `RandomForestClassifier` is a robust ensemble learning algorithm that combines decision trees to enhance predictive accuracy and reduce overfitting. We’ll train this model using historical S\u0026P 500 data.\n\n```python\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.metrics import precision_score\n\n\nmodel = RandomForestClassifier(\n    n_estimators=200,  # Number of decision trees\n    min_samples_split=50,  # Minimum samples required to split an internal node\n    random_state=1  # Ensure reproducibility\n)\n```\n\n## Prepare Features and Train the Model\n\nWe use historical prices as features to train the model. The features are lagged values of stock prices, allowing the model to learn patterns over time.\n\n```python\n# Define feature columns\npredictors = [\"Close\", \"Volume\", \"Open\", \"High\", \"Low\"]\n\n# Split the data into training and testing sets\ntrain = sp500.iloc[:-100]\ntest = sp500.iloc[-100:]\n\n# Train the model\nmodel.fit(train[predictors], train[\"Target\"])\n```\n\n## Evaluate the Model\n\nEvaluate the model’s predictive performance on unseen data using metrics such as precision:\n\n```python\n# Make predictions\npredictions = model.predict(test[predictors])\n\n# Evaluate precision\nprecision = precision_score(test[\"Target\"], predictions)\nprint(f\"Precision: {precision:.2%}\")\n```\n\n## Key Takeaways\n\nThis project showcases the integration of data engineering and machine learning for financial market predictions. By employing the RandomForestClassifier with historical stock data, the model demonstrates the potential to uncover patterns in market movements, aiding in decision-making processes.\n\n### Future Enhancements\n\n1. Feature Expansion: Incorporate technical indicators (e.g., moving averages, RSI) to improve prediction accuracy.\n2. Hyperparameter Tuning: Use tools like GridSearchCV or Optuna for optimizing model performance.\n3. Model Variants: Experiment with Gradient Boosting algorithms such as XGBoost or LightGBM for comparison.\n4. Real-Time Predictions: Extend the solution to provide real-time market predictions using live data feeds.\n\n### Suggestions for Contributions\n\n- Add new features such as technical indicators (e.g., moving averages, RSI).\n- Optimize hyperparameters using tools like GridSearchCV or Optuna.\n- Extend the project to predict other indices or stocks.\n- Enhance visualization capabilities with advanced charting libraries.\n\n## License\n\nThis project is licensed under the MIT License. See the LICENSE file for details.\n\n## Acknowledgments\n\n- Data sourced from Yahoo Finance.\n- Inspired by the intersection of financial markets and data-driven decision-making.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fddayto21%2Fstock-forecasting","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fddayto21%2Fstock-forecasting","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fddayto21%2Fstock-forecasting/lists"}