---
title: "US Government Contracts"
description: "US Government Contracts dataset from Quiver Quantitative."
canonical: https://www.quantconnect.com/docs/v2/writing-algorithms/datasets/quiver-quantitative/us-government-contracts
markdown: https://www.quantconnect.com/docs/v2/writing-algorithms/datasets/quiver-quantitative/us-government-contracts.md
language: python
source: https://github.com/QuantConnect/Documentation/tree/master/03%20Writing%20Algorithms/14%20Datasets/23%20Quiver%20Quantitative/05%20US%20Government%20Contracts
modified: 2026-10-31
index: https://www.quantconnect.com/llms.txt
---

# US Government Contracts

[Documentation](https://www.quantconnect.com/docs/v2.md) > [Writing Algorithms](https://www.quantconnect.com/docs/v2/writing-algorithms.md) > Datasets > [Quiver Quantitative](https://www.quantconnect.com/docs/v2/writing-algorithms/datasets/quiver-quantitative.md) > US Government Contracts

> Code examples are shown in Python. Append `?lang=csharp` to this URL for the C# version of this page.

## Introduction

The US Government Contracts dataset by Quiver Quantitative tracks the transactions of government contracts with publicly traded companies. The data covers over 700 US Equities, starts in October 2019, and is delivered on a daily frequency. Quiver Quantitative creates this dataset by using the API for [USASpending.gov](https://www.usaspending.gov/), which has the official open data source of federal spending information. The rows in this dataset only show new contracts, not payments or modifications to existing contracts. The dollar amounts are based on the total dollars obligated from each contract.

This dataset depends on the [US Equity Security Master](https://www.quantconnect.com/datasets/quantconnect-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 Government Contracts dataset, including CLI commands and pricing, see the [dataset listing](https://www.quantconnect.com/datasets/quiver-quantitative-us-government-contracts).

## About the Provider

[Quiver Quantitative](https://www.quiverquant.com/) 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 Government Contracts dataset:

```python
self.aapl = self.add_equity("AAPL", Resolution.DAILY).symbol
self.dataset_symbol = self.add_data(QuiverGovernmentContract, self.aapl).symbol

self._universe = self.add_universe(QuiverGovernmentContractUniverse, self.universe_selection)
```

## Data Summary

The following table describes the dataset properties:

| Property | Value |
| --- | --- |
| Start Date | October 15, 2019 |
| Asset Coverage | 748 US Equities |
| Data Density | Sparse |
| Resolution | Daily |
| Timezone | UTC |

## Requesting Data

To add US Government Contracts data to your algorithm, call the `add_data` method. Save a reference to the dataset `Symbol` so you can access the data later in your algorithm.

```python
class QuiverGovernmentContractDataAlgorithm(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(QuiverGovernmentContract, symbol).symbol
```

## Accessing Data

To get the current US Government Contract data, index the current [`Slice`](https://www.quantconnect.com/docs/v2/writing-algorithms/key-concepts/time-modeling/timeslices.md) 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.

```python
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} amount at {slice.time}: {data_point.amount}")
```

To iterate through all of the dataset objects in the current `Slice`, call the `get` method.

```python
def on_data(self, slice: Slice) -> None:
    for dataset_symbol, data_points in slice.get(QuiverGovernmentContract).items():
        for data_point in data_points:
            self.log(f"{dataset_symbol} amount at {slice.time}: {data_point.amount}")
```

## Historical Data

To get historical US Government Contracts data, call the `history` method with the dataset `Symbol`. If there is no data in the period you request, the history result is empty.

```python
# DataFrame
history_df = self.history(self.dataset_symbol, 100, Resolution.DAILY)

# Dataset objects
history_bars = self.history[QuiverGovernmentContract](self.dataset_symbol, 100, Resolution.DAILY)
```

For more information about historical data, see [History Requests](https://www.quantconnect.com/docs/v2/writing-algorithms/historical-data/history-requests.md).

## Universe Selection

To select a dynamic universe of US Equities based on US Government Contract data, call the `add_universe` method with the `QuiverGovernmentContractUniverse` class and a selection function.

```python
def initialize(self):
    self._universe = self.add_universe(QuiverGovernmentContractUniverse, self.universe_selection)

def universe_selection(self, alt_coarse: List[QuiverGovernmentContractUniverse]) -> List[Symbol]:
    gov_contract_data_by_symbol = {}

    for datum in alt_coarse:
        symbol = datum.symbol

        if symbol not in gov_contract_data_by_symbol:
            gov_contract_data_by_symbol[symbol] = []
        gov_contract_data_by_symbol[symbol].append(datum)

    return [symbol for symbol, d in gov_contract_data_by_symbol.items()
            if len(d) >= 3 and sum([x.amount for x in d]) > 50000]
```

## 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` method with the `Universe` object and the lookback period. If there is no data in the period you request, the history result is empty.

```python
# DataFrame example where the columns are the QuiverGovernmentContractUniverse attributes:
history_df = self.history(self._universe, 30, Resolution.DAILY, flatten=True)

# Series example where the values are lists of QuiverGovernmentContractUniverse objects:
universe_history = self.history(self._universe, 30, Resolution.DAILY)
for (_, time), contracts in universe_history.items():
    for contract in contracts:
        self.log(f"{contract.symbol} amount at {contract.end_time}: {contract.amount}")
```

### Historical Universe Data in Research

To get historical universe data in research, call the `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.

```python
# DataFrame example where the columns are the QuiverGovernmentContractUniverse attributes:
history_df = qb.universe_history(universe, qb.time-timedelta(30), qb.time, flatten=True)

# Series example where the values are lists of QuiverGovernmentContractUniverse objects:
universe_history = qb.universe_history(universe, qb.time-timedelta(30), qb.time)
for (_, time), contracts in universe_history.items():
    for contract in contracts:
        print(f"{contract.symbol} amount at {contract.end_time}: {contract.amount}")
```

You can call the `history` method in Research.

## Remove Subscriptions

To remove a subscription, call the `remove_security` method.

```python
self.remove_security(self.dataset_symbol)
```

If you subscribe to US Government Contracts 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](https://www.quantconnect.com/docs/v2/writing-algorithms/algorithm-framework/alpha/key-concepts.md#05-Track-Security-Changes).

## Example Applications

The Quiver Quantitative US Government Contracts dataset enables you to create strategies using the latest information on government contracts activity. Examples include the following strategies:

- Buying securities that have received the most new government contract awards over the last month
- Trading securities that have had the biggest change in government contracts awards over the last year

### Classic Algorithm Example

The following example algorithm buys Apple stock when they receive a new government contract worth over $50K. If they receive a new contract worth under $10K, the algorithm short sells Apple.

```python
from AlgorithmImports import *

class QuiverGovernmentContractAlgorithm(QCAlgorithm):

    def initialize(self) -> None:
        self.set_start_date(2024, 9, 1)
        self.set_end_date(2024, 12, 31)
        self.aapl = self.add_equity("AAPL", Resolution.DAILY).symbol
        # Subscribe to government contract data for AAPL to generate trade signal
        self.dataset_symbol = self.add_data(QuiverGovernmentContract, self.aapl).symbol

        # history request
        history = self.history(self.dataset_symbol, 10, Resolution.DAILY)
        self.debug(f"We got {len(history)} items from historical data request of {self.dataset_symbol}.")

    def on_data(self, slice: Slice) -> None:
        # Trade only base on government contract data
        for gov_contracts in slice.get(QuiverGovernmentContract).values():
            # Buy if over 50000 government contract amount, suggesting a large income
            if any([gov_contract.amount > 50000 for gov_contract in gov_contracts]):
                self.set_holdings(self.aapl, 1)
            # Sell if below 10000 government contract amount, suggesting a smaller than usual income
            elif any([gov_contract.amount < 10000 for gov_contract in gov_contracts]):
                self.set_holdings(self.aapl, -1)
```

### Framework Algorithm Example

The following example algorithm creates a dynamic universe of US Equities that have just received a government contract worth at least $5K. Each day, it then forms an equal-weighted dollar-neutral portfolio with the 10 companies that received the largest contracts and the 10 companies that received the smallest contracts.

```python
from AlgorithmImports import *

class QuiverGovernmentContractDataAlgorithm(QCAlgorithm):

    def initialize(self) -> None:
        self.set_start_date(2024, 9, 1)
        self.set_end_date(2024, 12, 31)
        self.set_cash(100000)
        # Seed the price of each asset with its last known price to avoid trading errors.
        self.settings.seed_initial_prices = True
        # Filter universe using government contract data
        self.add_universe(QuiverGovernmentContractUniverse, self.universe_selection)

        # Custom alpha model that emit insights based on updated government contract data
        self.add_alpha(QuiverGovernmentContractAlphaModel())

        # Invest equally to evenly dissipate the capital concentration risk
        self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())

        self.set_execution(ImmediateExecutionModel())

    def universe_selection(self, data: List[QuiverGovernmentContractUniverse]) -> List[Symbol]:
        gov_contract_data_by_symbol = {}

        for datum in data:
            symbol = datum.symbol

            if symbol not in gov_contract_data_by_symbol:
                gov_contract_data_by_symbol[symbol] = []
            gov_contract_data_by_symbol[symbol].append(datum)

        # Only select the stocks with over 5000 government contracts, which is considered material information
        return [symbol for symbol, d in gov_contract_data_by_symbol.items()
                if sum([x.amount for x in d]) > 5000]

class QuiverGovernmentContractAlphaModel(AlphaModel):

    def __init__(self) -> None:
        # A variable to control the rebalancing time
        self.last_time = datetime.min
        # To hold the government contract dataset symbol for managing subscription
        self.dataset_symbol_by_symbol = {}

    def update(self, algorithm: QCAlgorithm, slice: Slice) -> List[Insight]:
        if self.last_time > algorithm.time: return []

        # Trade signal only based on government contract data
        data_points = slice.get(QuiverGovernmentContract)

        if not data_points: return []

        gov_contracts = {}
        # To aggregate all data per symbol for analysis
        for data_point in data_points:
            if not algorithm.securities[data_point.key.underlying].price:
                continue
            if data_point.key not in gov_contracts:
                gov_contracts[data_point.key] = 0

            for gov_contract in data_point.value:
                gov_contracts[data_point.key] += gov_contract.amount

        # Long the top 10 highest government contract amount, predicting a higher expected income and return
        # Short the lowest 10 government contract amount, predicting a lower expected income and return
        sorted_by_gov_contracts = sorted(gov_contracts.items(), key=lambda x: x[1])
        long_symbols = [x[0].underlying for x in sorted_by_gov_contracts[-10:]]
        short_symbols = [x[0].underlying for x in sorted_by_gov_contracts[:10]]

        insights = []
        for symbol in long_symbols:
            insights.append(Insight.price(symbol, Expiry.END_OF_DAY, InsightDirection.UP))
        for symbol in short_symbols:
            insights.append(Insight.price(symbol, Expiry.END_OF_DAY, InsightDirection.DOWN))

        self.last_time = Expiry.END_OF_DAY(algorithm.time)

        return insights

    def on_securities_changed(self, algorithm: QCAlgorithm, changes: SecurityChanges) -> None:
        for security in changes.added_securities:
            # Requesting government contract data for trade signal generation
            symbol = security.symbol
            dataset_symbol = algorithm.add_data(QuiverGovernmentContract, symbol).symbol
            self.dataset_symbol_by_symbol[symbol] = dataset_symbol
            # Historical Data
            history = algorithm.history(dataset_symbol, 10, Resolution.DAILY)

        for security in changes.removed_securities:
            dataset_symbol = self.dataset_symbol_by_symbol.pop(security.symbol, None)
            if dataset_symbol:
                # Remove government contract data subscription to release computation resources
                algorithm.remove_security(dataset_symbol)
```

### Research Example

The following example lists all US Equities with Government contracts in the past year.

```python
qb = QuantBook()

# Requesting Data
aapl = qb.add_equity("AAPL", Resolution.DAILY).symbol
symbol = qb.add_data(QuiverGovernmentContract, aapl).symbol

# Historical data
history = qb.history(QuiverGovernmentContract, symbol, 360, Resolution.DAILY)
for (symbol, time), contracts in history.items():
    for contract in contracts:
        print(f"{contract.symbol} amount at {contract.end_time}: {contract.amount}")

# Add Universe Selection
def universe_selection(alt_coarse: List[QuiverGovernmentContractUniverse]) -> List[Symbol]:
    return [d.symbol for d in alt_coarse]

universe = qb.add_universe(QuiverGovernmentContractUniverse, universe_selection)

# Historical Universe data
universe_history = qb.universe_history(universe, qb.time-timedelta(360), qb.time)
for (_, time), contracts in universe_history.items():
    for contract in contracts:
        print(f"{contract.symbol} amount at {contract.end_time}: {contract.amount}")
```

## Data Point Attributes

The US Government Contracts dataset provides `QuiverGovernmentContract` and `QuiverGovernmentContractUniverse` objects.

### QuiverGovernmentContract

`QuiverGovernmentContract` objects have the following attributes:

*Members of `QuantConnect.DataSource.QuiverGovernmentContract` (JSON): https://www.quantconnect.com/services/inspector?type=T:QuantConnect.DataSource.QuiverGovernmentContract&language=python*

### QuiverGovernmentContractUniverse

`QuiverGovernmentContractUniverse` objects have the following attributes:

*Members of `QuantConnect.DataSource.QuiverGovernmentContractUniverse` (JSON): https://www.quantconnect.com/services/inspector?type=T:QuantConnect.DataSource.QuiverGovernmentContractUniverse&language=python*
