Lecture 06 · Module 1 — Foundations

Your First Producer

Python env setup · Streaming stock data · yFinance · Live BTC · Multi-producer pipelines

90 min
🐍 Python 3.x
📦 kafka-python · yfinance
02 / 14Agenda

Today's 90 Minutes

TimeTopicFormat
0 – 10Recap — Kafka architecture from Lecture 5Q&A
10 – 20What is a producer? Anatomy of producer.pyTheory
20 – 35Python env setup — venv on Mac & WindowsSetup
35 – 50Lab 1 — Stream stock_data.csv to KafkaLab
50 – 65Lab 2 — TCS live data via yFinanceLab
65 – 75Lab 3 — BTC-USD real-time 24×7 streamLab
75 – 85Lab 4 — Two producers, one topic (TCS + INFY)Lab
85 – 90Key takeaways + preview of Lecture 7Wrap-up
03 / 14Theory

What Is a Producer?

A producer is any application that publishes events to a Kafka topic. It doesn't know or care who reads the data — it just sends.

producer.py
YOUR CODE
Kafka Topic
stock-topic
Consumer(s)
analytics, alerts...

What a producer does in 3 steps

  1. Connect — establishes a TCP connection to the Kafka broker (your Docker container)
  2. Serialize — converts your Python dict → bytes (usually JSON) so Kafka can store it
  3. Send — publishes the message to a named topic; Kafka acknowledges receipt

Business framing: The producer is the "reporter on the ground". It records what's happening right now and files it with the newswire (Kafka). It doesn't know who will read the story.

04 / 14Theory

Anatomy of producer.py

Let's break down every line and why it exists.

KafkaProducer(...) Creates the connection to the broker. Holds an internal buffer and background thread for sending.
bootstrap_servers Address of at least one broker — Kafka uses it to discover the full cluster. localhost:9092 is your Docker container.
value_serializer Converts your dict → bytes before sending. JSON is human-readable and easy to debug. Avro (Lecture 8) is smaller and faster.
retries=5 Retry failed sends up to 5 times — handles transient network hiccups automatically. Without this, a 1-second network blip drops the message.
producer.partitions_for(TOPIC) Validates the broker is reachable before starting the loop. Fails fast with a clear error instead of silently dropping messages.
producer.send(TOPIC, value=row) Non-blocking publish — returns a Future. The message goes into an internal buffer and is flushed in the background.
producer.flush() Waits until all buffered messages are sent. Always call this before exiting — without it, the last few messages may be silently dropped.
05 / 14Setup

Python Environment Setup

A virtual environment (venv) keeps your project's libraries separate from your system Python — no version conflicts between projects.

Do this once per project. All students should work inside a venv named venv inside their SDA folder.

Step 1 — Create the SDA project folder

# Open Terminal and run:
mkdir ~/SDA
cd ~/SDA
:: Open Command Prompt (cmd) and run:
:: SDA folder is usually on C: or D: — choose whichever drive you use
mkdir C:\SDA
cd C:\SDA
:: If your files are on D: drive instead:
:: mkdir D:\SDA  and  cd D:\SDA

Step 2 — Create the virtual environment

python3 -m venv venv
python -m venv venv
06 / 14Setup

Activate & Install Packages

You must activate the venv every time you open a new terminal before running any Python files.

Activate the venv

cd ~/SDA
source venv/bin/activate
# Your prompt changes to: (venv) $
cd C:\SDA
venv\Scripts\activate
:: Your prompt changes to: (venv) C:\SDA>
:: If your SDA folder is on D: use:  cd D:\SDA

Install required libraries

bash (inside activated venv)
pip install kafka-python yfinance

Verify installation

bash
python -c "from kafka import KafkaProducer; import yfinance; print('✅ All good')"

Common issue: If you see ModuleNotFoundError, the venv is not activated. Run the activate command above first.

Deactivate when done: just type deactivate

07 / 14Lab 1

Stream stock_data.csv to Kafka

Our first producer reads a CSV file row by row and streams each row as a JSON message, simulating a live tick feed.

python · producer.py
import csv, time, json, sys
from kafka import KafkaProducer, errors

KAFKA_BROKER = 'localhost:9092'
TOPIC        = 'stock-topic'

try:
    producer = KafkaProducer(
        bootstrap_servers=KAFKA_BROKER,
        value_serializer=lambda v: json.dumps(v).encode('utf-8'),
        retries=5
    )
    producer.partitions_for(TOPIC)
    print("✅ Connected to Kafka at", KAFKA_BROKER)
except errors.NoBrokersAvailable:
    print("❌ Kafka not running — docker-compose up -d")
    sys.exit(1)

with open('stock_data.csv', 'r') as f:
    reader = csv.DictReader(f)
    for row in reader:
        producer.send(TOPIC, value=row)
        print(f"Produced: {row}")
        time.sleep(1)

producer.flush()

Run it

bash
# Make sure docker-compose is up and venv is activated
python producer.py
08 / 14Theory

Fetching Real Data with yFinance

Instead of a static CSV, we can pull real historical and live market data directly from Yahoo Finance using the yfinance Python library.

What it gives you

MethodDataUse Case
ticker.history(period, interval)OHLCV bars for a time rangeHistorical backtesting, streaming replays
ticker.fast_infoLatest price & basic statsLive price polling every N seconds
ticker.infoFull company profileEnriching events with company metadata

Quick test

python
import yfinance as yf
tcs = yf.Ticker("TCS.NS")
df  = tcs.history(period="1d", interval="1m")
print(df.tail(3))

Ticker formats: Indian NSE stocks use .NS suffix — TCS.NS, INFY.NS, RELIANCE.NS. US stocks are just the ticker: AAPL, MSFT. Crypto uses BTC-USD, ETH-USD.

09 / 14Lab 2

TCS Live Data — tcs_producer.py

Fetches 5 days of 1-minute OHLCV bars for TCS.NS from Yahoo Finance and streams them to Kafka.

python · tcs_producer.py
import json, time, sys
import yfinance as yf
from kafka import KafkaProducer, errors

producer = KafkaProducer(
    bootstrap_servers='localhost:9092',
    value_serializer=lambda v: json.dumps(v).encode('utf-8')
)

tcs = yf.Ticker("TCS.NS")
df  = tcs.history(period="5d", interval="1m").reset_index()

for _, row in df.iterrows():
    record = {
        "symbol":    "TCS.NS",
        "timestamp": str(row["Datetime"]),
        "close":     round(float(row["Close"]), 2),
        "volume":    int(row["Volume"])
    }
    producer.send("stock-topic", value=record)
    print(f"TCS | {record['timestamp']} | ₹{record['close']}")
    time.sleep(0.5)

producer.flush()

What you'll see: 5 days × ~375 bars/day ≈ ~1,875 TCS price points flowing into Kafka, one every 0.5 seconds.

10 / 14Lab 3

BTC-USD — Real-Time 24×7

Bitcoin trades every second of every day. This producer polls the live price every 10 seconds and never stops — until you press Ctrl+C.

python · btc_producer.py
import json, time, sys
from datetime import datetime
import yfinance as yf
from kafka import KafkaProducer

producer = KafkaProducer(
    bootstrap_servers='localhost:9092',
    value_serializer=lambda v: json.dumps(v).encode('utf-8')
)

print("₿ BTC-USD live stream — Ctrl+C to stop\n")
count = 0
while True:
    btc    = yf.Ticker("BTC-USD")
    record = {
        "symbol":    "BTC-USD",
        "timestamp": datetime.utcnow().isoformat(),
        "price":     round(float(btc.fast_info.last_price), 2),
        "market":    "crypto"
    }
    producer.send("stock-topic", value=record)
    count += 1
    print(f"[{count}] BTC: ${record['price']:,.2f}")
    time.sleep(10)   # poll every 10 seconds

Why is this different from TCS? TCS used historical data (a replay). BTC is truly live — the price changes every poll and the loop never ends. This is what a real-time streaming source looks like.

11 / 14Theory

Multiple Producers, One Topic

Kafka topics can receive events from many producers simultaneously. Each producer writes independently — Kafka merges all messages into a single ordered stream.

tcs_producer.py
TCS.NS price bars
stock-topic
all symbols, interleaved
infy_producer.py
INFY.NS price bars

A consumer reading stock-topic receives both TCS and INFY messages interleaved, identified by the symbol field.

Why this is powerful

Real-world parallel: Bloomberg Terminal aggregates price feeds from hundreds of exchanges into a single stream. Each exchange is a producer. Traders consume one unified topic.

12 / 14Lab 4

TCS + INFY — Same Topic

Open two terminals. Run one producer in each. Both stream to stock-topic simultaneously.

python · infy_producer.py (key lines)
# Only change vs tcs_producer.py: symbol and ticker
infy = yf.Ticker("INFY.NS")         # ← Infosys
df   = infy.history(period="5d", interval="1m").reset_index()

for _, row in df.iterrows():
    record = {
        "symbol":    "INFY.NS",     # ← Infosys symbol
        "timestamp": str(row["Datetime"]),
        "close":     round(float(row["Close"]), 2),
        "volume":    int(row["Volume"])
    }
    producer.send("stock-topic", value=record)

Run both at the same time

bash — Terminal A
python tcs_producer.py
bash — Terminal B
python infy_producer.py

Now open the Kafka console consumer in a third terminal to see both streams interleaved:

bash — Terminal C
docker exec -it kafka kafka-console-consumer.sh \
  --bootstrap-server localhost:9092 \
  --topic stock-topic --from-beginning
13 / 14Downloads

All Lab Files

Download all files for today's lab. Place them in your ~/SDA folder and run with your activated venv.

Install all at once:

pip install kafka-python yfinance
14 / 14Wrap-Up

Key Takeaways

Next — Lecture 7: We build the consumer. You'll read your own stock-topic stream in Python, track live portfolio value, and trigger alerts when a stock moves more than 2%.

1 / 14