# Piercing Veil strategy file. Upload this as-is to try it, then make it yours.
#
# UNIVERSE: up to 20 US-listed stocks or ETFs. Daily bars, split/dividend adjusted, from 2016
# (or from listing). decide() is called once per trading day, after the close.

import numpy as np

UNIVERSE = ["SPY", "TLT"]


def decide(history, state):
    """history: {symbol: DataFrame[open, high, low, close, volume]}, every day up to and including
                today. Never tomorrow.
       state:   a dict that persists between days (cache a trained model, counters, anything).
       return:  {symbol: position for tomorrow's open} between -1 (fully short) and 1 (fully long).
                Leave a symbol out, or return 0, to be flat."""
    positions = {}
    for symbol, bars in history.items():
        close = bars["close"]
        if len(close) < 200:                      # not enough history yet
            continue
        trend = close.iloc[-1] > close.tail(200).mean()
        vol = np.log(close).diff().tail(20).std() * np.sqrt(252)
        positions[symbol] = 1.0 if trend and vol < 0.25 else 0.0
    return positions
