Source: https://databento.com/docs/examples/basics-historical/eod


# End-of-day pricing and portfolio valuation

In this example we will use the [Historical client](https://databento.com/docs/api-historical/client.md) to calculate the end-of-day (EOD) value of a hypothetical portfolio.
To do this we will request the closing price for each symbol on a given date and use this price to determine the value of our portfolio.

## OHLCV Schemas

We'll demonstrate this example using the [OHLCV-1d schema](https://databento.com/docs/schemas/ohlcv.md).
The OHLCV family of schemas contain the opening, high, low and closing prices as well as the aggregated volume of trades within a time interval.
Since we are interested in end-of-day evaluation, we'll use an interval of one day, which is specified by the suffix `1D`.

## Example

```cpp
#include <databento/historical.hpp>
#include <databento/pretty.hpp>
#include <databento/symbol_map.hpp>
#include <iomanip>
#include <iostream>
#include <string>
#include <unordered_map>

namespace db = databento;

int main() {
  // hypothetical portfolio mapping symbols to positions
  std::unordered_map<std::string, std::uint32_t> portfolio = {
      {"AAPL", 200}, {"AMZN", 200}, {"GOOG", 100}, {"META", 100}, {"NFLX", 114},
  };

  db::TsSymbolMap symbol_map;
  auto extract_symbol_map = [&symbol_map](db::Metadata metadata) {
    symbol_map = metadata.CreateSymbolMap();
  };

  std::int64_t value = 0;
  auto calc_eod = [&portfolio, &symbol_map, &value](const db::Record& record) {
    auto bar = record.Get<db::OhlcvMsg>();
    auto symbol = symbol_map.At(bar);
    auto position = portfolio[symbol];
    value += bar.close * position;
    return db::KeepGoing::Continue;
  };

  std::vector<std::string> symbols;
  for (const auto& [symbol, _] : portfolio) {
    symbols.emplace_back(symbol);
  }

  auto client = db::Historical::Builder().SetKey("$YOUR_API_KEY").Build();
  client.TimeseriesGetRange(
      "XNAS.ITCH", db::DateTimeRange<std::string>{"2022-10-19"}, symbols,
      db::Schema::Ohlcv1D, db::SType::RawSymbol, db::SType::InstrumentId, {},
      extract_symbol_map, calc_eod);
  std::cout << '#### Result

```plaintext
$105536.78
```

 << std::setprecision(2) << db::pretty::Px{value} << '\n';
  return 0;
}
```
## Result


# End-of-day pricing and portfolio valuation

## Overview

This example shows how to use the [Historical client](https://databento.com/docs/api-historical/client.md) to calculate the end-of-day (EOD) value of a hypothetical portfolio.
To do this we will request the closing price for each symbol on a given date and use this price to determine the value of our portfolio.

## OHLCV-1d schema

We'll demonstrate this example using the [OHLCV-1d schema](https://databento.com/docs/schemas/ohlcv.md).
The OHLCV family of schemas contain the opening, high, low and closing prices as well
as the aggregated volume of trades within a time interval. Since we are interested in
end-of-day evaluation, we'll use an interval of one day, which is specified by the
suffix `-1d`.

Many users will prefer to use the official daily settlement prices found in the
`statistics` schema for this purpose.

## Example

```python
import databento as db

# A hypothetical portfolio mapping symbols to a quantity of shares
portfolio = {
    "AAPL": 200,
    "AMZN": 200,
    "GOOG": 100,
    "META": 100,
    "NFLX": 114,
}

# Create a historical client
client = db.Historical("$YOUR_API_KEY")

# Request OHLCV-1d data
data = client.timeseries.get_range(
    dataset="XNAS.ITCH",
    start="2022-09-19",
    symbols=list(portfolio.keys()),
    stype_in="raw_symbol",
    schema="ohlcv-1d",
)

# Convert to DataFrame
eod_data = data.to_df()
eod_data = eod_data.set_index("symbol")

# Sum the products of the close prices and portfolio quantities
eod_evaluation = sum(
    eod_data.at[symbol, "close"] * quantity for symbol, quantity in portfolio.items()
)
print(f"${eod_evaluation:,.2f}")
```
## Result

```plaintext
$109,235.90
```


# End-of-day pricing and portfolio valuation
In this example we will use the [Historical client](https://databento.com/docs/api-historical/client.md) to calculate the end-of-day (EOD) value of a hypothetical portfolio.
To do this we will request the closing price for each symbol on a given date and use this price to determine the value of our portfolio.

## OHLCV Schemas

We'll demonstrate this example using the [OHLCV-1d schema](https://databento.com/docs/schemas/ohlcv.md).
The OHLCV family of schemas contain the opening, high, low and closing prices as well as the aggregated volume of trades within a time interval.
Since we are interested in end-of-day evaluation, we'll use an interval of one day, which is specified by the suffix `1D`.

## Example
```rust
use std::collections::HashMap;

use databento::{
    HistoricalClient,
    dbn::{OhlcvMsg, Schema, decode::DbnMetadata, pretty::Px},
    historical::timeseries::GetRangeParams,
};
use time::macros::date;

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    // A hypothetical portfolio mapping symbols to a quantity of shares
    let portfolio = HashMap::from([
        ("AAPL", 200),
        ("AMZN", 200),
        ("GOOG", 100),
        ("META", 100),
        ("NFLX", 114),
    ]);
    let mut client = HistoricalClient::builder().key_from_env()?.build()?;
    // First, we request the OHLCV-1D data
    let mut decoder = client
        .timeseries()
        .get_range(
            &GetRangeParams::builder()
                .dataset("XNAS.ITCH")
                .date_time_range(date!(2022 - 10 - 19))
                .symbols(portfolio.keys().cloned().collect::<Vec<_>>())
                .schema(Schema::Ohlcv1D)
                .build(),
        )
        .await?;
    // Next, we extract the symbol mappings for the date we queried
    let symbol_mappings = decoder
        .metadata()
        .symbol_map_for_date(date!(2022 - 10 - 19))?;
    // Finally, we sum the products of the close prices and portfolio quantities
    let mut eod = 0;
    while let Some(ohlcv) = decoder.decode_record::<OhlcvMsg>().await? {
        eod += portfolio[symbol_mappings[ohlcv].as_str()] * ohlcv.close;
    }
    println!("${:.2}", Px(eod));
    Ok(())
}
```
## Result
```plaintext
$105536.78
```
