Python env setup · Streaming stock data · yFinance · Live BTC · Multi-producer pipelines
| Time | Topic | Format |
|---|---|---|
| 0 – 10 | Recap — Kafka architecture from Lecture 5 | Q&A |
| 10 – 20 | What is a producer? Anatomy of producer.py | Theory |
| 20 – 35 | Python env setup — venv on Mac & Windows | Setup |
| 35 – 50 | Lab 1 — Stream stock_data.csv to Kafka | Lab |
| 50 – 65 | Lab 2 — TCS live data via yFinance | Lab |
| 65 – 75 | Lab 3 — BTC-USD real-time 24×7 stream | Lab |
| 75 – 85 | Lab 4 — Two producers, one topic (TCS + INFY) | Lab |
| 85 – 90 | Key takeaways + preview of Lecture 7 | Wrap-up |
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.
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.
Let's break down every line and why it exists.
localhost:9092 is your Docker container.
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.
# 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
python3 -m venv venv
python -m venv venv
You must activate the venv every time you open a new terminal before running any Python files.
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
pip install kafka-python yfinance
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
Our first producer reads a CSV file row by row and streams each row as a JSON message, simulating a live tick feed.
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()
# Make sure docker-compose is up and venv is activated
python producer.py
Instead of a static CSV, we can pull real historical and live market data directly from Yahoo Finance using the yfinance Python library.
| Method | Data | Use Case |
|---|---|---|
ticker.history(period, interval) | OHLCV bars for a time range | Historical backtesting, streaming replays |
ticker.fast_info | Latest price & basic stats | Live price polling every N seconds |
ticker.info | Full company profile | Enriching events with company metadata |
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.
Fetches 5 days of 1-minute OHLCV bars for TCS.NS from Yahoo Finance and streams them to Kafka.
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.
Bitcoin trades every second of every day. This producer polls the live price every 10 seconds and never stops — until you press Ctrl+C.
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.
Kafka topics can receive events from many producers simultaneously. Each producer writes independently — Kafka merges all messages into a single ordered stream.
A consumer reading stock-topic receives both TCS and INFY messages interleaved, identified by the symbol field.
reliance_producer.py, zero changes to the consumerReal-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.
Open two terminals. Run one producer in each. Both stream to stock-topic simultaneously.
# 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)
python tcs_producer.py
python infy_producer.py
Now open the Kafka console consumer in a third terminal to see both streams interleaved:
docker exec -it kafka kafka-console-consumer.sh \
--bootstrap-server localhost:9092 \
--topic stock-topic --from-beginning
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
producer.flush() before exiting — without it, the last messages may be silently dropped.fast_info for live polling.symbol field so consumers can filter.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%.