Aibytec

logo
AI BY TEC

Build an AI Bitcoin Sentiment Monitor with Python & Streamlit (Free)

Build an AI Bitcoin Sentiment Monitor with Python & Streamlit (Free) | AIByTec
Python Tutorial

Build an AI Bitcoin Sentiment Monitor with Python & Streamlit (Free)

Muhammad Rustam| February 24, 2026| ~2 Hours Build Time| Beginner Friendly| AIByTec.com

With Bitcoin crashing 50% and AI agents controlling 20% of crypto trading volume, there's never been a better time to understand how AI market monitoring works — by building it yourself. This tutorial walks you through creating a fully functional, AI-powered Bitcoin sentiment dashboard using free tools. Deploy it, add it to your portfolio, and impress employers.

Python 3.10+
Streamlit
HuggingFace FinBERT
CoinGecko API (Free)
Plotly Charts
HF Spaces (Free Hosting)

What You'll Build

By the end of this tutorial, you'll have a live, deployed AI dashboard that displays:

A real-time Bitcoin price chart with 7-day history pulled from CoinGecko's free API. An AI sentiment analyzer powered by FinBERT — a financial BERT model from HuggingFace that classifies crypto news as positive, negative, or neutral. A live Fear & Greed style sentiment gauge. A news feed with per-headline AI sentiment scores. Price metrics showing 24h change, volume, and market cap. All running for free on Hugging Face Spaces, accessible from any device, anywhere in the world.

Live Dashboard Preview
🤖 AIByTec Bitcoin AI Monitor
BTC Price$63,242.17
24h Change▼ −4.2%
AI Sentiment Score28/100 (Bearish)
News Headlines Analyzed12 (Last Hour)
Positive / Negative Split3 / 9
ModelProsusAI/FinBERT

Requirements & Setup

Everything in this tutorial is 100% free. Here's what you need:

Python 3.10+
Download from python.org
CoinGecko API
Free tier — no key needed for basic endpoints
HuggingFace Account
Free at huggingface.co
Git (optional)
For deployment to HF Spaces

Open your terminal and install the required packages:

bashterminal
pip install streamlit transformers torch requests pandas plotly

💡 Pro Tip: Create a virtual environment first — python -m venv btc-env then source btc-env/bin/activate (Mac/Linux) or btc-env\Scripts\activate (Windows) — to keep your project dependencies clean.

STEP 1 Fetch Bitcoin Data from CoinGecko API

CoinGecko's free API provides everything we need — current price, 24h change, volume, market cap, and 7-day price history. No API key required for the endpoints we'll use.

Create a file called data.py in your project folder:

pythondata.py
# data.py — Fetch Bitcoin market data from CoinGecko API
import requests
import pandas as pd
from datetime import datetime

def get_bitcoin_price():
    """Fetch current Bitcoin price and 24h metrics"""
    url = "https://api.coingecko.com/api/v3/coins/bitcoin"
    params = {
        "localization": "false",
        "tickers": "false",
        "community_data": "false",
        "developer_data": "false"
    }
    response = requests.get(url, params=params, timeout=10)
    data = response.json()
    market = data["market_data"]

    return {
        "price": market["current_price"]["usd"],
        "change_24h": market["price_change_percentage_24h"],
        "change_7d": market["price_change_percentage_7d"],
        "volume": market["total_volume"]["usd"],
        "market_cap": market["market_cap"]["usd"],
        "ath": market["ath"]["usd"],
        "ath_change": market["ath_change_percentage"]["usd"],
        "last_updated": data["last_updated"]
    }

def get_price_history(days=7):
    """Fetch Bitcoin price history for chart"""
    url = f"https://api.coingecko.com/api/v3/coins/bitcoin/market_chart"
    params = {"vs_currency": "usd", "days": days, "interval": "hourly"}
    response = requests.get(url, params=params, timeout=10)
    data = response.json()

    prices = data["prices"]
    df = pd.DataFrame(prices, columns=["timestamp", "price"])
    df["datetime"] = pd.to_datetime(df["timestamp"], unit="ms")
    return df

STEP 2 Add AI Sentiment Analysis with FinBERT

FinBERT is a BERT model pre-trained on financial text. It classifies any text as positive, negative, or neutral with high accuracy for financial content. We'll use it to analyze crypto news headlines and generate an overall sentiment score.

Create sentiment.py:

pythonsentiment.py
# sentiment.py — AI sentiment analysis using FinBERT
from transformers import pipeline
import streamlit as st

# Load model once — @st.cache_resource prevents reloading every refresh
@st.cache_resource
def load_sentiment_model():
    """Load FinBERT — financial sentiment analysis model"""
    return pipeline(
        "text-classification",
        model="ProsusAI/finbert",
        return_all_scores=True
    )

def analyze_sentiment(texts: list[str]) -> dict:
    """
    Analyze a list of news headlines.
    Returns: sentiment label, score (0-100), and per-headline results.
    """
    model = load_sentiment_model()
    results = []

    for text in texts:
        scores = model(text[:512])[0]  # FinBERT max 512 tokens
        score_dict = {s["label"]: s["score"] for s in scores}
        label = max(score_dict, key=score_dict.get)
        confidence = score_dict[label]
        results.append({
            "text": text[:80] + ("..." if len(text) > 80 else ""),
            "label": label,
            "confidence": round(confidence * 100, 1)
        })

    # Calculate overall sentiment score 0-100
    pos_count = sum(1 for r in results if r["label"] == "positive")
    neg_count = sum(1 for r in results if r["label"] == "negative")
    total = len(results)
    score = round((pos_count / total) * 100) if total > 0 else 50

    overall = "Bullish" if score > 60 else "Bearish" if score < 40 else "Neutral"

    return {
        "score": score,
        "label": overall,
        "positive": pos_count,
        "negative": neg_count,
        "neutral": total - pos_count - neg_count,
        "headlines": results
    }

STEP 3 Build the Streamlit Dashboard

Now we tie everything together into a beautiful, interactive Streamlit dashboard. Create app.py:

pythonapp.py — Main Streamlit Dashboard
# app.py — AI Bitcoin Sentiment Monitor | AIByTec
import streamlit as st
import plotly.graph_objects as go
import plotly.express as px
from data import get_bitcoin_price, get_price_history
from sentiment import analyze_sentiment
from datetime import datetime

# ── PAGE CONFIG ──────────────────────────────────
st.set_page_config(
    page_title="AI Bitcoin Monitor | AIByTec",
    page_icon="🤖",
    layout="wide",
    initial_sidebar_state="collapsed"
)

# ── SAMPLE HEADLINES (replace with real news API) ─
HEADLINES = [
    "Bitcoin falls below $63,000 amid extreme investor fear",
    "US tariff proposals trigger crypto market selloff",
    "Bitcoin ETF sees $203 million in outflows this week",
    "CZ predicts Bitcoin could reach $200,000 this cycle",
    "Fear and Greed Index hits record low of 5",
    "Agentic AI systems now control 20% of crypto trading",
    "Institutional investors see opportunity in Bitcoin dip",
    "Prediction markets give 90% odds of sub-$60K Bitcoin",
]

# ── MAIN APP ─────────────────────────────────────
st.title("🤖 AI Bitcoin Sentiment Monitor")
st.caption("Powered by FinBERT + CoinGecko API | Built with AIByTec")
st.divider()

# Load data with spinner
with st.spinner("Fetching live Bitcoin data..."):
    btc = get_bitcoin_price()
    history = get_price_history(days=7)

# ── PRICE METRICS ROW ─────────────────────────────
col1, col2, col3, col4 = st.columns(4)
with col1:
    st.metric("BTC Price", f"${btc['price']:,.2f}",
              f"{btc['change_24h']:.2f}%")
with col2:
    st.metric("7D Change", f"{btc['change_7d']:.2f}%")
with col3:
    st.metric("From ATH", f"{btc['ath_change']:.1f}%")
with col4:
    vol_b = btc['volume'] / 1e9
    st.metric("24h Volume", f"${vol_b:.2f}B")

st.divider()

# ── PRICE CHART ───────────────────────────────────
fig = go.Figure()
fig.add_trace(go.Scatter(
    x=history["datetime"], y=history["price"],
    mode="lines", name="BTC/USD",
    line=dict(color="#f7931a", width=2),
    fill="tozeroy",
    fillcolor="rgba(247,147,26,0.05)"
))
fig.update_layout(
    title="Bitcoin Price — 7 Day History",
    paper_bgcolor="rgba(0,0,0,0)",
    plot_bgcolor="rgba(0,0,0,0)",
    font=dict(color="#d4d0e8"),
    xaxis=dict(gridcolor="rgba(255,255,255,0.05)"),
    yaxis=dict(gridcolor="rgba(255,255,255,0.05)", tickprefix="$"),
    height=350
)
st.plotly_chart(fig, use_container_width=True)

# ── AI SENTIMENT ANALYSIS ─────────────────────────
st.subheader("🧠 AI Sentiment Analysis")
with st.spinner("Running FinBERT sentiment analysis..."):
    sentiment = analyze_sentiment(HEADLINES)

col_s1, col_s2, col_s3 = st.columns([1, 2, 1])
with col_s1:
    color = "🟢" if sentiment["label"] == "Bullish" else "🔴"
    st.metric("AI Sentiment",
              f"{color} {sentiment['label']}",
              f"{sentiment['score']}/100")

with col_s2:
    df_sent = px.bar(
        x=["Positive", "Neutral", "Negative"],
        y=[sentiment["positive"], sentiment["neutral"], sentiment["negative"]],
        color=["Positive", "Neutral", "Negative"],
        color_discrete_map={"Positive":"#00e5a0","Neutral":"#7b3fe4","Negative":"#ff4d6d"},
        title="Sentiment Distribution",
        height=200
    )
    df_sent.update_layout(paper_bgcolor="rgba(0,0,0,0)",
                          plot_bgcolor="rgba(0,0,0,0)",
                          showlegend=False,
                          font=dict(color="#d4d0e8"))
    st.plotly_chart(df_sent, use_container_width=True)

# ── HEADLINE TABLE ────────────────────────────────
st.subheader("📰 News Headlines — AI Sentiment Scores")
for h in sentiment["headlines"]:
    icon = "🟢" if h["label"] == "positive" else "🔴" if h["label"] == "negative" else "⚪"
    st.write(f"{icon} **{h['label'].upper()}** ({h['confidence']}%) — {h['text']}")

st.caption(f"Last updated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} | Model: ProsusAI/FinBERT")

💡 Run it locally: In your terminal, run streamlit run app.py — your browser will open automatically at localhost:8501. You should see the full dashboard with live Bitcoin data and AI sentiment analysis.

STEP 4 Deploy Free on Hugging Face Spaces

Hugging Face Spaces provides free hosting for Streamlit apps. Here's how to deploy in 5 minutes:

bashrequirements.txt — Create this file
streamlit>=1.32.0
transformers>=4.38.0
torch>=2.2.0
requests>=2.31.0
pandas>=2.1.0
plotly>=5.18.0

Then go to huggingface.co/spaces, click "Create New Space", choose Streamlit as the SDK, upload your four files (app.py, data.py, sentiment.py, requirements.txt), and your app goes live at https://huggingface.co/spaces/YOUR-USERNAME/bitcoin-ai-monitor — completely free, accessible worldwide.

Extend This Project (6 Ideas)

This is a foundation — here's how to level it up for your portfolio or course capstone project:

📡
Real News Feed
Connect to CryptoPanic's free API or NewsAPI to pull live crypto headlines instead of hardcoded ones.
DIFFICULTY: EASY
📱
SMS / Email Alerts
Add Twilio (free tier) to send you an SMS alert when the AI sentiment drops below 20 — your personal bear market alarm.
DIFFICULTY: EASY
🔮
Price Prediction
Add a 24-hour price prediction using Facebook Prophet or a simple LSTM model trained on historical data.
DIFFICULTY: MEDIUM
🐦
Twitter/X Sentiment
Integrate Twitter/X API to analyze crypto tweets in real time — creating a social sentiment layer on top of news sentiment.
DIFFICULTY: MEDIUM
📊
Multi-Coin Dashboard
Expand to track ETH, SOL, BNB — add a dropdown selector and sentiment comparison across multiple assets.
DIFFICULTY: EASY
🤖
Agentic AI Mode
Transform this into an agentic system that autonomously checks sentiment every hour and builds a historical database — your first agentic AI project.
DIFFICULTY: ADVANCED
// Career Value

A deployed, live AI Bitcoin dashboard is an exceptional portfolio project. It demonstrates API integration, NLP with HuggingFace, Streamlit deployment, and financial AI — exactly the skill set that AI engineering roles look for in 2026. Link it on your LinkedIn and AIByTec profile.

Frequently Asked Questions

Can I build an AI Bitcoin monitor completely for free?
Yes, completely free. This tutorial uses CoinGecko's free API (no key required for basic endpoints), HuggingFace's free FinBERT model, Streamlit's free framework, and Hugging Face Spaces for free hosting. Total cost is $0. The only requirement is a computer with Python installed.
What Python skills do I need for this tutorial?
Basic Python knowledge is sufficient — understanding functions, loops, and importing libraries. No machine learning background is required because we use pre-trained HuggingFace models that work out of the box. If you've completed any basic Python course, you can follow this tutorial.
What is FinBERT and why is it better than regular sentiment analysis?
FinBERT is a BERT-based transformer model pre-trained specifically on financial text including earnings calls, financial news, and economic reports. For crypto and financial sentiment analysis, it dramatically outperforms general-purpose models (like VADER or basic BERT) because it understands financial terminology like "bearish," "ETF outflows," and "market correction" in context.
Can I use this dashboard for actual trading decisions?
This dashboard is educational and for informational purposes only — it is not a trading signal generator. Sentiment analysis is one input among many and has significant limitations. Never make trading decisions based on any single indicator including AI sentiment scores. This project teaches you how AI monitoring tools work and demonstrates valuable skills — it is not an investment tool.
How can I extend this for my AI course portfolio?
Strong extensions: integrate CryptoPanic's free API for live news, add SMS alerts via Twilio free tier, include price prediction with Facebook Prophet, add Twitter sentiment via Twitter API, expand to multi-coin monitoring, or build it into a full agentic AI system that autonomously monitors every hour. Any of these significantly enhance the project's portfolio value.

Want to Learn More AI Projects Like This?

Join AIByTec's Generative AI course — from Streamlit and Gradio dashboards to full agentic AI systems. Build your portfolio from day one.

Explore Full Course More Tutorials
⚠️ Disclaimer: This tutorial is for educational purposes only. The completed project is not a trading tool and should not be used to make financial decisions. Cryptocurrency investments carry significant risk. Always do your own research.

Leave a Comment

Your email address will not be published. Required fields are marked *

Advanced AI solutions for business Chatbot
Chat with AI
Verified by MonsterInsights