Stock/Crypto Trading System

This repository contains Python scripts I've built for stock and cryptocurrency trading analysis. Each script serves a unique purpose, ranging from data analysis to trade execution, helping to automate and optimize the trading process.

Additionally, a number of dashboards are included to visualize the data and insights generated by the scripts. These dashboards provide a user-friendly interface for monitoring market trends, analyzing technical indicators, and making informed trading decisions.

[Python] Trading Scripts

Features

  • Backtesting and analysis tools to measure the effectiveness of trading strategies and optimize performance.
  • Real-time trading scripts using Alpaca and Coinbase API integrations for automated stock and cryptocurrency trading.
  • Options pricing using the Black-Scholes model for advanced financial modeling and option valuation.
  • Analysis of the best trading hours for specific markets and assets, providing insights for optimal buy/sell times.
  • Buy and sell signal generators to automate decision-making processes with backtesting functionality for strategy validation.
  • Volatility and risk assessment models like GARCH, MCMC, and Jump Diffusion for enhanced risk management in dynamic markets.
  • Technical analysis tools with indicators like moving averages, RSI, MACD, and Fourier transforms for more informed trading.
  • Portfolio optimization techniques to balance risk and return for maximizing profits in stock and cryptocurrency portfolios.

Scripts Overview

Script Name Description
alpaca-bot.py Integrates with Alpaca API to execute trades automatically. Monitors markets and places buy/sell orders.
analyze.py Analyzes trading data including profit trends and generates visualizations of trading performance.
best-trading-hours-month.py Identifies the best trading hours for a given asset on a weekly basis for each month using historical data.
best-trading-hours.py Analyzes the best trading hours for each day of the week, providing detailed analysis of buy/sell patterns.
black-scholes.py Implements the Black-Scholes model to calculate option prices based on market volatility.
buy-and-sell.py Generates buy/sell signals using technical indicators and provides backtesting for signal optimization.
coinbase_bot.py Automates cryptocurrency trading using the Coinbase Pro API with predefined strategies.
correlation.py Calculates the dynamic correlation between cryptocurrencies over time for diversification insights.
daily.py Automates daily cryptocurrency data updates, ensuring datasets stay current.
fb-prophet.py Utilizes fbprophet to forecast cryptocurrency prices based on historical data with trend predictions.
fetch-coin-data.py Fetches cryptocurrency data from public APIs and stores it for further analysis.
fourier-transforms.py Applies Fourier Transforms to analyze price trends and identify cyclical patterns in market data.
garch.py Uses GARCH models to forecast price volatility and assist with risk management.
hourly.py Collects and processes hourly cryptocurrency data for short-term trading strategies.
jump-diffusion.py Models asset prices using the Jump Diffusion process to account for large, sudden price changes.
kelly-criterion.py Implements the Kelly Criterion to calculate the optimal bet size for maximizing long-term wealth growth.
mcmc.py Uses Monte Carlo Markov Chain (MCMC) simulation to model price probability distributions.
polygon-fetch.py Fetches stock and crypto data from the Polygon API for real-time analysis.
polygon-trades.py Executes trades using real-time data from the Polygon API for stocks and cryptocurrencies.
portfolio-optimizer.py Uses optimization techniques to balance risk and return for building an optimal portfolio.
price-swings-15min.py Analyzes 15-minute price swings for high-frequency trading strategies.
price-swings-daily.py Detects significant daily price swings and provides insights into asset volatility.
price-swings-hourly.py Identifies hourly price swings for high-frequency traders needing granular market insights.
price-vol.py Analyzes historical price volatility to identify periods of high/low price fluctuations.
rate-of-return-hourly.py Calculates hourly rate of return for various assets to inform short-term market performance.
rf.py Implements a Random Forest model to predict future price movements using historical data.
steady-state-distro.py Performs steady-state distribution analysis to model long-term price behavior.
stl-prophet.py Combines STL decomposition with Prophet forecasting for trend and seasonal time-series predictions.
ta.py Implements technical analysis indicators like moving averages, RSI, and MACD for trading decisions.
volatility.py Models price volatility using various mathematical approaches for risk management and strategy adjustment.
wavelet-transform.py Applies wavelet transforms to decompose price data for multi-scale analysis and anomaly detection.

[UI] Whale Watcher Dashboard

A responsive frontend dashboard providing visualizations for cryptocurrency holdings, price movements, volatility, and correlations. Built with HTML, JavaScript, Highcharts, and Bootstrap, it offers an interactive experience for tracking crypto market dynamics.

Feature Script Description
Data Processing & Aggregation data-processor.js, utils.js Handles real-time data fetching and aggregation across various timespans (15M, 1H, 1D) to ensure consistent datasets.
Line Graph Visualization line-graph-highchart.js Displays historical trends in holdings for the top 40 crypto addresses with time-filtered views and interactive controls.
Stream Graph Visualization stream-graph.js, percentage-graph.js Depicts wealth distribution among top holders over time with zoom/pan functionality and group toggling.
Volatility Analysis volatility.html Ranks cryptocurrencies by volatility, showing price swings and daily returns in both table and chart formats.
Correlation Analysis corrs.html Displays correlation coefficients between a base coin and others over time, helping with portfolio diversification.
Wavelet Transform & Entropy Heatmap moac-global.html Visualizes entropy across wavelet levels, measuring randomness and predictability of price data for multiple coins.
User Interface & Controls index.html, script.js A responsive interface using Bootstrap, allowing users to filter data, toggle views, and adjust timespans seamlessly.

[UI] Coin-Specific Dashboard

This dashboard provides detailed visualizations of a stock or cryptocurrency’s price, trends, volatility, and more. Built with JavaScript, Highcharts, and Bootstrap, it delivers interactive, real-time data for informed decision-making.

Feature Script Description
Combined Chart combined.js Visualizes price, volume, volatility, and correlations in one chart with zooming capabilities.
Monte Carlo Simulation monte-carlo.js Simulates future price paths based on historical data, highlighting scenarios for risk assessment.
Seasonal-Trend Decomposition stl.js Breaks down price data into trend, seasonal, and residual components for market cycle detection.
STL Prophet Forecast stl-prophet-forecast.js Combines STL and Prophet to generate multi-scenario forecasts with confidence intervals.
Fourier Transform fourier-transform.js Identifies dominant price cycles and recurring trends through Fourier analysis.
Price Swings & Heatmap price-swings.js, price-swings-heatmap.js Tracks price swings and visualizes the best days to buy/sell using a heatmap.
Wavelet Transform wavelet-transform.js Performs multi-resolution analysis of price data to detect patterns across different time scales.
Price & Market Cap Trends price-swings.js Tracks daily price and market cap with annotations for significant price movements.
Best Days to Buy Heatmap price-swings.js Highlights optimal buy/sell days based on historical returns for entry/exit timing.

Summary of Features:

  • Comprehensive analysis of a single asset’s price, volume, volatility, and correlations.
  • Interactive charts for exploring historical and simulated data.
  • STL & Prophet forecasting for future price predictions.
  • Fourier and wavelet transforms to uncover trends.
  • Heatmaps and price swings for identifying volatility and trading opportunities.

[UI] Technical Analysis & Trading Signals Dashboard

This dashboard provides visualizations for technical analysis (TA) indicators and trading signals for stocks or cryptocurrencies. Built with JavaScript, Highcharts, and Bootstrap, it offers real-time updates and an interactive interface.

Feature Description
Real-Time Data Updates Fetches data every 10 seconds from an external source, providing prices, buy/sell signals, and TA indicators like SMA, EMA, RSI.
Interactive Chart Displays asset prices along with multiple technical indicators. Users can toggle SMA, EMA, RSI, MACD, and more, with buy/sell signals annotated.
Technical Indicators Supports 20+ indicators that can be toggled on/off, with user preferences saved in localStorage for customization.
Buy/Sell Signals Highlights buy/sell signals with green and red triangles, updated in real-time to reflect market conditions.
Screen Alerts Visual alerts flash green for buy signals and red for sell signals, ensuring instant notification of new signals.
Indicators Panel A side panel lists all indicators with checkboxes for easy selection, allowing quick customization and saving settings.
Responsive Design Fully responsive layout using Bootstrap, optimized for both desktop and mobile, with auto-scaling chart elements.

Summary of Features:

  • Real-time data: Updates every 10 seconds with price, indicators, and signals.
  • Interactive chart: Toggle indicators and view buy/sell signals.
  • Multiple indicators: 20+ TA indicators like SMA, EMA, RSI, MACD.
  • Visual signals: Buy/sell signals marked on the chart with screen alerts.
  • Custom settings: Saves user preferences for future visits.
  • Responsive design: Works seamlessly across devices.

[PineScript] TradingView Scripts

These scripts are designed for TradingView, enabling custom indicators, strategies, and backtesting for technical analysis. They apply tools like MACD and MFI, tailored for specific stocks like $GME and $TSLA, or general market conditions.

Strategy Type Scripts Description
MACD & MFI Combination strat-gme-macd-mfi.ps, strat-mfi-buy-combined-sell.ps Combines MACD (trend momentum) with MFI (volume-weighted RSI) for buy/sell signals based on oversold/overbought conditions.
Pure MACD-Based strat-gme-macd.ps, strat-mother-macd.ps, strat-tsla-macd.ps Focuses on MACD crossovers to generate buy/sell signals, optimized for $GME, $TSLA, and general stock behavior.
MFI Buy/Sell Strategy strat-mfi-buy-mfi-sell.ps Uses MFI to trigger buy/sell signals based on overbought (above 80) or oversold (below 20) levels.
Keltner Channel Strategy strat-tsla-keltner.ps Uses Keltner Channels to identify volatility-based entry/exit points, ideal for $TSLA in volatile environments.

Practical Application:

  • Backtesting: These strategies can be backtested within TradingView to analyze historical performance.
  • Automated Trading: Use TradingView’s strategy tester to automate buy/sell decisions based on generated signals.
  • Customization: Input parameters like MACD or MFI periods can be adjusted for market conditions or specific assets.
  • Specific Asset Focus: Optimized for $GME and $TSLA, with stock-specific strategies leveraging their behavior.

How to Use

  1. Clone the repository.

  2. For Python scripts, run the desired script:

    python script.py
  3. For dashboards, start a local server:

    cd dashboard
    python -m http.server 8000
  4. Open the dashboard in your browser by navigating to:

    http://localhost:8000
    

Contributions

Feel free to contribute by submitting pull requests or opening issues.