Created
May 22, 2020 02:29
-
-
Save jamesfulford/aa493aac3d427301b2ad31759bc31e1d to your computer and use it in GitHub Desktop.
Alpaca-compliant algorithm for tracking a single asset. Underperforms most assets except in downturns - a conservative strategy.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from pylivetrader.api import * | |
import logbook | |
log = logbook.Logger('track-ticker') | |
def enter_play(context, data): | |
s = context.ticker | |
if not data.can_trade(s): | |
return | |
fast_sma = data.history(s, 'price', context.fast_sma_days, '1d').mean() | |
slow_sma = data.history(s, 'price', context.slow_sma_days, '1d').mean() | |
context.target_percentage = context.exit_percentage if fast_sma < slow_sma else context.enter_percentage | |
print("Current target percentage: {.2f}".format(context.target_percentage)) | |
order_target_percent(s, context.target_percentage) | |
def initialize(context): | |
# TODO: Try gradient descent on these parameters | |
context.exit_percentage = 0.1 | |
context.enter_percentage = 1.0 | |
context.fast_sma_days = 2 | |
context.slow_sma_days = 15 | |
context.trade_at_minute = 30 | |
context.ticker = symbol('MSFT') | |
if context.target_percentage: | |
log.info("Current target percentage: {}".format(round(context.target_percentage * 100, 2))) | |
else: | |
log.info("Fresh context") | |
schedule_function( | |
enter_play, | |
date_rules.every_day(), | |
time_rules.market_open(minutes=context.trade_at_minute), | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment