US Department of Agriculture

USDA Fruit And Vegetables

Introduction

The USDA Fruit And Vegetables dataset by the U.S. Department of Agriculture (USDA) tracks retail price estimates for 75+ commonly consumed fresh and processed fruits and vegetables. Includes price per pound/pint and normalized price per edible cup equivalent.

For more information about the USDA Fruit And Vegetables dataset, including CLI commands and pricing, see the dataset listing.

About the Provider

The Economic Research Service (ERS) is a federal statistical agency of the U.S. Department of Agriculture (USDA) dedicated to conducting objective economic research that informs public and private decision-making across agriculture, food, the environment, and rural America. ERS serves policymakers at all levels of government, Congress, and industry groups by providing high-quality analysis on topics ranging from farm sector performance and food security to global trade and rural economic development. The USDA Economic Research Service (ERS) publishes retail price data for fruits and vegetables across multiple forms: Fresh, Canned, Frozen, Dried, and Juice.

Getting Started

The following snippet demonstrates how to request data from the USDA Fruit and Vegetables dataset:

self.dataset_symbol = self.add_data(USDAFruitAndVegetables,
    USDAFruitAndVegetable.Symbols.Apples, Resolution.DAILY)
var datasetSymbol = AddData<USDAFruitAndVegetables>(
    USDAFruitAndVegetable.Symbols.Apples, Resolution.Daily);

Data Summary

The following table describes the dataset properties:

PropertyValue
Start DateJanuary 2013
Asset Coverage75 Fruits and Vegetables
ResolutionAnnual
Data DensitySparse
TimezoneNew York

Requesting Data

To add USDA Fruit And Vegetables 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 USDAFruitAndVegetablesAlgorithm(QCAlgorithm):     
    def initialize(self) -> None: 	 
        self.set_start_date(2013, 1, 1)
        self.set_end_date(2024, 12, 31)
        self.set_cash(100000)
        self.dataset_symbol = self.add_data(USDAFruitAndVegetables, USDAFruitAndVegetable.Symbols.Apples, Resolution.DAILY)
public class USDAFruitAndVegetablesAlgorithm: QCAlgorithm  
{  
    private Symbol _datasetSymbol;  
    public override void Initialize()  
    {  
        SetStartDate(2013, 1, 1);
        SetEndDate(2024, 12, 31); 
        SetCash(100000);
        _datasetSymbol = AddData<USDAFruitAndVegetables>(USDAFruitAndVegetable.Symbols.Apples, Resolution.Daily);
    }
}

Accessing Data

To get the current USDA Fruit And Vegetables 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):  
        collection = slice[self.dataset_symbol]  
        for data in collection.data:
            self.log(f"{symbol} [{data.form}]: ${data.price_per_cup_equivalent}")
public override void OnData(Slice slice)  
{  
    if (slice.ContainsKey(_datasetSymbol))  
    {  
        var collection = slice[_datasetSymbol];  
         // Iterate over all forms in the collection
        foreach (USDAFruitAndVegetable data in collection.Data)
        {
            Log($"{symbol} [{data.Form}]: ${data.PricePerCupEquivalent}");
        }
    }  
}

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

def on_data(self, slice: Slice) -> None:  
    for symbol, collection in slice.get(USDAFruitAndVegetables).items():
        # Iterate over all forms in the collection
        for data in collection.data:
            self.log(f"{symbol} [{data.form}]: ${data.price_per_cup_equivalent}")
public override void OnData(Slice slice)  
{  
    foreach (var kvp in slice.Get<USDAFruitAndVegetables>())
    {
        var symbol = kvp.Key;
        var collection = kvp.Value;

        // Iterate over all forms in the collection
        foreach (USDAFruitAndVegetable data in collection.Data)
        {
            Log($"{symbol} [{data.Form}]: ${data.PricePerCupEquivalent}");
        }
    }
}

Historical Data

To get historical USDA Fruit And Vegetables data, call the Historyhistory method with the dataset Symbol. If there is no data in the period you request, the history result is empty.

history_df = self.history(self.dataset_symbol, datetime(2013, 1, 1), self.time, Resolution.DAILY) 
var history = History<USDAFruitAndVegetables>(_datasetSymbol, new DateTime(2013, 1, 1), Time, Resolution.Daily); 

Remove Subscriptions

To remove a subscription, call the RemoveSecurityremove_security method.

self.remove_security(self.dataset_symbol)
RemoveSecurity(_datasetSymbol);

Supported Assets

The USDA Fruit And Vegetable dataset lists data for the following agricultural products:

Example Applications

The USDA Fruit and Vegetable dataset provides insights into the agricultural sector. Examples include the following strategies:

  • Compare the prices across sub-products (fresh vs frozen)
  • Compare the price trends across products (strawberry vs orange)
  • Understand how the agricultural market correlates with the stock market

Classic Algorithm Example

The following example algorithm compares the price difference between fresh and frozen strawberries:

from AlgorithmImports import *

class FreshVsFrozenAlgorithm(QCAlgorithm):

    def initialize(self):
        self.set_start_date(2018, 1, 1)
        self.set_end_date(2023, 12, 31)

        # Single subscription gets both Fresh and Frozen forms
        self.strawberries = self.add_data(USDAFruitAndVegetables, USDAFruitAndVegetable.Symbols.Strawberries).symbol

        history = self.history(USDAFruitAndVegetables, self.strawberries, datetime(2013,1,1), self.time, flatten=True)        

    def on_data(self, slice):
        if slice.contains_key(self.strawberries):
            collection = slice[self.strawberries]

            # Find Fresh and Frozen forms in the collection
            fresh_price = None
            frozen_price = None

            for data in collection.data:
                if data.form == "Fresh":
                    fresh_price = data.value
                elif data.form == "Frozen":
                    frozen_price = data.value

            if fresh_price and frozen_price:
                diff_pct = ((fresh_price / frozen_price) - 1) * 100
                self.log(f"{self.time.year}: Fresh ${fresh_price:.2f} vs Frozen ${frozen_price:.2f} ({diff_pct:+.1f}%)")
public class FreshVsFrozenAlgorithm : QCAlgorithm
{
    private Symbol _strawberries;
    public override void Initialize()
    {
        SetStartDate(2018, 1, 1);
        SetEndDate(2023, 12, 31);

        // Single subscription gets both Fresh and Frozen forms
        _strawberries = AddData<USDAFruitAndVegetables>(USDAFruitAndVegetable.Symbols.Strawberries).Symbol;

        var history = History<USDAFruitAndVegetables>(_strawberries, new DateTime(2013,1,1), Time).ToList();
    }

    public override void OnData(Slice slice)
    {
        if (!slice.TryGet<USDAFruitAndVegetables>(_strawberries, out var collection))
        {
            return;
        }

        // Find Fresh and Frozen forms in the collection
        decimal? freshPrice = null;
        decimal? frozenPrice = null;

        foreach (var data in collection.Data.Cast<USDAFruitAndVegetable>())
        {
            if (data.Form == "Fresh")
                freshPrice = data.Value;
            if (data.Form == "Frozen")
                frozenPrice = data.Value;
        }

        if (freshPrice.HasValue && frozenPrice.HasValue)
        {
            var diffPct = ((freshPrice / frozenPrice) - 1) * 100;
            Log($"{Time.Year}: Fresh ${freshPrice:.2f} vs Frozen ${frozenPrice:.2f} ({diffPct:+.1f}%)");
        }
    }
}

Data Point Attributes

The USDA Fruit And Vegetable dataset provides USDAFruitAndVegetables and USDAFruitAndVegetable objects, which have the following attributes:

USDAFruitAndVegetables Attributes

USDAFruitAndVegetable 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: