Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
b770250
core(notebooks): Added executed notebooks on Google Colab
shortthirdman Sep 27, 2025
72f7337
core(notebook): Added executed notebook on Optimal Credit Spreads Str…
shortthirdman Sep 27, 2025
39c4e7f
core(notebooks): Added notebook for exploring the ML library TabFN
shortthirdman Sep 28, 2025
c51d5da
docs: Updated README with documentation
shortthirdman Sep 28, 2025
e7555bf
core(notebook): Anchored VWAP for Trading
shortthirdman Oct 2, 2025
166a67d
core(notebook): Simulating Stock Prices
shortthirdman Oct 2, 2025
c9f9c09
core(notebook): Measuring Volatility Mean-Reversion
shortthirdman Oct 2, 2025
7569304
core(notebooks): Time Series Analysis of Netflix (NFLX)
shortthirdman Oct 6, 2025
ab66f4d
core(notebooks): Portfolio Diversification Using PCA
shortthirdman Oct 6, 2025
1ba0431
core(notebooks): Time Series Analysis using XGBoost
shortthirdman Oct 6, 2025
28ca796
core(notebooks): Inflation Hedge Strategy Implementation
shortthirdman Oct 6, 2025
9af1a91
core(notebooks): Implemented pipeline SCADA forecasting
shortthirdman Nov 5, 2025
cac61b8
core(notebooks): Added implementation for quant finance portfolio man…
shortthirdman Nov 5, 2025
2ce5904
core(notebooks): Added implementation for Solar Irradiance forecasting
shortthirdman Nov 5, 2025
3ecf377
core(notebooks): Added implemented notebook for Options Pricing
shortthirdman Nov 12, 2025
d0d9c09
core(notebooks): Linear Regression using PyTorch
shortthirdman Nov 12, 2025
4255192
core(notebooks): Trading Market Regimes using GMM
shortthirdman Nov 12, 2025
e7b5df8
devops: Added GHA workflow to convert notebooks to HTML and publish t…
shortthirdman Nov 12, 2025
8ae2a75
devops: Removed unexpected value 'persist-credentials'
shortthirdman Nov 12, 2025
fa93dde
core(notebooks): Updated with reference for Options Pricing
shortthirdman Nov 12, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 57 additions & 0 deletions .github/workflows/convert-notebooks.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
name: Convert Notebooks to HTML

on:
workflow_dispatch: # Manual trigger only

permissions:
contents: write # Required to commit and push changes
actions: read # Default safe read access
pages: write
id-token: write

jobs:
convert:
runs-on: ubuntu-latest

steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
persist-credentials: true # Needed for pushing commits

- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: '3.x'

- name: Install Jupyter
run: |
python -m pip install --upgrade pip
pip install jupyter

- name: Convert large notebooks to HTML
run: |
mkdir -p docs
# Find notebooks larger than 20KB (20 * 1024 bytes)
find notebooks -type f -name "*.ipynb" -size +20k | while read nb; do
echo "Converting $nb ..."
jupyter nbconvert "$nb" --to html --output-dir docs
done

- name: List generated files
run: ls -lh docs

- name: Commit and push changes
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
git config user.name "github-actions[bot]"
git config user.email "github-actions[bot]@users.noreply.github.com"
# Add and commit only if there are changes
git add docs/
if git diff --cached --quiet; then
echo "No changes to commit."
else
git commit -m "Automated: Convert Jupyter notebooks to HTML"
git push origin HEAD:${{ github.ref }}
fi
50 changes: 48 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,48 @@
# Google-Colab-Notebooks
Collection of Jupyter Notebooks from Google Colab
<h1 align="center">Welcome to Google-Colab-Notebooks πŸ‘‹</h1>
<p>
<img alt="Version" src="https://img.shields.io/badge/version-1.0.0-blue.svg?cacheSeconds=2592000" />
<a href="https://github.com/shortthirdman-org/Google-Colab-Notebooks" target="_blank">
<img alt="Documentation" src="https://img.shields.io/badge/documentation-yes-brightgreen.svg" />
</a>
<a href="LICENSE" target="_blank">
<img alt="License: MIT" src="https://img.shields.io/badge/License-MIT-yellow.svg" />
</a>
<a href="https://twitter.com/ShortThirdMan93" target="_blank">
<img alt="Twitter: ShortThirdMan93" src="https://img.shields.io/twitter/follow/ShortThirdMan93.svg?style=social" />
</a>
</p>

> Collection of Jupyter Notebooks from Google Colab

### 🏠 [Homepage](https://github.com/shortthirdman-org/Google-Colab-Notebooks)

### ✨ [Demo](https://github.com/shortthirdman-org/Google-Colab-Notebooks)

## Author

πŸ‘€ **Swetank Mohanty**

* Website: https://shortthirdman.medium.com/
* Twitter: [@ShortThirdMan93](https://twitter.com/ShortThirdMan93)
* Github: [@shortthirdman](https://github.com/shortthirdman)
* LinkedIn: [@shortthirdman](https://linkedin.com/in/shortthirdman)

## 🀝 Contributing

Contributions, issues and feature requests are welcome!<br />Feel free to check [issues page](https://github.com/shortthirdman-org/Google-Colab-Notebooks/issues).

## Show your support

Give a ⭐️ if this project helped you!

<a href="https://www.patreon.com/shortthirdman">
<img src="https://c5.patreon.com/external/logo/become_a_patron_button@2x.png" width="160">
</a>

## πŸ“ License

Copyright Β© 2025 [Swetank Mohanty](https://github.com/shortthirdman).<br />
This project is [MIT](LICENSE) licensed.

***
_This README was generated with ❀️ by [readme-md-generator](https://github.com/kefranabg/readme-md-generator)_
280 changes: 280 additions & 0 deletions notebooks/Anchoring_VWAP.ipynb

Large diffs are not rendered by default.

75 changes: 75 additions & 0 deletions notebooks/Bayesian_Opt_Trading_Strategy.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
{
"metadata": {
"kernelspec": {
"name": "python",
"display_name": "Python (Pyodide)",
"language": "python"
},
"language_info": {
"codemirror_mode": {
"name": "python",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8"
}
},
"nbformat_minor": 4,
"nbformat": 4,
"cells": [
{
"cell_type": "markdown",
"source": "### [Bayesian Optimization to Optimize a Trading Strategy on the Top 10 Most Active Stocks](https://wire.insiderfinance.io/i-used-bayesian-optimization-to-optimize-a-trading-strategy-on-the-top-10-most-active-stocks-97345ff731ed)",
"metadata": {}
},
{
"cell_type": "code",
"source": "import yfinance as yf\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom bayes_opt import BayesianOptimization\nimport time\nimport numpy as np\nimport calendar\n\nplt.style.use(\"dark_background\")\n\ntickers = [\"LCID\", \"NVDA\", \"INTC\", \"F\", \"TSLA\", \"HOOD\", \"WULF\", \"CIFR\", \"SOFI\", \"IREN\"]\nstart_date = \"2020-01-01\"\nend_date = \"2025-06-30\"\ntrain_cutoff_date = \"2023-12-31\"\ninitial_capital = 10\n\nresults = []",
"metadata": {
"trusted": true
},
"outputs": [],
"execution_count": null
},
{
"cell_type": "code",
"source": "def backtest_strategy_double_ma(data, short_window, long_window, initial_capital):\n df = data.copy()\n df['SMA_Short'] = df['Close'].rolling(window=short_window).mean()\n df['SMA_Long'] = df['Close'].rolling(window=long_window).mean()\n df['Signal'] = 0\n df.loc[df['SMA_Short'] > df['SMA_Long'], 'Signal'] = 1\n df['Position'] = df['Signal'].shift(1)\n df['Return'] = df['Close'].pct_change()\n df['Strategy_Return'] = df['Position'] * df['Return']\n df['Equity_Curve'] = (1 + df['Strategy_Return']).cumprod() * initial_capital\n final_value = df['Equity_Curve'].iloc[-1]\n num_trades = df['Position'].diff().abs().sum()\n return final_value, num_trades, df",
"metadata": {
"trusted": true
},
"outputs": [],
"execution_count": null
},
{
"cell_type": "code",
"source": "for symbol in tickers:\n print(f\"Running for {symbol}...\")\n df = yf.download(symbol, start=start_date, end=end_date)[['Close']]\n\n df_train = df.loc[start_date:train_cutoff_date].copy()\n df_test = df.loc[train_cutoff_date:end_date].copy()\n\n def backtest_bo(short_window, long_window):\n short_window = int(round(short_window))\n long_window = int(round(long_window))\n if short_window >= long_window:\n return -1e10\n final_value, _, _ = backtest_strategy_double_ma(df_train, short_window, long_window, initial_capital)\n return final_value\n\n pbounds = {'short_window': (5, 50), 'long_window': (55, 200)}\n optimizer = BayesianOptimization(f=backtest_bo, pbounds=pbounds, random_state=42, verbose=0)\n optimizer.maximize(init_points=5, n_iter=45)\n\n best_params = optimizer.max['params']\n best_short_window = int(round(best_params['short_window']))\n best_long_window = int(round(best_params['long_window']))\n\n _, _, df_test_result = backtest_strategy_double_ma(df_test, best_short_window, best_long_window, initial_capital)\n df_test_result['Buy & Hold'] = (1 + df_test_result['Return']).cumprod() * initial_capital\n\n final_strategy_value = df_test_result['Equity Curve'].iloc[-1]\n final_bh_value = df_test_result['Buy & Hold'].iloc[-1]\n strategy_return_pct = ((final_strategy_value / initial_capital) - 1) * 100\n bh_return_pct = ((final_bh_value / initial_capital) - 1) * 100\n num_trades = df_test_result['Position'].diff().abs().sum()\n\n results.append({\n \"Symbol\": symbol,\n \"Short Window\": best_short_window,\n \"Long Window\": best_long_window,\n \"Strategy Final Value\": final_strategy_value,\n \"Buy & Hold Final Value\": final_bh_value,\n \"Strategy Return (%)\": strategy_return_pct,\n \"Buy & Hold Return (%)\": bh_return_pct,\n \"Trades\": int(num_trades)\n })\n \n # Print the results for the current symbol\n print(f\"{symbol} - Best Short Window: {best_short_window}, Best Long Window: {best_long_window}\")\n print(f\"{symbol} - Strategy Final Value: ${final_strategy_value:.2f}, Buy & Hold Final Value: ${final_bh_value:.2f}\")\n print(f\"{symbol} - Strategy Return: {strategy_return_pct:.2f}%, Buy & Hold Return: {bh_return_pct:.2f}%\")\n print(f\"{symbol} - Number of Trades: {int(num_trades)}\\n\")\n\n # Plot equity curve comparison\n plt.figure(figsize=(12, 6))\n plt.plot(df_test_result['Equity Curve'], label='Strategy', color='green')\n plt.plot(df_test_result['Buy & Hold'], label='Buy & Hold', linestyle='--', color='orange')\n plt.title(f\"{symbol} - Out-of-Sample Equity Curve\")\n plt.xlabel(\"Date\")\n plt.ylabel(\"Portfolio Value (USD)\")\n plt.legend()\n plt.grid(True, color='gray', linestyle='--', linewidth=0.5)\n plt.tight_layout()\n plt.savefig(f\"{symbol}_equity_curve.png\", dpi=300)\n plt.show()",
"metadata": {
"trusted": true
},
"outputs": [],
"execution_count": null
},
{
"cell_type": "code",
"source": "results_df = pd.DataFrame(results)\nresults_df = results_df.set_index(\"Symbol\")\nresults_df = results_df.sort_values(\"Strategy Return (%)\", ascending=False)\nresults_df.to_csv(\"multi_ticker_strategy_comparison.csv\")\nresults_df",
"metadata": {
"trusted": true
},
"outputs": [],
"execution_count": null
},
{
"cell_type": "code",
"source": "plt.figure(figsize=(12, 6))\nx = np.arange(len(results_df))\nwidth = 0.35\n\nbars1 = plt.bar(x - width/2, results_df[\"Strategy Return (%)\"], width, label=\"Strategy\", color='red')\nbars2 = plt.bar(x + width/2, results_df[\"Buy & Hold Return (%)\"], width, label=\"Buy & Hold\", color='green')\n\nfor bars in [bars1, bars2]:\n for bar in bars:\n height = bar.get_height()\n plt.text(bar.get_x() + bar.get_width()/2, height + np.sign(height)*2, f\"{height:.1f}%\", \n ha='center', va='bottom' if height >= 0 else 'top', fontsize=12)\n\nplt.xticks(x, results_df.index, rotation=45)\nplt.ylabel(\"Return (%)\")\nplt.title(\"Strategy vs Buy & Hold Performance (Test Set)\")\nplt.legend()\nplt.grid(True, linestyle='--', alpha=0.5)\nplt.tight_layout()\nplt.savefig(\"comparison_bar_chart.png\", dpi=300)\nplt.show()",
"metadata": {
"trusted": true
},
"outputs": [],
"execution_count": null
}
]
}
Loading