Quiver Quantitative
US Congress Trading
Introduction
The US Congress Trading dataset by Quiver Quantitative tracks US Equity trades made by members of Congress in the Senate and the House of Representatives. The data covers 1,800 US Equities, starts in January 2016, and is delivered on a daily frequency. This dataset is created by scraping SEC reports.
This dataset depends on the US Equity Security Master dataset because the US Equity Security Master dataset contains information on splits, dividends, and symbol changes.
For more information about the US Congress Trading dataset, including CLI commands and pricing, see the dataset listing.
About the Provider
Quiver Quantitative was founded by two college students in February 2020 with the goal of bridging the information gap between Wall Street and non-professional investors. Quiver allows retail investors to tap into the power of big data and have access to actionable, easy to interpret data that hasn’t already been dissected by Wall Street.
Getting Started
The following snippet demonstrates how to request data from the US Congress Trading dataset:
self.aapl = self.add_equity("AAPL", Resolution.DAILY).symbol self.dataset_symbol = self.add_data(QuiverCongress, self.aapl).symbol self._universe = self.add_universe(QuiverQuantCongressUniverse, self.universe_selection)
_symbol = AddEquity("AAPL", Resolution.Daily).Symbol; _datasetSymbol = AddData<QuiverCongress>(_symbol).Symbol; _universe = AddUniverse<QuiverQuantCongresssUniverse>(UniverseSelection);
Requesting Data
To add US Congress Trading data to your algorithm, call the AddData
add_data
method. Save a reference to the dataset Symbol
so you can access the data later in your algorithm.
class QuiverCongressDataAlgorithm(QCAlgorithm): def initialize(self) -> None: self.set_start_date(2019, 1, 1) self.set_end_date(2020, 6, 1) self.set_cash(100000) symbol = self.add_equity("AAPL", Resolution.DAILY).symbol self.dataset_symbol = self.add_data(QuiverCongress, symbol).symbol
public class QuiverCongressDataAlgorithm : QCAlgorithm { private Symbol _datasetSymbol; public override void Initialize() { SetStartDate(2019, 1, 1); SetEndDate(2020, 6, 1); SetCash(100000); symbol = AddEquity("AAPL", Resolution.Daily).Symbol; _datasetSymbol = AddData<QuiverCongress>(symbol).Symbol; } }
Accessing Data
To get the current US Congress Trading data, index the current Slice
with the dataset Symbol
. Slice objects deliver unique events to your algorithm as they happen, but the Slice
may not contain data for your dataset at every time step. To avoid issues, check if the Slice
contains the data you want before you index it.
def on_data(self, slice: Slice) -> None: if slice.contains_key(self.dataset_symbol): data_points = slice[self.dataset_symbol] for data_point in data_points: self.log(f"{self.dataset_symbol} transaction amount at {slice.time}: {data_point.amount}")
public override void OnData(Slice slice) { if (slice.ContainsKey(_datasetSymbol)) { var dataPoints = slice[_datasetSymbol]; foreach (var dataPoint in dataPoints) { Log($"{_datasetSymbol} transaction amount at {slice.Time}: {dataPoint.Amount}"); } } }
To iterate through all of the dataset objects in the current Slice
, call the Get
get
method.
def on_data(self, slice: Slice) -> None: for dataset_symbol, data_point in slice.get(QuiverCongress).items(): self.log(f"{dataset_symbol} transaction amount at {slice.time}: {data_point.amount}")
public override void OnData(Slice slice) { foreach (var kvp in slice.Get<QuiverCongress>()) { var datasetSymbol = kvp.Key; var dataPoint = kvp.Value; Log($"{datasetSymbol} transaction amount at {slice.Time}: {dataPoint.Amount}"); } }
Historical Data
To get historical US Congress Trading data, call the History
history
method with the dataset Symbol
. If there is no data in the period you request, the history result is empty.
# DataFrame history_df = self.history(self.dataset_symbol, 100, Resolution.DAILY) # Dataset objects history_bars = self.history[QuiverCongress](self.dataset_symbol, 100, Resolution.DAILY)
var history = History<QuiverCongress>(_datasetSymbol, 100, Resolution.Daily);
For more information about historical data, see History Requests.
Universe Selection
To select a dynamic universe of US Equities based on US Congress Trading data, call the AddUniverse
add_universe
method with the QuiverQuantCongressUniverse
class and a selection function.
def initialize(self) -> None: self._universe = self.add_universe(QuiverQuantCongressUniverse, self.universe_selection) def universe_selection(self, alt_coarse: List[QuiverQuantCongresssUniverse]) -> List[Symbol]: return [d.symbol for d in alt_coarse \ if d.amount > 200000 and d.transaction == OrderDirection.BUY]
private Universe _universe; public override void Initialize() { _universe = AddUniverse<QuiverQuantCongresssUniverse>(altCoarse => { return from d in altCoarse.OfType<QuiverCongressDataPoint>() where d.Amount > 200000 && d.Transaction == OrderDirection.Buy select d.Symbol; }) };
For more information about dynamic universes, see Universes.
Universe History
You can get historical universe data in an algorithm and in the Research Environment.
Historical Universe Data in Algorithms
To get historical universe data in an algorithm, call the History
history
method with the Universe
object and the lookback period. If there is no data in the period you request, the history result is empty.
var universeHistory = History(_universe, 30, Resolution.Daily); foreach (var trade in universeHistory.SelectMany(x => x).OfType<QuiverCongressDataPoint>()) { Log($"{trade.Symbol} amount at {trade.EndTime}: {trade.Amount} {trade.Representative}"); }
# DataFrame example where the columns are the QuiverQuantCongressUniverse attributes: history_df = self.history(self._universe, 30, Resolution.DAILY, flatten=True) # Series example where the values are lists of QuiverQuantCongressUniverse objects: history = self.history(self._universe, 30, Resolution.DAILY) for (univere_symbol, time), trades in universe_history.items(): for trade in trades: self.log(f"{trade.symbol} amount at {trade.end_time}: {trade.amount} {trade.representative}") {trade.Representative}")
Historical Universe Data in Research
To get historical universe data in research, call the UniverseHistory
universe_history
method with the Universe
object, a start date, and an end date. This method returns the filtered universe. If there is no data in the period you request, the history result is empty.
var universeHistory = qb.UniverseHistory(universe, qb.Time.AddDays(-30), qb.Time); foreach (var trade in universeHistory.SelectMany(x => x).OfType<QuiverCongressDataPoint>()) { Console.WriteLine($"{trade.Symbol} amount at {trade.EndTime}: {trade.Amount} {trade.Representative}"); }
# DataFrame example where the columns are the QuiverQuantCongressUniverse attributes: history_df = qb.universe_history(universe, qb.time-timedelta(30), qb.time, flatten=True) # Series example where the values are lists of QuiverQuantCongressUniverse objects: universe_history = qb.universe_history(universe, qb.time-timedelta(30), qb.time) for (univere_symbol, time), trades in universe_history.items(): for trade in trades: print(f"{trade.symbol} amount at {trade.end_time}: {trade.amount} {trade.representative}")
You can call the History
history
method in Research.
Remove Subscriptions
To remove a subscription, call the RemoveSecurity
remove_security
method.
self.remove_security(self.dataset_symbol)
RemoveSecurity(_datasetSymbol);
If you subscribe to US Congress Trading data for assets in a dynamic universe, remove the dataset subscription when the asset leaves your universe. To view a common design pattern, see Track Security Changes.
Example Applications
The US Congress Trading dataset enables you to take immediate action on trades made by informed Members of Congress. Examples include the following strategies:
- Following the trades of specific representatives on the premise that the representatives are more informed
- Assigning a long/short-bias to securities on a daily frequency based on how Members of Congress are trading them
Classic Algorithm Example
The following example algorithm follows the net bias of the trades made by Members of Congress each day. When Members of Congress are net buyers, the algorithm buys. When they are net sellers, the algorithm short sells.
from AlgorithmImports import * from QuantConnect.DataSource import * class QuiverCongressDataAlgorithm(QCAlgorithm): def initialize(self) -> None: self.set_start_date(2019, 1, 1) self.set_end_date(2020, 6, 1) self.set_cash(100000) # Requesting data per underlying data to subscribe to updated congress members' trade information aapl = self.add_equity("AAPL", Resolution.DAILY).symbol quiver_congress_symbol = self.add_data(QuiverCongress, aapl).symbol # Historical data history = self.history(QuiverCongress, quiver_congress_symbol, 60, Resolution.DAILY) self.debug(f"We got {len(history)} items from our history request"); def on_data(self, slice: Slice) -> None: congress_by_symbol = slice.Get(QuiverCongress) # Determine net direction of Congress trades for each security to estimate the sentiment direction due to political factor net_quantity_by_symbol = {} for symbol, points in congress_by_symbol.items(): symbol = symbol.underlying if symbol not in net_quantity_by_symbol: net_quantity_by_symbol[symbol] = 0 # Voting weight is by order size for point in points: net_quantity_by_symbol[symbol] += (1 if point.transaction == OrderDirection.BUY else -1) * point.amount for symbol, net_quantity in net_quantity_by_symbol.items(): if net_quantity == 0: self.liquidate(symbol) continue # Buy when Congress members have bought, short otherwise self.set_holdings(symbol, 1 if net_quantity > 0 else -1)
public class QuiverCongressDataAlgorithm : QCAlgorithm { public override void Initialize() { SetStartDate(2019, 1, 1); SetEndDate(2020, 6, 1); SetCash(100000); // Requesting data per underlying data to subscribe to updated congress members' trade information var aapl = AddEquity("AAPL", Resolution.Daily).Symbol; var quiverCongressSymbol = AddData<QuiverCongress>(aapl).Symbol; // Historical data var history = History<QuiverCongress>(quiverCongressSymbol, 60, Resolution.Daily); Debug($"We got {history.Count()} items from our history request"); } public override void OnData(Slice slice) { var congressBySymbol = slice.Get<QuiverCongress>(); // Determine net direction of Congress trades for each security to estimate the sentiment direction due to political factor var netQuantityBySymbol = new Dictionary<Symbol, decimal>(); foreach (var (s, points) in congressBySymbol) { var symbol = s.Underlying; if (!netQuantityBySymbol.ContainsKey(symbol)) { netQuantityBySymbol[symbol] = 0m; } // Voting weight is by order size foreach(QuiverCongressDataPoint point in points) { netQuantityBySymbol[symbol] += (point.Transaction == OrderDirection.Buy ? 1 : -1) * (point.Amount ?? 0m); } } foreach (var (symbol, netQuantity) in netQuantityBySymbol) { if (netQuantity == 0) { Liquidate(symbol); continue; } // Buy when Congress members have bought, short otherwise SetHoldings(symbol, netQuantity > 0 ? 1 : -1); } } }
Framework Algorithm Example
The following example algorithm follows the net bias of the trades made by Members of Congress each day. When Members of Congress are net buyers, the algorithm buys. When they are net sellers, the algorithm short sells.
from AlgorithmImports import * from QuantConnect.DataSource import * class QuiverCongressDataAlgorithm(QCAlgorithm): def initialize(self) -> None: self.set_start_date(2019, 1, 1) self.set_end_date(2020, 6, 1) self.set_cash(100000) self.universe_settings.resolution = Resolution.DAILY # Filter according to QuiverCongress data self.add_universe(QuiverQuantCongressUniverse, "QuiverQuantCongresssUniverse", Resolution.DAILY, self.universe_selection) self.add_alpha(CongressAlphaModel()) self.set_portfolio_construction(InsightWeightingPortfolioConstructionModel(lambda time: None)) self.add_risk_management(NullRiskManagementModel()) self.set_execution(ImmediateExecutionModel()) def universe_selection(self, alt_coarse: List[QuiverQuantCongressUniverse]) -> List[Symbol]: # Only include the ones with large size buy, since they are estimated to be materially confident to go up return [d.symbol for d in alt_coarse if d.amount > 200000 and d.transaction == OrderDirection.BUY] class CongressAlphaModel(AlphaModel): symbol_data_by_symbol = {} def update(self, algorithm: QCAlgorithm, slice: Slice) -> List[Insight]: insights = [] congress_by_symbol = slice.Get(QuiverCongress) # Determine net direction of Congress trades for each security to estimate the sentiment direction due to political factor net_quantity_by_symbol = {} for symbol, points in congress_by_symbol.items(): symbol = symbol.underlying if symbol not in net_quantity_by_symbol: net_quantity_by_symbol[symbol] = 0 # Voting weight is by order size for point in points: net_quantity_by_symbol[symbol] += (1 if point.transaction == OrderDirection.BUY else -1) * point.amount for symbol, net_quantity in net_quantity_by_symbol.items(): # Buy when Congress members have bought, as they may have advance information to be confident to the return direction if net_quantity > 0 and not algorithm.portfolio[symbol].is_long: insights += [Insight.price(symbol, timedelta(7), InsightDirection.UP, weight=0.5)] # Short sell when Congress members have sold elif net_quantity < 0 and not algorithm.portfolio[symbol].is_short: insights += [Insight.price(symbol, timedelta(7), InsightDirection.DOWN, weight=0.5)] return insights def on_securities_changed(self, algorithm: QCAlgorithm, changes: SecurityChanges) -> None: for security in changes.added_securities: symbol = security.symbol self.symbol_data_by_symbol[symbol] = SymbolData(algorithm, symbol) for security in changes.removed_securities: symbol_data = self.symbol_data_by_symbol.pop(security.symbol, None) if symbol_data: symbol_data.dispose() class SymbolData: def __init__(self, algorithm: QCAlgorithm, symbol: Symbol): self.algorithm = algorithm # Requesting data per underlying data to subscribe to updated congress members' trade information self.quiver_congress_symbol = algorithm.add_data(QuiverCongress, symbol).symbol # Historical data history = algorithm.history(self.quiver_congress_symbol, 14, Resolution.DAILY) algorithm.debug(f"We got {len(history)} items from our history request for {symbol} Quiver Congress data") def dispose(self) -> None: # Unsubscribe from Quiver Congress feed for this security to release computational resources self.algorithm.remove_security(self.quiver_congress_symbol)
public class QuiverCongressDataAlgorithm : QCAlgorithm { public override void Initialize() { SetStartDate(2019, 1, 1); SetEndDate(2020, 6, 1); SetCash(100000); // Filter according to QuiverCongress data AddUniverse<QuiverQuantCongressUniverse>("QuiverQuantCongresssUniverse", Resolution.Daily, altCoarse => { // Only include the ones with large size buy, since they are estimated to be materially confident to go up return from d in altCoarse where d.Amount > 200000 && d.Transaction == OrderDirection.Buy select d.Symbol; }); AddAlpha(new CongressAlphaModel()); SetPortfolioConstruction(new InsightWeightingPortfolioConstructionModel(time => None)); AddRiskManagement(new NullRiskManagementModel()); SetExecution(new ImmediateExecutionModel()); } } public class CongressAlphaModel : AlphaModel { private Dictionary<Symbol, SymbolData> _symbolDataBySymbol = new (); public override IEnumerable<Insight> Update(QCAlgorithm algorithm, Slice slice) { var congressBySymbol = slice.Get<QuiverCongress>(); // Determine net direction of Congress trades for each security to estimate the sentiment direction due to political factor var netQuantityBySymbol = new Dictionary<Symbol, decimal>(); foreach (var (s, points) in congressBySymbol) { var symbol = s.Underlying; if (!netQuantityBySymbol.ContainsKey(symbol)) { netQuantityBySymbol[symbol] = 0m; } // Voting weight is by order size foreach(QuiverCongressDataPoint point in points) { netQuantityBySymbol[symbol] += (point.Transaction == OrderDirection.Buy ? 1 : -1) * (point.Amount ?? 0m); } } foreach (var (symbol, netQuantity) in netQuantityBySymbol) { // Buy when Congress members have bought, as they may have advance information to be confident to the return direction if (netQuantity > 0 && !algorithm.Portfolio[symbol].IsLong) { yield return Insight.Price(symbol, TimeSpan.FromDays(7), InsightDirection.Up, weight: 0.5); } // Short sell when Congress members have sold else if (netQuantity < 0 && !algorithm.Portfolio[symbol].IsShort) { yield return Insight.Price(symbol, TimeSpan.FromDays(7), InsightDirection.Down, weight: 0.5); } } } public override void OnSecuritiesChanged(QCAlgorithm algorithm, SecurityChanges changes) { foreach (var security in changes.AddedSecurities) { var symbol = security.Symbol; _symbolDataBySymbol.Add(symbol, new SymbolData(algorithm, symbol)); } foreach (var security in changes.RemovedSecurities) { var symbol = security.Symbol; if (_symbolDataBySymbol.ContainsKey(symbol)) { _symbolDataBySymbol[symbol].dispose(); _symbolDataBySymbol.Remove(symbol); } } } } public class SymbolData { private Symbol _quiverCongressSymbol; private QCAlgorithm _algorithm; public SymbolData(QCAlgorithm algorithm, Symbol symbol) { _algorithm = algorithm; // Requesting data per underlying data to subscribe to updated congress members' trade information _quiverCongressSymbol = algorithm.AddData<QuiverCongress>(symbol).Symbol; // Historical data var history = algorithm.History<QuiverCongress>(_quiverCongressSymbol, 60, Resolution.Daily); algorithm.Debug($"We got {history.Count()} items from our history request for {symbol} Quiver Congress data"); } public void dispose() { // Unsubscribe from Quiver Congress feed for this security to release computational resources _algorithm.RemoveSecurity(_quiverCongressSymbol); } }
Research Example
The following example lists trades made by Members of Congress daily as buyers.
#r "../QuantConnect.DataSource.QuiverQuantCongressTrading.dll" using QuantConnect.DataSource; var qb = new QuantBook(); // Add QuiverCongress var aapl = qb.AddEquity("AAPL", Resolution.Daily).Symbol; var quiverCongressSymbol = qb.AddData<QuiverCongress>(aapl).Symbol; // Historical data var history = qb.History<QuiverCongress>(quiverCongressSymbol, 60, Resolution.Daily); foreach (var trade in history.SelectMany(x => x).OfType<QuiverCongressDataPoint>()) { Console.WriteLine($"{trade.EndTime} {trade.Symbol.Value} {trade.Representative} {trade.Amount}"); } // Add Universe Selection IEnumerable<Symbol> UniverseSelection(IEnumerable>BaseData> altCoarse) { return from d in altCoarse.OfType<QuiverCongressDataPoint>() where d.Transaction == OrderDirection.Buy select d.Symbol; } var universe = qb.AddUniverse>QuiverQuantCongressUniverse>(UniverseSelection); // Historical Universe data var universeHistory = qb.UniverseHistory(universe, qb.Time.AddDays(-60), qb.Time); foreach (var trade in universeHistory.SelectMany(x => x).OfType<QuiverCongressDataPoint>()) { Console.WriteLine($"{trade.EndTime} {trade.Symbol.Value} {trade.Representative} {trade.Amount}"); }
qb = QuantBook() # Add QuiverCongress aapl = qb.add_equity("AAPL", Resolution.DAILY).symbol quiver_congress_symbol = qb.add_data(QuiverCongress, aapl).symbol # Historical data history = qb.history(QuiverCongress, quiver_congress_symbol, 60, Resolution.DAILY) for (symbol, time), trades in history.items(): for trade in trades: print(f'{time} {trade.symbol.value} {trade.representative} {trade.amount}') # Add Universe Selection def universe_selection(alt_coarse: List[QuiverQuantCongressUniverse]) -> List[Symbol]: return [d.symbol for d in alt_coarse if d.transaction == OrderDirection.BUY] universe = qb.add_universe(QuiverQuantCongressUniverse, universe_selection) # Historical Universe data history = qb.universe_history(universe, qb.time-timedelta(60), qb.time) for (univere_symbol, time), trades in history.items(): for trade in trades: print(f'{time} {trade.symbol.value} {trade.representative} {trade.amount}')
Data Point Attributes
The US Congress Trading dataset provides QuiverCongressDataPoint
, QuiverCongress
, and QuiverQuantCongressUniverse
objects.
QuiverCongressDataPoint Attributes
QuiverCongressDataPoint
object has the following attributes:
QuiverCongress Attributes
QuiverCongress
object has the following attributes:
QuiverQuantCongressUniverse Attributes
QuiverQuantCongressUniverse
object has the following attributes: