如何用Zipline从quantopian-quandl数据bundle获取现金分红及函数调用疑问
Hey there! Let's tackle your two questions about accessing cash dividends from the quantopian-quandl bundle in Zipline step by step.
The quantopian-quandl bundle stores dividend data alongside pricing and metadata, and there are two main practical ways to access it:
Option 1: Use Zipline's Built-in get_dividends Function (For Backtests)
Zipline provides a dedicated get_dividends API that lets you fetch dividend records directly within your backtest script—this is the most straightforward method for strategy development.
Here's an example of how to pull historical dividends for a specific stock in your initialize function:
from zipline.api import get_dividends, symbols def initialize(context): # Target a specific stock (e.g., Apple) context.stock = symbols('AAPL') # Fetch dividends between a custom date range dividend_history = get_dividends( context.stock, start_date='2010-01-01', end_date='2020-12-31' ) # Print key dividend details (returns a pandas DataFrame) if not dividend_history.empty: print("Apple's Dividend History:") print(dividend_history[['ex_date', 'amount', 'payment_date']])
The returned DataFrame includes critical fields:
ex_date: The ex-dividend date (when the stock starts trading without the dividend)amount: Cash dividend amount per sharepayment_date: When the dividend is credited to your accountrecord_date: The date you need to hold the stock to qualify for the dividend
Option 2: Directly Query the Bundle's SQLite Database (For Offline Analysis)
If you want to inspect dividend data outside of a backtest, the quantopian-quandl bundle stores its data in a SQLite database. You can connect to it using pandas or SQLAlchemy:
import pandas as pd from sqlalchemy import create_engine from zipline.api import symbols # Locate your bundle's DB path (default: ~/.zipline/data/quantopian-quandl/[timestamp]/db.sqlite) bundle_db_path = "/home/your-username/.zipline/data/quantopian-quandl/2024-05-20/db.sqlite" engine = create_engine(f'sqlite:///{bundle_db_path}') # Read the full dividends table all_dividends = pd.read_sql_table('dividends', engine) # Filter for a specific stock using its SID (Security ID) aapl_sid = symbols('AAPL').sid aapl_dividends = all_dividends[all_dividends['sid'] == aapl_sid] print(aapl_dividends[['ex_date', 'amount']])
handle_data(context, data) Function? Absolutely! You can use get_dividends directly within handle_data to check for dividends on the current backtest date, or fetch recent records to inform your trading logic.
Here's an example that checks if the target stock has an ex-dividend date on the current day:
def handle_data(context, data): stock = context.stock current_date = data.current_dt.date() # Fetch dividends for the current trading day today_dividends = get_dividends( stock, start_date=current_date, end_date=current_date ) if not today_dividends.empty: dividend_amount = today_dividends['amount'].iloc[0] print(f"🚨 {stock.symbol} has an ex-dividend today! Amount per share: ${dividend_amount}") # Add custom logic here (e.g., track dividend income or adjust positions) context.dividend_income += dividend_amount * context.portfolio.positions[stock].amount
A few key notes:
handle_dataruns daily during the backtest, so this check executes once per trading day.- Zipline automatically credits dividend cash to your strategy's account balance by default, but this method lets you add custom behavior like reinvesting dividends or logging income.
内容的提问来源于stack exchange,提问作者Vincent Roye




