Datasets

India Equity

Introduction

This page explains how to request, manipulate, and visualize historical India Equity data.

Create Subscriptions

Follow these steps to subscribe to an India Equity security:

  1. Load the required assembly files and data types.
  2. #load "../Initialize.csx"
    #load "../QuantConnect.csx"
    
    using QuantConnect;
    using QuantConnect.Data;
    using QuantConnect.Algorithm;
    using QuantConnect.Research;
  3. Create a QuantBook.
  4. var qb = new QuantBook();
    qb = QuantBook()
  5. Call the AddEquity method with a ticker and then save a reference to the India Equity Symbol.
  6. var icicibank = qb.AddEquity("ICICIBANK", Resolution.Minute, Market.India).Symbol;
    var yesbank = qb.AddEquity("YESBANK", Resolution.Minute, Market.India).Symbol;
    icicibank = qb.AddEquity("ICICIBANK", Resolution.Minute, Market.India).Symbol
    yesbank = qb.AddEquity("YESBANK", Resolution.Minute, Market.India).Symbol

To view the supported assets in the India Equities dataset, see Supported Assets.

Get Historical Data

You need a subscription before you can request historical data for a security. On the time dimension, you can request an amount of historical data based on a trailing number of bars, a trailing period of time, or a defined period of time. On the security dimension, you can request historical data for a single India Equity, a subset of the India Equities you created subscriptions for in your notebook, or all of the India Equities in your notebook.

Trailing Number of Bars

To get historical data for a number of trailing bars, call the History method with the Symbol object(s) and an integer.

// Slice objects
var singleHistorySlice = qb.History(icicibank, 10);
var subsetHistorySlice = qb.History(new[] {icicibank, yesbank}, 10);
var allHistorySlice = qb.History(10);

// TradeBar objects
var singleHistoryTradeBars = qb.History<TradeBar>(icicibank, 10);
var subsetHistoryTradeBars = qb.History<TradeBar>(new[] {icicibank, yesbank}, 10);
var allHistoryTradeBars = qb.History<TradeBar>(qb.Securities.Keys, 10);
# DataFrame of trade data
single_history_df = qb.History(icicibank, 10)
subset_history_df = qb.History([icicibank, yesbank], 10)
all_history_df = qb.History(qb.Securities.Keys, 10)

# Slice objects
all_history_slice = qb.History(10)

# TradeBar objects
single_history_trade_bars = qb.History[TradeBar](icicibank, 10)
subset_history_trade_bars = qb.History[TradeBar]([icicibank, yesbank], 10)
all_history_trade_bars = qb.History[TradeBar](qb.Securities.Keys, 10)

The preceding calls return the most recent bars, excluding periods of time when the exchange was closed.

Trailing Period of Time

To get historical data for a trailing period of time, call the History method with the Symbol object(s) and a TimeSpantimedelta.

// Slice objects
var singleHistorySlice = qb.History(icicibank, TimeSpan.FromDays(3));
var subsetHistorySlice = qb.History(new[] {icicibank, yesbank}, TimeSpan.FromDays(3));
var allHistorySlice = qb.History(10);

// TradeBar objects
var singleHistoryTradeBars = qb.History<TradeBar>(icicibank, TimeSpan.FromDays(3));
var subsetHistoryTradeBars = qb.History<TradeBar>(new[] {icicibank, yesbank}, TimeSpan.FromDays(3));
var allHistoryTradeBars = qb.History<TradeBar>(TimeSpan.FromDays(3));
# DataFrame of trade data
single_history_df = qb.History(icicibank, timedelta(days=3))
subset_history_df = qb.History([icicibank, yesbank], timedelta(days=3))
all_history_df = qb.History(qb.Securities.Keys, timedelta(days=3))

# Slice objects
all_history_slice = qb.History(timedelta(days=3))

# TradeBar objects
single_history_trade_bars = qb.History[TradeBar](icicibank, timedelta(days=3))
subset_history_trade_bars = qb.History[TradeBar]([icicibank, yesbank], timedelta(days=3))
all_history_trade_bars = qb.History[TradeBar](qb.Securities.Keys, timedelta(days=3))

The preceding calls return the most recent bars, excluding periods of time when the exchange was closed.

Defined Period of Time

To get historical data for a specific period of time, call the History method with the Symbol object(s), a start DateTimedatetime, and an end DateTimedatetime. The start and end times you provide are based in the notebook time zone.

var startTime = new DateTime(2021, 1, 1);
var endTime = new DateTime(2021, 2, 1);

// Slice objects
var singleHistorySlice = qb.History(icicibank, startTime, endTime);
var subsetHistorySlice = qb.History(new[] {icicibank, yesbank}, startTime, endTime);
var allHistorySlice = qb.History(qb.Securities.Keys, startTime, endTime);

// TradeBar objects
var singleHistoryTradeBars = qb.History<TradeBar>(icicibank, startTime, endTime);
var subsetHistoryTradeBars = qb.History<TradeBar>(new[] {icicibank, yesbank}, startTime, endTime);
var allHistoryTradeBars = qb.History<TradeBar>(qb.Securities.Keys, startTime, endTime);
start_time = datetime(2021, 1, 1)
end_time = datetime(2021, 2, 1)

# DataFrame of trade data
single_history_df = qb.History(icicibank, start_time, end_time)
subset_history_df = qb.History([icicibank, yesbank], start_time, end_time)
all_history_df = qb.History(qb.Securities.Keys, start_time, end_time)

# TradeBar objects
single_history_trade_bars = qb.History[TradeBar](icicibank, start_time, end_time)
subset_history_trade_bars = qb.History[TradeBar]([icicibank, yesbank], start_time, end_time)
all_history_trade_bars = qb.History[TradeBar](qb.Securities.Keys, start_time, end_time)

The preceding calls return the bars that have a timestamp within the defined period of time.

Resolutions

The following table shows the available resolutions and data formats for India Equity subscriptions:

ResolutionTradeBarQuoteBarTrade TickQuote Tick
Tick

Second

Minutegreen check
Hourgreen check
Dailygreen check

Markets

LEAN groups all of the India Equity exchanges under Market.India.

Data Normalization

The data normalization mode defines how historical data is adjusted for corporate actions. By default, LEAN adjusts US Equity data for splits and dividends to produce a smooth price curve, but the following data normalization modes are available:

We use the entire split and dividend history to adjust historical prices. This process ensures you get the same adjusted prices, regardless of the QuantBook time.

To set the data normalization mode for a security, pass a dataNormalizationMode argument to the AddEquity method.

var icicibank = qb.AddEquity("ICICIBANK", dataNormalizationMode: DataNormalizationMode.Raw).Symbol;
icicibank = qb.AddEquity("ICICIBANK", dataNormalizationMode=DataNormalizationMode.Raw).Symbol

When you request historical data, the History method uses the data normalization of your security subscription. To get historical data with a different data normalization, pass a dataNormalizationMode argument to the History method.

var history = qb.History(qb.Securities.Keys, qb.Time-TimeSpan.FromDays(10), qb.Time, dataNormalizationMode: DataNormalizationMode.SplitAdjusted);
history = qb.History(qb.Securities.Keys, qb.Time-timedelta(days=10), qb.Time, dataNormalizationMode=DataNormalizationMode.SplitAdjusted)

Wrangle Data

You need some historical data to perform wrangling operations. The process to manipulate the historical data depends on its data type. To display pandas objects, run a cell in a notebook with the pandas object as the last line. To display other data formats, call the print method.

You need some historical data to perform wrangling operations. Use LINQ to wrangle the data and then call the Console.WriteLine method in a Jupyter Notebook to display the data. The process to manipulate the historical data depends on its data type.

DataFrame Objects

If the History method returns a DataFrame, the first level of the DataFrame index is the encoded India Equity Symbol and the second level is the EndTime of the data sample. The columns of the DataFrame are the data properties.

DataFrame of two India Equities

To select the historical data of a single India Equity, index the loc property of the DataFrame with the India Equity Symbol.

all_history_df.loc[icicibank]  # or all_history_df.loc['ICICIBANK']
DataFrame of one India Equity

To select a column of the DataFrame, index it with the column name.

all_history_df.loc[icicibank]['close']
Series of close values

If you request historical data for multiple India Equities, you can transform the DataFrame so that it's a time series of close values for all of the India Equities. To transform the DataFrame, select the column you want to display for each India Equity and then call the unstack method.

all_history_df['close'].unstack(level=0)

The DataFrame is transformed so that the column indices are the Symbol of each India Equity and each row contains the close value.

DataFrame of one India Equity

You may construct a Microsoft.Data.Analysis.DataFrame object from the historical data for efficient vectorized data wrangling.

var columns = new DataFrameColumn[] {
    new PrimitiveDataFrameColumn("Time", history.Select(x => x[icicibank].EndTime)),
    new DecimalDataFrameColumn("ICICIBANK Open", history.Select(x => x[icicibank].Open)),
    new DecimalDataFrameColumn("ICICIBANK High", history.Select(x => x[icicibank].High)),
    new DecimalDataFrameColumn("ICICIBANK Low", history.Select(x => x[icicibank].Low)),
    new DecimalDataFrameColumn("ICICIBANK Close", history.Select(x => x[icicibank].Close))
};
var df = new DataFrame(columns);
df

The below displayed a formatted dataframe with reference from SWHarden.

Historical C# dataframe

To select a particular column, specifies it like a dictionary key.

df["ICICIBANK close"]
Historical C# dataframe column

Slice Objects

If the History method returns Slice objects, iterate through the Slice objects to get each one. The Slice objects may not have data for all of your India Equity subscriptions. To avoid issues, check if the Slice contains data for your India Equity before you index it with the India Equity Symbol.

foreach (var slice in allHistorySlice) {
    if (slice.Bars.ContainsKey(icicibank))
    {
        var tradeBar = slice.Bars[icicibank];
    }
}
for slice in all_history_slice:
        if slice.Bars.ContainsKey(icicibank):
        trade_bar = slice.Bars[icicibank]

You can also iterate through each TradeBar in the Slice.

foreach (var slice in allHistorySlice)
{
    foreach (var kvp in slice.Bars)
    {
        var symbol = kvp.Key;
        var tradeBar = kvp.Value;
    }
}
for slice in all_history_slice:
    for kvp in slice.Bars:
        symbol = kvp.Key
        trade_bar = kvp.Value

You can also use LINQ to select each TradeBar in the Slice for a given Symbol.

var tradeBars = allHistorySlice.Where(slice => slice.Bars.ContainsKey(icicibank)).Select(slice => slice.Bars[icicibank]);

TradeBar Objects

If the History method returns TradeBar objects, iterate through the TradeBar objects to get each one.

foreach (var tradeBar in singleHistoryTradeBars)
{
    Console.WriteLine(tradeBar);
}
for trade_bar in single_history_trade_bars:
    print(trade_bar)

If the History method returns TradeBars, iterate through the TradeBars to get the TradeBar of each India Equity. The TradeBars may not have data for all of your India Equity subscriptions. To avoid issues, check if the TradeBars object contains data for your security before you index it with the India Equity Symbol.

foreach (var tradeBars in allHistoryTradeBars)
{
    if (tradeBars.ContainsKey(icicibank))
    {
        var tradeBar = tradeBars[icicibank];
    }
}
for trade_bars in all_history_trade_bars:
    if trade_bars.ContainsKey(icicibank):
        trade_bar = trade_bars[icicibank]

You can also iterate through each of the TradeBars.

foreach (var tradeBars in allHistoryTradeBars)
{
    foreach (var kvp in tradeBars)
    {
        var symbol = kvp.Key;
        var tradeBar = kvp.Value;
    }
}
for trade_bars in all_history_trade_bars:
    for kvp in trade_bars:
        symbol = kvp.Key
        trade_bar = kvp.Value

Plot Data

You need some historical Equity data to produce plots. You can use many of the supported plotting librariesPlot.NET package to visualize data in various formats. For example, you can plot candlestick and line charts.

Candlestick Chart

Follow these steps to plot candlestick charts:

  1. Get some historical data.
  2. history = qb.History(icicibank, datetime(2021, 11, 23), datetime(2021, 12, 8), Resolution.Daily).loc[icicibank]
    var history = qb.History<TradeBar>(icicibank, new DateTime(2021, 11, 23), new DateTime(2021, 12, 8), Resolution.Daily);
  3. Import the plotlyPlotly.NET library.
  4. import plotly.graph_objects as go
    #r "../Plotly.NET.dll"
    using Plotly.NET;
    using Plotly.NET.LayoutObjects;
  5. Create a Candlestick chart.
  6. candlestick = go.Candlestick(x=history.index,
                                 open=history['open'],
                                 high=history['high'],
                                 low=history['low'],
                                 close=history['close'])
    var chart = Chart2D.Chart.Candlestick<decimal, decimal, decimal, decimal, DateTime, string>(
        history.Select(x => x.Open),
        history.Select(x => x.High),
        history.Select(x => x.Low),
        history.Select(x => x.Close),
        history.Select(x => x.EndTime)
    );
  7. Create a Layout.
  8. layout = go.Layout(title=go.layout.Title(text='ICICIBANK OHLC'),
                       xaxis_title='Date',
                       yaxis_title='Price',
                       xaxis_rangeslider_visible=False)
    LinearAxis xAxis = new LinearAxis();
    xAxis.SetValue("title", "Time");
    LinearAxis yAxis = new LinearAxis();
    yAxis.SetValue("title", "Price ($)");
    Title title = Title.init("ICICIBANK Price");
    
    Layout layout = new Layout();
    layout.SetValue("xaxis", xAxis);
    layout.SetValue("yaxis", yAxis);
    layout.SetValue("title", title);
  9. Create the Figure.
  10. fig = go.Figure(data=[candlestick], layout=layout)
  11. Assign the Layout to the chart.
  12. chart.WithLayout(layout);
  13. Show the plot.
  14. fig.show()
    HTML(GenericChart.toChartHTML(chart))

    Candlestick charts display the open, high, low, and close prices of the security.

Candlestick plot of ICICIBANK OHLC Candlestick plot of ICICIBANK OHLC

Line Chart

Follow these steps to plot line charts using built-in methodsPlotly.NET package:

  1. Get some historical data.
  2. history = qb.History([icicibank, yesbank], datetime(2021, 11, 23), datetime(2021, 12, 8), Resolution.Daily)
    var history = qb.History<TradeBar>(icicibank, new DateTime(2021, 11, 23), new DateTime(2021, 12, 8), Resolution.Daily);
  3. Select the data to plot.
  4. volume = history['volume'].unstack(level=0)
  5. Call the plot method on the pandas object.
  6. volume.plot(title="Volume", figsize=(15, 10))
  7. Create a Line chart.
  8. var chart = Chart2D.Chart.Line<DateTime, decimal, string>(
        icicibank.Select(x => x.EndTime),
        icicibank.Select(x => x.Volume)
    );
  9. Create a Layout.
  10. LinearAxis xAxis = new LinearAxis();
    xAxis.SetValue("title", "Time");
    LinearAxis yAxis = new LinearAxis();
    yAxis.SetValue("title", "Volume");
    Title title = Title.init("ICICIBANK Volume");
    
    Layout layout = new Layout();
    layout.SetValue("xaxis", xAxis);
    layout.SetValue("yaxis", yAxis);
    layout.SetValue("title", title);
  11. Assign the Layout to the chart.
  12. chart.WithLayout(layout);
  13. Show the plot.
  14. plt.show()
    HTML(GenericChart.toChartHTML(chart))

    Line charts display the value of the property you selected in a time series.

Common Errors

Some factor files have INF split values, which indicate that the stock has so many splits that prices can't be calculated with correct numerical precision. To allow history requests with these symbols, we need to move the starting date forward when reading the data. If there are numerical precision errors in the factor files for a security in your history request, LEAN throws the following error:

"Warning: when performing history requests, the start date will be adjusted if there are numerical precision errors in the factor files."

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: