#!/usr/bin/env python
# Copyright (c) TripleBlind Holdings, Inc. Confidential and Proprietary. All rights reserved.

import tripleblind as tb


tb.initialize(api_token=tb.config.example_user1["token"])

# Example of publishing a dataset in a different format from the source data.
# Here a subset of the data is published, and a complex calculation is
# performed to generate a 15-day and 30-day running average from a series of
# data rows.

name = "EXAMPLE - FORD moving average price"
desc = """Example of data owner munging.  The moving average daily low
(mov_15 and mov_30) for a single stock (FORD) is computed from a database
holding daily high and low values for many stocks."""

try:
    print(f"Creating '{name}'")
    asset = tb.asset.DatabaseDataset.create(
        connection="postgresql://demouser:=DJdmcAY8xx%tnsfXuhO@104.154.188.123:5432/postgres",
        query="""
        select date, low,
               avg(low) over (
                   order by date
                   rows between 15 preceding
                    and current row
                ) as mov_15,
               avg(low) over (
                   order by date
                   rows between 30 preceding
                    and current row
               ) as mov_30
        from stock.daily
        where ticker = 'F'
        order by date;
        """,
        name=name,
        desc=desc,
    )
except tb.TripleblindAssetAlreadyExists:
    print("Asset already exists.")

print("Data is in position.")
