Test Project

Target weights example.

A minimal homepage for viewing my current target weights and a compact consumer script that polls /api and rebalances only when portfolio drift exceeds 2.00%. Later, this project will likely focus on green stocks and smaller businesses, but it does not at the moment.

API route: /api
Symbols: 4

Current targets

Symbol Weight
CAT 0.200000
SMCI 0.200000
UPS 0.113194
CB 0.153825

Not Financial Advice

The information provided on this platform is for general informational and educational purposes only. It does not constitute, and should not be considered, professional or personal financial advice. Before making any financial or investment decisions, you should consult a licensed financial advisor to assess your specific personal circumstances, financial situation, and objectives.

Consumer script

This script allows you to follow my investements yourself, in an automated way. It polls the API on this site, and submits market notional orders to your alpaca account using the account keys you add.

import time
import requests

from alpaca.trading.client import TradingClient
from alpaca.trading.requests import MarketOrderRequest
from alpaca.trading.enums import OrderSide, TimeInForce

API_KEY = "YOUR_ALPACA_KEY"
API_SECRET = "YOUR_ALPACA_SECRET"
PAPER = False

TARGETS_URL = "http://127.0.0.1:8000/api"
POLL_SECONDS = 30
DRIFT_THRESHOLD = 0.02
MIN_NOTIONAL = 5.00

client = TradingClient(API_KEY, API_SECRET, paper=PAPER)


def get_target_weights():
    r = requests.get(TARGETS_URL, timeout=10)
    r.raise_for_status()
    data = r.json()
    return data["target_weights"] if "target_weights" in data else data


def get_equity_and_positions():
    account = client.get_account()
    equity = float(account.equity)
    positions = {}
    for p in client.get_all_positions():
        positions[p.symbol] = float(p.market_value)
    return equity, positions


def submit_notional_order(symbol, side, notional):
    order = MarketOrderRequest(
        symbol=symbol,
        notional=round(notional, 2),
        side=side,
        time_in_force=TimeInForce.DAY,
    )
    return client.submit_order(order_data=order)


def rebalance_once():
    target_weights = get_target_weights()
    equity, positions = get_equity_and_positions()

    current_symbols = set(positions)
    target_symbols = set(target_weights)

    for symbol in sorted(current_symbols | target_symbols):
        current_value = positions.get(symbol, 0.0)
        current_weight = current_value / equity if equity > 0 else 0.0
        target_weight = float(target_weights.get(symbol, 0.0))
        diff = target_weight - current_weight

        if abs(diff) <= DRIFT_THRESHOLD:
            continue

        notional = abs(diff) * equity
        if notional < MIN_NOTIONAL:
            continue

        side = OrderSide.BUY if diff > 0 else OrderSide.SELL
        submit_notional_order(symbol, side, notional)
        print(f"{side.value.upper():4} {symbol} ${notional:.2f} "
              f"drift={diff:+.4f}")


if __name__ == "__main__":
    while True:
        try:
            rebalance_once()
        except Exception as e:
            print("error:", e)
        time.sleep(POLL_SECONDS)

Green Finance Framework by Felix Farquharson is marked CC0 1.0