0

我需要绘制在特定时间范围内具有 a和 a的交易的成交量加权平均 Prive (VWAP) 。price_per_unitquantitiy

作为聚合的结果,每个桶都date_histogram应该包含迄今为止发生的所有交易的 VWAP。

我不确定这是否可以使用 Elasticsearch 进行,也不确定处理它的正确方法是什么(比如使用脚本?)?

文档的基本映射trade非常简单:

"trade": {
  "properties": 
    "trade_id": {"type": "string", "index": "not_analyzed"},
    "product_id": {"type": "string", "index": "not_analyzed"},
    "quantity": {'type': 'double'}, // number of units
    "execution_time": {'type': 'date'},
    "price_per_unit": {'type': 'double'},
  }
}

鉴于execution_time应该用于date_histogram和 交易的总价格是 和 的price_per_unit乘积quantity。因此VWAP = sum(price_per_unit * quantity) / sum(quantity).

4

1 回答 1

2
DELETE test
PUT test
{
  "mappings": {
    "trade": {
      "properties": {
        "trade_id": {
          "type": "string",
          "index": "not_analyzed"
        },
        "product_id": {
          "type": "string",
          "index": "not_analyzed"
        },
        "quantity": {
          "type": "double"
        },
        "execution_time": {
          "type": "date"
        },
        "price_per_unit": {
          "type": "double"
        }
      }
    }
  }
}

POST test/trade/_bulk
{"index":{}}
{"execution_time":"2016-11-18T22:45:27Z","quantity":10,"price_per_unit":5}
{"index":{}}
{"execution_time":"2016-11-18T22:45:27Z","quantity":10,"price_per_unit":5}
{"index":{}}
{"execution_time":"2016-11-19T22:45:27Z","quantity":10,"price_per_unit":5}
{"index":{}}
{"execution_time":"2016-11-20T22:45:27Z","quantity":10,"price_per_unit":5}
{"index":{}}
{"execution_time":"2016-11-20T22:45:27Z","quantity":10,"price_per_unit":5}
{"index":{}}
{"execution_time":"2016-11-20T22:45:27Z","quantity":10,"price_per_unit":5}
{"index":{}}
{"execution_time":"2016-11-21T22:45:27Z","quantity":10,"price_per_unit":5}
{"index":{}}
{"execution_time":"2016-11-21T22:45:27Z","quantity":10,"price_per_unit":5}

POST test/trade/_search
{
  "size": 0,
  "aggs": {
    "sales_per_day": {
      "date_histogram": {
        "field": "execution_time",
        "interval": "day"
      },
      "aggs": {
        "sales": {
          "sum": {
            "script": {
              "lang": "groovy",
              "inline": "doc['quantity'] * doc['price_per_unit']"
            }
          }
        },
        "cumulative_sales": {
          "cumulative_sum": {
            "buckets_path": "sales"
          }
        }
      }
    }
  }
}

并且您需要为 groovy 启用内联脚本

于 2016-11-29T15:25:28.817 回答