Quiver Quantitative
US Government Contracts
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, 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 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.
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 Government Contracts dataset:
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)
_symbol = AddEquity("AAPL", Resolution.Daily).Symbol; _datasetSymbol = AddData<QuiverGovernmentContract>(_symbol).Symbol; _universe = AddUniverse<QuiverGovernmentContractUniverse>(UniverseSelection);
Requesting Data
To add US Government Contracts 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 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
namespace QuantConnect.Algorithm.CSharp.AltData { public class QuiverGovernmentContractDataAlgorithm : 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<QuiverGovernmentContract>(symbol).Symbol; } } }
Accessing Data
To get the current US Government Contract 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} 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} 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_points in slice.get(QuiverGovernmentContract).items(): for data_point in data_points: self.log(f"{dataset_symbol} amount at {slice.time}: {data_point.amount}")
public override void OnData(Slice slice) { foreach (var kvp in slice.Get<QuiverGovernmentContract>()) { var datasetSymbol = kvp.Key; var dataPoints = kvp.Value; foreach(var dataPoint in dataPoints) { Log($"{datasetSymbol} amount at {slice.Time}: {dataPoint.Amount}"); } } }
Historical Data
To get historical US Government Contracts 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[QuiverGovernmentContract](self.dataset_symbol, 100, Resolution.DAILY)
var history = History<QuiverGovernmentContract>(_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 Government Contract data, call the AddUniverse
add_universe
method with the QuiverGovernmentContractUniverse
class and a selection function.
def initialize(self): self._universe = self.add_universe(QuiverGovernmentContractUniverse, self.universe_selection) def universe_selection(self, alt_coase: 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]
private Universe _universe; public override void Initialize() { _universe = AddUniverse<QuiverGovernmentContractUniverse>(altCoarse => { var govContractDataBySymbol = new Dictionary<Symbol, List<QuiverGovernmentContractUniverse>>(); foreach (var datum in altCoarse.OfType<QuiverGovernmentContractUniverse>()) { var symbol = datum.Symbol; if (!govContractDataBySymbol.ContainsKey(symbol)) { govContractDataBySymbol.Add(symbol, new List<QuiverGovernmentContractUniverse>()); } govContractDataBySymbol[symbol].Add(datum); } return from kvp in govContractDataBySymbol where kvp.Value.Count >= 3 && kvp.Value.Sum(x => x.Amount) > 50000m select kvp.Key; }); }
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 contracts in universeHistory) { foreach (QuiverGovernmentContractUniverse contract in contracts) { Log($"{contract.Symbol} amount at {contract.EndTime}: {contract.Amount}"); } }
# 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 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 contracts in universeHistory) { foreach (QuiverGovernmentContractUniverse contract in contracts) { Console.WriteLine($"{contract.Symbol} amount at {contract.EndTime}: {contract.Amount}"); } }
# 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
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 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.
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.
from AlgorithmImports import * from QuantConnect.DataSource import * class QuiverGovernmentContractAlgorithm(QCAlgorithm): def initialize(self) -> None: self.set_start_date(2020, 10, 7) #Set Start Date self.set_end_date(2021, 10, 11) #Set End Date 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)
using QuantConnect.DataSource; namespace QuantConnect { public class QuiverGovernmentContractAlgorithm : QCAlgorithm { private Symbol _symbol, _datasetSymbol; public override void Initialize() { SetStartDate(2020, 10, 7); //Set Start Date SetEndDate(2021, 10, 11); //Set End Date _symbol = AddEquity("AAPL").Symbol; // Subscribe to government contract data for AAPL to generate trade signal _datasetSymbol = AddData<QuiverGovernmentContract>(_symbol).Symbol; // history request var history = History<QuiverGovernmentContract>(new[] {_datasetSymbol}, 10, Resolution.Daily); Debug($"We got {history.Count()} items from historical data request of {_datasetSymbol}."); } public override void OnData(Slice slice) { // Trade only base on government contract data foreach (var kvp in slice.Get<QuiverGovernmentContract>()) { // Buy if over 50000 government contract amount, suggesting a large income if (kvp.Value.Any(x => (int) (x as QuiverGovernmentContract).Amount > 50000m)) { SetHoldings(_symbol, 1); } // Sell if below 10000 government contract amount, suggesting a smaller than usual income else if (kvp.Value.Any(x => (int) (x as QuiverGovernmentContract).Amount < 10000m)) { SetHoldings(_symbol, -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.
from AlgorithmImports import * from QuantConnect.DataSource import * class QuiverGovernmentContractDataAlgorithm(QCAlgorithm): def initialize(self) -> None: self.set_start_date(2019, 1, 1) self.set_end_date(2020, 1, 1) self.set_cash(100000) self.universe_settings.resolution = Resolution.MINUTE # 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]: try: if self.last_time > algorithm.time: return [] except: self.Log("") # 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 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) algorithm.debug(f"We got {len(history)} items from our history request on {dataset_symbol}.") 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)
using QuantConnect.DataSource; namespace QuantConnect { public class QuiverGovernmentContractFrameworkAlgorithm : QCAlgorithm { public override void Initialize() { SetStartDate(2021, 1, 1); SetEndDate(2021, 7, 1); SetCash(100000); UniverseSettings.Resolution = Resolution.Minute; // Filter universe using government contract data AddUniverse<QuiverGovernmentContractUniverse>(data => { var govContractDataBySymbol = new Dictionary<Symbol, List<QuiverGovernmentContractUniverse>>(); foreach (var datum in data.OfType<QuiverGovernmentContractUniverse>()) { var symbol = datum.Symbol; if (!govContractDataBySymbol.ContainsKey(symbol)) { govContractDataBySymbol.Add(symbol, new List<QuiverGovernmentContractUniverse>()); } govContractDataBySymbol[symbol].Add(datum); } // Only select the stocks with over 5000 government contracts, which is considered material information return from kvp in govContractDataBySymbol where kvp.Value.Sum(x => x.Amount) > 5000m select kvp.Key; }); // Custom alpha model that emit insights based on updated government contract data AddAlpha(new QuiverGovernmentContractAlphaModel()); // Invest equally to evenly dissipate the capital concentration risk SetPortfolioConstruction(new EqualWeightingPortfolioConstructionModel()); SetExecution(new ImmediateExecutionModel()); } } public class QuiverGovernmentContractAlphaModel: AlphaModel { // A variable to control the rebalancing time private DateTime _time; // To hold the government contract dataset symbol for managing subscription private Dictionary<Symbol, Symbol> _datasetSymbolBySymbol = new(); public QuiverGovernmentContractAlphaModel() { _time = DateTime.MinValue; } public override IEnumerable<Insight> Update(QCAlgorithm algorithm, Slice slice) { if (_time > algorithm.Time) return new List<Insight>(); // Trade signal only based on government contract data var dataPoints = slice.Get<QuiverGovernmentContract>(); if (dataPoints.IsNullOrEmpty()) return new List<Insight>(); // To aggregate all data per symbol for analysis var govContracts = dataPoints.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.Sum(x => ((QuiverGovernmentContract)x).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 var sortedByGovContract = from kvp in govContracts orderby kvp.Value descending select kvp.Key.Underlying; var longSymbols = sortedByGovContract.Take(10).ToList(); var shortSymbols = sortedByGovContract.TakeLast(10).ToList(); var insights = new List<Insight>(); insights.AddRange(longSymbols.Select(symbol => new Insight(symbol, Expiry.EndOfDay, InsightType.Price, InsightDirection.Up))); insights.AddRange(shortSymbols.Select(symbol => new Insight(symbol, Expiry.EndOfDay, InsightType.Price, InsightDirection.Down))); _time = Expiry.EndOfDay(algorithm.Time); return insights; } public override void OnSecuritiesChanged(QCAlgorithm algorithm, SecurityChanges changes) { foreach (var security in changes.AddedSecurities) { // Requesting government contract data for trade signal generation var symbol = security.Symbol; var datasetSymbol = algorithm.AddData<QuiverGovernmentContract>(symbol).Symbol; _datasetSymbolBySymbol.Add(symbol, datasetSymbol); // History request var history = algorithm.History<QuiverGovernmentContract>(datasetSymbol, 10, Resolution.Daily); algorithm.Debug($"We get {history.Count()} items in historical data of {datasetSymbol}"); } foreach (var security in changes.RemovedSecurities) { var symbol = security.Symbol; if (_datasetSymbolBySymbol.ContainsKey(symbol)) { // Remove government contract data subscription to release computation resources _datasetSymbolBySymbol.Remove(symbol, out var datasetSymbol); algorithm.RemoveSecurity(datasetSymbol); } } } } }
Research Example
The following example lists all US Equities with Government contracts in the past year.
#r "../QuantConnect.DataSource.QuiverGovernmentContracts.dll" using QuantConnect.DataSource; // Requesting data var aapl = qb.AddEquity("AAPL", Resolution.Daily).Symbol; var symbol = qb.AddData<QuiverGovernmentContract>(aapl).Symbol; // Historical data var history = qb.History<QuiverGovernmentContract>(symbol, 360, Resolution.Daily); foreach (var contracts in history) { foreach (QuiverGovernmentContract contract in contracts) { Console.WriteLine($"{contract.Symbol} amount at {contract.EndTime}: {contract.Amount}"); } } // Add Universe Selection IEnumerable<Symbol> UniverseSelection(IEnumerable<BaseData> altCoarse) { return from d in altCoarse.OfType<QuiverGovernmentContractUniverse>() select d.Symbol; } var universe = qb.AddUniverse<QuiverGovernmentContractUniverse<(UniverseSelection); // Historical Universe data var universeHistory = qb.UniverseHistory(universe, qb.Time.AddDays(-360), qb.Time); foreach (var contracts in universeHistory) { foreach (QuiverGovernmentContractUniverse contract in contracts) { Console.WriteLine($"{contract.Symbol} amount at {contract.EndTime}: {contract.Amount}"); } }
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:
QuiverGovernmentContractUniverse
QuiverGovernmentContractUniverse
objects have the following attributes: