DEV Community

agenthustler
agenthustler

Posted on

Building a Crypto Fear and Greed Index Tracker with Python

The Crypto Fear & Greed Index measures sentiment from 0 (extreme fear) to 100 (extreme greed). Build a tracker combining this with price data for better trading signals.

Alternative.me API

import requests, statistics
from datetime import datetime

class FearGreedTracker:
    def __init__(self):
        self.fg = "https://api.alternative.me/fng/"
        self.cg = "https://api.coingecko.com/api/v3"

    def current(self):
        d = requests.get(f"{self.fg}?limit=1").json()["data"][0]
        return {"value":int(d["value"]),"label":d["value_classification"]}

    def history(self, days=90):
        return [{"value":int(d["value"]),"label":d["value_classification"],
                 "date":datetime.fromtimestamp(int(d["timestamp"])).strftime("%Y-%m-%d")}
                for d in requests.get(f"{self.fg}?limit={days}").json()["data"]]

    def btc_prices(self, days=90):
        r = requests.get(f"{self.cg}/coins/bitcoin/market_chart",
            params={"vs_currency":"usd","days":days})
        return {datetime.fromtimestamp(p[0]/1000).strftime("%Y-%m-%d"):p[1]
                for p in r.json()["prices"]}
Enter fullscreen mode Exit fullscreen mode

Correlation Analysis

    def correlate(self, days=90):
        fg, prices = self.history(days), self.btc_prices(days)
        paired = [{"fg":e["value"],"price":prices[e["date"]]}
                  for e in fg if e["date"] in prices]
        sigs = {"fear":[],"greed":[]}
        for i, p in enumerate(paired):
            if i+7 < len(paired):
                ret = (paired[i+7]["price"]-p["price"])/p["price"]*100
                if p["fg"] <= 20: sigs["fear"].append(ret)
                elif p["fg"] >= 80: sigs["greed"].append(ret)
        for k, v in sigs.items():
            if v: print(f"{k}: avg 7d={statistics.mean(v):+.2f}%, win={sum(1 for r in v if r>0)/len(v)*100:.0f}%")

    def social_sentiment(self):
        r = requests.get("https://www.reddit.com/r/cryptocurrency/hot.json",
            headers={"User-Agent":"Bot/1.0"})
        posts = r.json()["data"]["children"]
        bull = sum(1 for p in posts if any(w in p["data"]["title"].lower() for w in ["bull","moon","pump"]))
        bear = sum(1 for p in posts if any(w in p["data"]["title"].lower() for w in ["bear","crash","dump"]))
        t = bull+bear or 1
        return {"bull":bull/t*100,"bear":bear/t*100}

    def composite(self):
        fg, soc = self.current(), self.social_sentiment()
        score = fg["value"]*0.6 + soc["bull"]*0.4
        print(f"Composite: {score:.0f}/100 | F&G:{fg['value']} | Social:{soc['bull']:.0f}% bull")

t = FearGreedTracker()
print(t.current())
t.correlate(90)
t.composite()
Enter fullscreen mode Exit fullscreen mode

Scaling

ScraperAPI for social media JS rendering. ThorData for IP diversity. ScrapeOps for monitoring.

Insights

Buying during Extreme Fear and selling during Extreme Greed historically outperforms. Combine with price action for best results.

Top comments (0)