{"id":46639307,"url":"https://github.com/spamsch/diabetes-recommendation-engine","last_synced_at":"2026-03-08T02:19:02.306Z","repository":{"id":311619264,"uuid":"1044300493","full_name":"spamsch/diabetes-recommendation-engine","owner":"spamsch","description":"A Python application for monitoring glucose levels from Dexcom sensors, providing intelligent analysis, predictions, and recommendations to help manage diabetes. ","archived":false,"fork":false,"pushed_at":"2025-08-25T15:52:27.000Z","size":114,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-08-25T16:07:21.606Z","etag":null,"topics":["dexcom","diabetes"],"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/spamsch.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,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2025-08-25T13:30:08.000Z","updated_at":"2025-08-25T15:52:31.000Z","dependencies_parsed_at":"2025-08-25T16:07:27.465Z","dependency_job_id":"214d4a3e-90c8-47b0-bb09-5bcade07b56d","html_url":"https://github.com/spamsch/diabetes-recommendation-engine","commit_stats":null,"previous_names":["spamsch/diabetes-recommendation-engine"],"tags_count":null,"template":false,"template_full_name":null,"purl":"pkg:github/spamsch/diabetes-recommendation-engine","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/spamsch%2Fdiabetes-recommendation-engine","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/spamsch%2Fdiabetes-recommendation-engine/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/spamsch%2Fdiabetes-recommendation-engine/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/spamsch%2Fdiabetes-recommendation-engine/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/spamsch","download_url":"https://codeload.github.com/spamsch/diabetes-recommendation-engine/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/spamsch%2Fdiabetes-recommendation-engine/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":30242406,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-03-08T00:58:18.660Z","status":"online","status_checked_at":"2026-03-08T02:00:06.215Z","response_time":56,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"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":["dexcom","diabetes"],"created_at":"2026-03-08T02:19:01.531Z","updated_at":"2026-03-08T02:19:02.274Z","avatar_url":"https://github.com/spamsch.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Diabetes Recommendation Engine\n\nA Python application for monitoring glucose levels from Dexcom sensors,\nproviding intelligent analysis, predictions, and recommendations to help manage\ndiabetes. This is a fully vibe coded app (4 hours total using Claude Code and\nGPT-5 for initial and working implementation) and will contain a lot of emojis\nand other nonsensensical text. But it works for me and has been very helpful.\nThe recommendations have become pretty decent.\n\nMy use-case is to reduce mental load while handling the glucose levels for my\nchild. I love that a Telegram bot is helping me making decisions.  My goal is to\ntrust this software to alert me and give valid recommendations. I do not want to\nlook at the Omnipod active insulin and the current value of the Dexcom and think\nabout a solution.\n\nOne next step could be to integrate an LLM. But not sure of that really makes sense.\n\n## ⚠️ Important Medical Disclaimer\n\n**This application is for monitoring and educational purposes only. It is NOT a substitute for professional medical advice, diagnosis, or treatment. Always consult with qualified healthcare providers before making any medical decisions or changes to diabetes management.**\n\n- Never ignore symptoms even if readings appear normal\n- Always have emergency glucose supplies available\n- Seek immediate medical attention for severe symptoms\n- Follow your healthcare provider's diabetes management plan\n\n## Prerequisites\n\n**Dexcom Follow Required**: This application requires Dexcom Follow to be enabled and configured. It uses the [pydexcom](https://pypi.org/project/pydexcom/) library to connect to Dexcom Share API, which requires:\n- A Dexcom G6/G7 sensor system\n- Dexcom Follow feature enabled in the Dexcom app\n- Valid Dexcom Share credentials\n\n## Features\n\n### 🩸 Continuous Glucose Monitoring\n- Real-time data collection from Dexcom sensors every 5 minutes\n- Reliable data storage in SQLite database\n- Automatic reconnection handling\n\n### 📊 Intelligent Analysis\n- **Trend Analysis**: Detects glucose trends with configurable thresholds (down, fast_down, very_fast_down, up, fast_up, very_fast_up, stable)\n- **Pattern Recognition**: Identifies critical patterns and approaching thresholds\n- **Prediction Engine**: Forecasts glucose levels 15 minutes ahead using multiple algorithms\n- **IOB/COB Tracking**: Tracks Insulin on Board and Carbs on Board for accurate predictions\n\n### 💊 Smart Recommendations\n- **Insulin Recommendations**: Suggests insulin doses for high, stable glucose levels (considers IOB)\n- **Carbohydrate Recommendations**: Recommends fast-acting carbs for low glucose situations\n- **IOB Status Recommendations**: Suggests checking current active insulin for better prediction accuracy\n- **Monitoring Recommendations**: Advises on increased monitoring frequency\n- **Safety-First Approach**: Conservative recommendations with built-in safety checks\n\n### 📱 Telegram Integration\n- **Real-time Command Processing**: Full command support via Telegram bot\n- **IOB Shortcuts**: Send plain numbers (e.g., \"2.4\" or \"2,4\") to set IOB quickly\n- **Interactive Commands**: Log insulin, carbs, check status, get history\n- **Monitoring Sync**: Synchronize monitoring thread with Dexcom's actual update schedule\n- **Formatted Notifications**: Rich messages with priority levels and safety notes\n\n#### Available Telegram Commands\n- `/status` or `/s` - Current glucose status and IOB/COB\n- `/insulin \u003cunits\u003e [type] [notes]` or `/i` - Log insulin dose\n- `/carbs \u003cgrams\u003e [type] [notes]` or `/c` - Log carbohydrate intake\n- `/iob \u003cunits\u003e [source] [notes]` or `/setiob` - Set current IOB override\n- **Plain numbers** - Quick IOB entry (supports both dot and comma: `2.4` or `2,4`)\n- `/history [hours]` - Show glucose history\n- `/help` - Show available commands\n\n### 📈 Visualization\n- Real-time terminal display with trend arrows\n- Color-coded glucose values (green/yellow/red based on thresholds)\n- IOB/COB status display with impact calculations\n- Interactive terminal commands including monitoring sync\n\n### 🧪 Comprehensive Testing\n- Mock client for testing recommendations\n- Multiple realistic scenarios (approaching low values, post-meal spikes, exercise drops)\n- Safety validation for all recommendation algorithms\n\n## Installation\n\n1. **Clone the repository**\n```bash\ngit clone \u003crepository-url\u003e\ncd dexcom-analyze\n```\n\n2. **Install dependencies**\n```bash\npip install -r requirements.txt\n```\n\n3. **Configure the application**\n```bash\ncp .env.example .env\n# Edit .env with your Dexcom credentials and preferences\n```\n\n## Configuration\n\n### Required Settings\n\nEdit `.env` file with your information:\n\n```bash\n# Dexcom credentials (required)\nDEXCOM_USERNAME=your_dexcom_username\nDEXCOM_PASSWORD=your_dexcom_password\nDEXCOM_OUS=false  # Set to true for non-US accounts\n\n# Optional Telegram notifications\nTELEGRAM_BOT_URL=https://api.telegram.org/bot\u003cYOUR_BOT_TOKEN\u003e/sendMessage\nTELEGRAM_CHAT_ID=your_chat_id\n```\n\n### Configuration Settings\n\n| Setting | Description | Default | Notes |\n|---------|-------------|---------|-------|\n| **Core Settings** |\n| `DEXCOM_USERNAME` | Dexcom Share username | *required* | Must have Follow enabled |\n| `DEXCOM_PASSWORD` | Dexcom Share password | *required* | |\n| `DEXCOM_OUS` | Outside US account | `false` | Set true for non-US |\n| `POLL_INTERVAL_MINUTES` | How often to check for new readings | `5` | Dexcom updates every 5min |\n| `SENSOR_READING_INTERVAL_SECONDS` | Wait time after reading timestamp | `305` | 300s + 5s buffer |\n| `ANALYSIS_WINDOW_SIZE` | Number of readings to analyze | `15` | 10-20 recommended |\n| `PREDICTION_MINUTES_AHEAD` | Prediction timeframe | `15` | Minutes ahead to predict |\n| `TREND_CALCULATION_POINTS` | Readings used for trend analysis | `3` | Recent readings for trends |\n| **Glucose Thresholds (mg/dL)** |\n| `LOW_GLUCOSE_THRESHOLD` | Low glucose alert threshold | `70` | |\n| `HIGH_GLUCOSE_THRESHOLD` | High glucose alert threshold | `180` | |\n| `CRITICAL_LOW_THRESHOLD` | Critical low threshold | `55` | Emergency level |\n| `CRITICAL_HIGH_THRESHOLD` | Critical high threshold | `300` | Emergency level |\n| `TARGET_GLUCOSE` | Target glucose for calculations | `120` | Used in insulin recommendations |\n| **Trend Classification (mg/dL per minute)** |\n| `TREND_DOWN_THRESHOLD` | Minimum rate for \"down\" trend | `0.5` | Configurable sensitivity |\n| `TREND_FAST_DOWN_THRESHOLD` | Rate for \"fast_down\" trend | `2.0` | |\n| `TREND_VERY_FAST_DOWN_THRESHOLD` | Rate for \"very_fast_down\" trend | `4.0` | |\n| `TREND_UP_THRESHOLD` | Minimum rate for \"up\" trend | `0.5` | |\n| `TREND_FAST_UP_THRESHOLD` | Rate for \"fast_up\" trend | `2.0` | |\n| `TREND_VERY_FAST_UP_THRESHOLD` | Rate for \"very_fast_up\" trend | `4.0` | |\n| **Insulin Settings** |\n| `ENABLE_INSULIN_RECOMMENDATIONS` | Enable insulin suggestions | `true` | Safety feature |\n| `INSULIN_EFFECTIVENESS` | Glucose drop per insulin unit | `40.0` | mg/dL per unit |\n| `INSULIN_UNIT_RATIO` | Insulin calculation ratio | `0.2` | Dosing multiplier |\n| `INSULIN_DURATION_RAPID` | Rapid insulin duration | `180` | Minutes active |\n| `INSULIN_DURATION_LONG` | Long insulin duration | `720` | Minutes active |\n| **Carbohydrate Settings** |\n| `ENABLE_CARB_RECOMMENDATIONS` | Enable carb suggestions | `true` | Safety feature |\n| `CARB_EFFECTIVENESS` | Glucose rise per 15g carbs | `15.0` | mg/dL per 15g |\n| `CARB_TO_GLUCOSE_RATIO` | Glucose rise per 1g carb | `3.5` | mg/dL per gram |\n| `CARB_ABSORPTION_FAST` | Fast carb absorption time | `90` | Minutes |\n| `CARB_ABSORPTION_SLOW` | Slow carb absorption time | `180` | Minutes |\n| **IOB/COB Thresholds** |\n| `IOB_THRESHOLD_HIGH` | High IOB threshold | `2.0` | Units for warnings |\n| `COB_THRESHOLD_HIGH` | High COB threshold | `30.0` | Grams for warnings |\n| **System Settings** |\n| `DATABASE_PATH` | SQLite database file path | `glucose_monitor.db` | |\n| `DATA_RETENTION_DAYS` | Days to keep historical data | `30` | |\n| `LOG_LEVEL` | Logging verbosity | `INFO` | DEBUG/INFO/WARNING/ERROR |\n| `ENABLE_TERMINAL_OUTPUT` | Show terminal display | `true` | Real-time output |\n\n## Usage\n\n### Basic Monitoring\n```bash\n# Start monitoring with real Dexcom data\npython -m src.main\n\n# Start with mock data for testing\npython -m src.main --mock\n\n# Specify custom configuration file\npython -m src.main --env-file custom.env\n```\n\n### Run Tests\n```bash\n# Run all tests\npytest\n\n# Run specific test categories\npytest tests/test_recommendations.py -v\npytest tests/test_analysis.py -v\n\n# Run tests with coverage\npytest --cov=src tests/\n```\n\n## How It Works\n\n### 1. Data Collection\n- Connects to Dexcom Share API using pydexcom library\n- Retrieves new glucose readings every 5 minutes + 5 seconds\n- Stores readings in SQLite database with timestamp and trend information\n\n### 2. Analysis Engine\nThe system performs multi-layered analysis:\n\n**Trend Analysis**\n- Calculates rate of change (mg/dL per minute) using configurable thresholds\n- Determines trend direction and strength with linear regression\n- Assesses glucose stability using variance analysis\n\n**IOB/COB Tracking**\n- Tracks Insulin on Board using configurable insulin duration curves\n- Monitors Carbs on Board with absorption time modeling  \n- Supports manual IOB overrides from pump/Omnipod readings\n- Calculates glucose impact predictions from active insulin/carbs\n\n**Prediction Algorithms**\n- Linear extrapolation for consistent trends\n- Polynomial fitting for curved patterns\n- Considers IOB/COB effects on future glucose levels\n- Ensemble approach selecting best method with confidence scoring\n\n### 3. Recommendation System\n\n**Four Recommendation Types**:\n1. **Carbohydrate Recommendations** (Priority 1) - For low/falling glucose\n2. **Insulin Recommendations** (Priority 2) - For high/stable glucose  \n3. **IOB Status Recommendations** (Priority 4) - To verify active insulin accuracy\n4. **Monitoring Recommendations** (Priority 5) - Increased monitoring frequency\n\n**IOB Status Recommendations** trigger when:\n- Approaching low glucose without IOB data (High urgency)\n- Glucose rising fast with no IOB data (Medium urgency)  \n- High IOB (\u003e0.6u) significantly affecting predictions (Medium urgency)\n- Approaching low with existing IOB requiring verification (High urgency)\n\n**Safety-First Design**:\n- Conservative thresholds with configurable sensitivity\n- Multiple safety checks including IOB consideration\n- Clear contraindications (e.g., no insulin if trending down rapidly)\n\n### 4. Telegram Integration\n- Real-time bidirectional communication\n- Plain number shortcuts for quick IOB entry (supports `2.4` and `2,4` formats)\n- Rich command processing with parameter validation\n- Formatted responses with safety notes and recommendations\n\n## Message Examples\n\n### IOB Status Recommendation\n```\n🔄 IOB Status Check - 14:30\n\nIMPORTANT: Check current IOB status - approaching low with 0.6u IOB - verify accuracy for safe predictions.\n\nCurrent IOB: 0.6 units\nExpected effect: 0.6u IOB should lower glucose by ~24 mg/dL\n\n💡 Safety Notes:\n• Accurate IOB improves prediction accuracy\n• Check pump/Omnipod display for current active insulin  \n• Update using /iob command or plain number in Telegram\n```\n\n### Insulin Recommendation (IOB-Aware)\n```\n🩸 Glucose Alert - 14:30\n\nCurrent: 220 mg/dL ⬆️\nTrend: Rising\nIOB: 0.2 units (minimal impact)\n\n💉 Insulin Recommendation\nConsider 0.7 units of rapid-acting insulin. Adjusted for current IOB.\n• Suggested: 0.7 units (reduced from 0.9u due to active insulin)\n\n⚠️ Safety reminders:\n• Consult healthcare provider before administering insulin\n• Monitor glucose closely after insulin administration\n```\n\n### Quick IOB Update via Telegram\n```\nUser: 2.4\nBot: ✅ IOB Override Set\n\nIOB updated to 2.4 units from telegram-shortcut\nExpected glucose effect: -96 mg/dL over next 60 minutes\nLast updated: 14:32\n```\n\n### Automatic Timestamp-Based Scheduling\nThe monitoring system automatically schedules the next reading check based on the Dexcom sensor's actual timestamp plus the configured interval (`SENSOR_READING_INTERVAL_SECONDS`). This ensures optimal synchronization with Dexcom's update schedule without manual intervention.\n\n## Architecture\n\n```\nsrc/\n├── main.py                 # Main application entry point\n├── config/                 # Configuration management\n├── database/               # SQLite database operations\n├── sensors/                # Dexcom and mock data clients  \n├── analysis/               # Trend analysis and predictions\n│   ├── trend_analyzer.py   # Configurable glucose trend analysis\n│   ├── predictor.py        # Future value predictions\n│   ├── iob_calculator.py   # IOB/COB tracking and calculations\n│   └── recommendations.py  # Four-tier recommendation engine\n├── notifications/          # Telegram integration with commands\n│   └── telegram_bot.py     # Bidirectional bot with IOB shortcuts\n├── commands/               # Command processing and formatting\n└── terminal/               # Interactive terminal interface\n\ntests/                      # Comprehensive test suite\n```\n\n## Safety Features\n\n### Built-in Safety Checks\n- No insulin recommendations for rapidly falling glucose\n- IOB consideration in all insulin calculations\n- Conservative carb calculations for lows\n- Maximum limits on insulin suggestions (0.1-2.0 units)\n- Mandatory healthcare provider consultation reminders\n\n### Emergency Protocols  \n- Critical alerts for glucose \u003c55 or \u003e300 mg/dL\n- Immediate Telegram notifications with IOB context\n- Clear action steps with timing and expected effects\n\n### Data Validation\n- Realistic glucose range validation (40-400 mg/dL)\n- Trend consistency checking with configurable thresholds  \n- Prediction reasonableness assessment including IOB effects\n- IOB/COB data integrity validation\n\n## Troubleshooting\n\n### Common Issues\n\n**Dexcom Connection Errors**\n- Ensure Dexcom Follow is enabled in the Dexcom mobile app\n- Verify username/password for Dexcom Share\n- Check DEXCOM_OUS setting for non-US accounts\n```bash\n# Test Dexcom connection  \npython -c \"from src.sensors import DexcomClient; from src.config import Settings; DexcomClient(Settings()).test_connection()\"\n```\n\n**Telegram Bot Issues**\n- Verify bot token and chat ID are correct\n- Check that the bot has permission to send messages\n- Test with simple commands first\n```bash\n# Test Telegram connection\npython debug_telegram.py\n```\n\n**Configuration Issues**\n```bash\n# Validate configuration\npython -c \"from src.config import Settings; print(Settings().to_dict())\"\n```\n\n## Contributing\n\n1. Fork the repository\n2. Create a feature branch  \n3. Add tests for new functionality\n4. Ensure all tests pass: `pytest`\n5. Submit a pull request\n\n### Development Setup\n```bash\n# Install development dependencies\npip install pytest pytest-cov pytest-mock\n\n# Run tests with coverage\npytest --cov=src tests/\n\n# Run specific test scenarios\npytest tests/test_recommendations.py::TestRecommendationScenarios::test_iob_recommendation_approaching_low -v\n```\n\n## License\n\n[Add your license here]\n\n## Acknowledgments\n\n- Built with [pydexcom](https://pypi.org/project/pydexcom/) for Dexcom Share integration\n- Requires Dexcom Follow to be enabled for API access\n- Uses SQLite for reliable data storage\n- Telegram Bot API for real-time communication\n\n---\n\n**Remember: This tool is designed to supplement, not replace, proper medical care and monitoring. Always consult with healthcare professionals for diabetes management decisions.**","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fspamsch%2Fdiabetes-recommendation-engine","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fspamsch%2Fdiabetes-recommendation-engine","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fspamsch%2Fdiabetes-recommendation-engine/lists"}