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);

Data Summary

The following table describes the dataset properties:

PropertyValue
Start DateJanuary 2016
Asset Coverage1,800 US Equities
Data DensitySparse
ResolutionDaily
TimezoneUTC

Requesting Data

To add US Congress Trading data to your algorithm, call the AddDataadd_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);
        var 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 Getget 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 Historyhistory 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 AddUniverseadd_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 Historyhistory 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 UniverseHistoryuniverse_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 Historyhistory method in Research.

Remove Subscriptions

To remove a subscription, call the RemoveSecurityremove_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 *


class QuiverCongressDataAlgorithm(QCAlgorithm):

    def initialize(self) -> None:
        self.set_start_date(2024, 9, 1)
        self.set_end_date(2024, 12, 31)
        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(2024, 9, 1);
        SetEndDate(2024, 12, 31);
        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 *


class QuiverCongressDataAlgorithm(QCAlgorithm):

    def initialize(self) -> None:
        self.set_start_date(2024, 9, 1)
        self.set_end_date(2024, 12, 31)
        self.set_cash(100000)
        self.settings.seed_initial_prices = True
        self.universe_settings.minimum_time_in_universe = timedelta(days=7)
        # Add the Quiver Congress universe.
        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]:
        # Return all symbols from the Quiver Congress universe.
        return [d.symbol for d in alt_coarse]


class CongressAlphaModel(AlphaModel):
    _securities = []
    _insight_by_asset = {}

    def update(self, algorithm: QCAlgorithm, slice: Slice) -> List[Insight]:
        congress_data_by_asset = slice.get(QuiverCongress)
        if congress_data_by_asset:
            self._insight_by_asset.clear()
            net_quantity_by_asset = {}
            for congress_data_symbol, congress_data in congress_data_by_asset.items():
                security = algorithm.securities[congress_data_symbol.underlying]
                if security not in net_quantity_by_asset:
                    net_quantity_by_asset[security] = 0
                for point in congress_data:
                    net_quantity_by_asset[security] += (1 if point.transaction == OrderDirection.BUY else -1) * point.amount
            for security, net_quantity in net_quantity_by_asset.items():
                # Emit an up insight when Congress members are net buyers.
                if net_quantity > 0 and not security.holdings.is_long:
                    direction = InsightDirection.UP
                # Emit a down insight when Congress members are net sellers.
                elif net_quantity < 0 and not security.holdings.is_short:
                    direction = InsightDirection.DOWN
                else:
                    continue
                self._insight_by_asset[security] = Insight.price(security, timedelta(7), direction, weight=0.5)
        # To avoid error messages, emit the insights when the algorithm has a price for the asset.
        return [
                self._insight_by_asset.pop(security) 
                for security in list(self._insight_by_asset.keys())
                if security.price
        ]

    def on_securities_changed(self, algorithm: QCAlgorithm, changes: SecurityChanges) -> None:
        for security in changes.added_securities:
            self._securities.append(security)
            # Add the Quiver Congress subscription for the security.
            security.congress_data = algorithm.add_data(QuiverCongress, security, Resolution.DAILY)
            history = algorithm.history(QuiverCongress, security.congress_data, 14, Resolution.DAILY)
            algorithm.debug(f"We got {len(history)} items from our history request for {security}")
        for security in changes.removed_securities:
            if security in self._securities:
                if security in self._insight_by_asset:
                    self._insight_by_asset.pop(security)
                # Remove the Quiver Congress subscription for the security.
                algorithm.remove_security(security.congress_data)
                self._securities.remove(security)
public class QuiverCongressDataAlgorithm : QCAlgorithm
{
    public override void Initialize()
    {
        SetStartDate(2024, 9, 1);
        SetEndDate(2024, 12, 31);
        SetCash(100000);
        Settings.SeedInitialPrices = true;
        UniverseSettings.MinimumTimeInUniverse = TimeSpan.FromDays(7);
        // Add the Quiver Congress universe.
        AddUniverse<QuiverQuantCongressUniverse>(altCoarse => altCoarse.Select(d => d.Symbol));
        AddAlpha(new CongressAlphaModel());
        SetPortfolioConstruction(new InsightWeightingPortfolioConstructionModel(time => null));
        AddRiskManagement(new NullRiskManagementModel());
        SetExecution(new ImmediateExecutionModel());
    }
}

public class CongressAlphaModel : AlphaModel
{
    private readonly List<Security> _securities = [];
    private readonly Dictionary<Security, Insight> _insightByAsset = [];

    public override IEnumerable<Insight> Update(QCAlgorithm algorithm, Slice slice)
    {
        var congressDataByAsset = slice.Get<QuiverCongress>();
        if (congressDataByAsset.Count > 0)
        {
            _insightByAsset.Clear();
            // Aggregate the net Congress trade quantity for each security.
            var netQuantityByAsset = new Dictionary<Security, decimal>();
            foreach (var (congressDataSymbol, congressData) in congressDataByAsset)
            {
                var security = algorithm.Securities[congressDataSymbol.Underlying];
                if (!netQuantityByAsset.ContainsKey(security))
                {
                    netQuantityByAsset[security] = 0m;
                }
                // Weight each transaction by its reported amount.
                foreach (QuiverCongressDataPoint point in congressData)
                {
                    netQuantityByAsset[security] += (point.Transaction == OrderDirection.Buy ? 1 : -1) * (point.Amount ?? 0m);
                }
            }
            
            foreach (var (security, netQuantity) in netQuantityByAsset)
            {
                // Emit an up insight when Congress members are net buyers.
                InsightDirection direction;
                if (netQuantity > 0 && !security.Holdings.IsLong)
                {
                    direction = InsightDirection.Up;
                }
                // Emit a down insight when Congress members are net sellers.
                else if (netQuantity < 0 && !security.Holdings.IsShort)
                {
                    direction = InsightDirection.Down;
                }
                else
                {
                    continue;
                }
                _insightByAsset[security] = Insight.Price(security.Symbol, TimeSpan.FromDays(7), direction, weight: 0.5);
            }
        }
        // To avoid error messages, emit the insights when the algorithm has a price for the asset.
        return _insightByAsset.Keys
            .ToList()  // snapshot keys
            .Where(security => security.Price != 0m)
            .Select(security => {
                var insight = _insightByAsset[security];  // capture value
                _insightByAsset.Remove(security);  // remove
                return insight;
            })
            .ToList();
    }

    public override void OnSecuritiesChanged(QCAlgorithm algorithm, SecurityChanges changes)
    {
        foreach (var security in changes.AddedSecurities)
        {
            _securities.Add(security);
            // Add the Quiver Congress subscription for the security.
            var congressData = algorithm.AddData<QuiverCongress>(security.Symbol, Resolution.Daily);
            security.Set("CongressData", congressData);
            var history = algorithm.History<QuiverCongress>(congressData.Symbol, 14, Resolution.Daily);
            algorithm.Debug($"We got {history.Count()} items from our history request for {security}");
        }

        foreach (var security in changes.RemovedSecurities)
        {
            if (_securities.Contains(security))
            {
                _insightByAsset.Remove(security);
                // Remove the Quiver Congress subscription for the security.
                var congressData = security.Get<Security>("CongressData");
                algorithm.RemoveSecurity(congressData.Symbol);
                _securities.Remove(security);
            }
        }
    }
}

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 QuiverQuantCongressUniverseobjects.

QuiverCongressDataPoint Attributes

QuiverCongressDataPoint object has the following attributes:

QuiverCongress Attributes

QuiverCongress object has the following attributes:

QuiverQuantCongressUniverse Attributes

QuiverQuantCongressUniverse object has the following attributes:

You can also see our Videos. You can also get in touch with us via Discord.

Did you find this page helpful?

Contribute to the documentation: