示例#1
0
def run_strat(
    strat_json,
    strat_id,
    user_id=None,
    telegram_id=None,
    live=False,
    simulate_orders=True,
):
    log.info(f"Worker received job for strat {strat_id}")
    strat_dict = json.loads(strat_json)
    strat = Strategy.from_dict(strat_dict)
    strat.id = strat_id
    strat.telegram_id = telegram_id

    strat.run(
        viz=False,
        live=live,
        simulate_orders=simulate_orders,
        user_id=user_id,
        as_job=True,
    )
    result_df = strat.quant_results
    if result_df is None:
        log.warning("No results from strategy")
        return

    return result_df.to_json()
示例#2
0
def run_indicator(indicator_name):
    strat = Strategy(indicator_name)
    strat.add_market_indicator(indicator_name)
    click.secho('Running {}'.format(indicator_name), fg='cyan')
    strat.run(viz=False)
    click.secho('{}: {}'.format(indicator_name,
                                strat.quant_results['net_profit_pct']),
                fg='cyan')
    # import pdb; pdb.set_trace()

    return strat
示例#3
0
def run(datasets):
    """Runs s strategy based on provided Blockchain dataset codes

        \b
        Example:
            bchain -s NTRAN -s CPTRA

        \b
        Available Dataset Codes:
          - TOTBC - Total Bitcoins
          - MKTCP - Bitcoin Market Capitalization
          - TRFEE - Bitcoin Total Transaction Fees
          - TRFUS - Bitcoin Total Transaction Fees USD
          - NETDF - Bitcoin Network Deficit
          - NTRAN - Bitcoin Number of Transactions
          - NTRAT - Bitcoin Total Number of Transactions
          - NTREP - Bitcoin Number of Transactions Excluding Popular Addresses
          - NADDU - Bitcoin Number of Unique Bitcoin Addresses Used
          - NTRBL - Bitcoin Number of Transaction per Block
          - TOUTV - Bitcoin Total Output Volume
          - ETRAV - Bitcoin Estimated Transaction Volume
          - ETRVU - Bitcoin Estimated Transaction Volume USD
          - TRVOU - Bitcoin USD Exchange Trade Volume
          - TVTVR - Bitcoin Trade Volume vs Transaction Volume Ratio
          - MKPRU - Bitcoin Market Price USD
          - CPTRV - Bitcoin Cost % of Transaction Volume
          - CPTRA - Bitcoin Cost Per Transaction
          - HRATE - Bitcoin Hash Rate
          - MIREV - Bitcoin Miners Revenue
          - ATRCT - Bitcoin Median Transaction Confirmation Time
          - BCDDC - Bitcoin Days Destroyed Cumulative
          - BCDDE - Bitcoin Days Destroyed
          - BCDDW - Bitcoin Days Destroyed (Minimum Age 1 Week)
          - BCDDM - Bitcoin Days Destroyed (Minimum Age 1 Month)
          - BCDDY - Bitcoin Days Destroyed (Minimum Age 1 Year)
          - BLCHS - Bitcoin api.blockchain Size
          - AVBLS - Bitcoin Average Block Size
          - MWTRV - Bitcoin My Wallet Transaction Volume
          - MWNUS - Bitcoin My Wallet Number of Users
          - MWNTD - Bitcoin My Wallet Number of Transaction Per Day
          - MIOPM - Bitcoin Mining Operating Margin
          - DIFF - Bitcoin Difficulty
  """

    click.secho("Executing using datasets:\n{}".format(datasets), fg="white")

    strat = Strategy()

    strat.use_dataset("quandl", columns=list(datasets))
    strat.run()
示例#4
0
def run(keywords, asset):
    """Runs strategy using Google Search Trends

        Example:
            trends 'btc' 'btc usd' 'btc price'
    """

    keywords = list(keywords)
    if asset:
        keywords.append(CONFIG["ASSET"].replace("_", " "))

    strat = Strategy()
    strat.use_dataset("google", columns=keywords)

    click.secho("Analysis Google Trends:\n{}".format(keywords), fg="white")

    strat.run()
示例#5
0
from kryptos.strategy import Strategy
from kryptos.strategy.indicators import technical
from catalyst.api import order_target_percent, order, record

import logbook

log = logbook.Logger("BUY_LOW_SELL_HIGH")
log.level = logbook.INFO

strat = Strategy("BUY_LOW_SELL_HIGH", data_frequency="daily")

rsi = technical.get_indicator("RSI")
rsi.update_param("timeperiod", 14)

strat.add_market_indicator(rsi)


@strat.init
def init(context):
    context.TARGET_POSITIONS = 30
    context.PROFIT_TARGET = 0.1
    context.SLIPPAGE_ALLOWED = 0.02
    context.cost_basis = None
    context.buy_increment = None
    context.i = 0


@strat.handle_data
def handle_data(context, data):
    context.i += 1
示例#6
0
from kryptos.strategy import Strategy
from kryptos.strategy.indicators import technical
from catalyst.api import order_target_percent, order, record, get_open_orders

import logbook

log = logbook.Logger("DUAL_MOVING_AVG")
log.level = logbook.INFO


strat = Strategy("DUAL_MOVING_AVG", data_frequency="daily")

#
# short_avg = technical.get_indicator('SMA')
# long_avg = technical.get_indicator('SMA')
#
# strat.add_market_indicator(short_avg)
# strat.add_market_indicator(long_avg)

strat.load_json_file('dual_moving_average.json')

@strat.init
def init(context):
    context.i = 0
    context.base_price = None


@strat.handle_data
def trade_logic(context, data):
    # define the windows for the moving averages
    short_window = 50
示例#7
0
# For this example, we're going to write a simple momentum script.  When the
# stock goes up quickly, we're going to buy; when it goes down quickly, we're
# going to sell.  Hopefully we'll ride the waves.
import time

import talib
from kryptos.strategy import Strategy
from kryptos.strategy.indicators import technical
from catalyst.api import order_target_percent, order, record, get_open_orders, symbol

import logbook



strat = Strategy("MEAN_REVERSION", data_frequency="daily")

strat.load_json_file('mean_reversion.json')

log = logbook.Logger(strat.name)


# To run an algorithm in Catalyst, you need two functions: initialize and
# handle_data.

@strat.initialize
def initialize(context):
    # This initialize function sets any data or variables that you'll use in
    # your algorithm.  For instance, you'll want to define the trading pair (or
    # trading pairs) you want to backtest.  You'll also want to define any
    # parameters or values you're going to use.
示例#8
0
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from logbook import Logger

from catalyst import run_algorithm
from catalyst.api import (
    record,
    symbol,
    order_target_percent,
)
from catalyst.exchange.utils.stats_utils import extract_transactions

from kryptos.strategy import Strategy

strat = Strategy('PAPER')

NAMESPACE = 'dual_moving_average'
log = Logger(NAMESPACE)


def initialize(context):
    context.i = 0
    context.asset = symbol('ltc_usd')
    context.base_price = None


def handle_data(context, data):
    # define the windows for the moving averages
    short_window = 50
    long_window = 200
示例#9
0
from kryptos.strategy import Strategy
from kryptos.strategy.indicators import technical
from catalyst.api import order_target_percent, record

import logbook

log = logbook.Logger("BEAR_MARKET")
log.level = logbook.INFO

strat = Strategy("BEAR_MARKET", data_frequency="daily")


@strat.init
def init(context):
    log.info("Algo is being initialzed, setting up context")
    context.i = 0
    context.IS_MARKET_BEAR = False


@strat.handle_data
def handle_data(context, data):
    log.debug("Processing new trading step")
    context.i += 1

    # Get price history for the last two months. Find peak, bottom, and last
    # prices for the period
    price_history = data.history(context.asset,
                                 fields="price",
                                 bar_count=60,
                                 frequency="1d")
    context.peak = price_history.max()
示例#10
0
from kryptos.strategy import Strategy
from kryptos.strategy.indicators import technical

import logbook

log = logbook.Logger('EXAMPLE')
log.level = logbook.INFO

strat = Strategy('Simple Stragey', data_frequency='daily')

bbands = technical.get_indicator('BBANDS')
bbands.update_param('matype', 'EMA')

stoch = technical.get_indicator('STOCH')

strat.add_market_indicator(bbands)
strat.add_market_indicator(stoch)

strat.use_dataset('quandl', columns=['MKTCP'])

strat.use_dataset('google', columns=['bitcoin futures'])
strat.add_data_indicator('google', 'relchange', col='bitcoin futures')

# trading config can be set via json or api
# Note that minute data is not supported for external datasets
# strat.trading_info['CAPITAL_BASE'] = 10000
# strat.trading_info['DATA_FREQ'] = 'minute'
# strat.trading_info['HISTORY_FREQ'] = '1m'
# strat.trading_info['START'] = '2017-12-10'
# strat.trading_info['END'] = '2017-12-11'
示例#11
0
import talib as ta
from kryptos.strategy import Strategy
from kryptos.strategy.indicators import technical
from catalyst.api import order_target_percent, order, record, get_open_orders

import logbook


strat = Strategy("BBANDS_PSAR", data_frequency="daily")

strat.load_json_file('bbands_psar.json')

log = logbook.Logger(strat.name)

@strat.init
def initialize(context):


    context.swallow_errors = True
    context.errors = []

    # Bars to look at per iteration should be bigger than SMA_SLOW
    # context.BARS = 365

    context.ORDER_SIZE = 0.5
    # context.SLIPPAGE_ALLOWED =


@strat.handle_data
def trade_logic(context, data):
    log.info("handling bar {}".format(data.current_dt))
示例#12
0
from kryptos.strategy import Strategy
from kryptos.strategy.signals import utils
from kryptos.utils import viz
import matplotlib.pyplot as plt

config = './sma_crossover.json'

strat = Strategy()

strat.load_json_file(config)

sma_fast = strat.indicator('SMA_FAST')
sma_slow = strat.indicator('SMA_SLOW')


@strat.signal_sell(override=True)
def signal_sell(context, data):
    return utils.cross_below(sma_fast.outputs.SMA_FAST,
                             sma_slow.outputs.SMA_SLOW)


@strat.signal_buy(override=True)
def signal_buy(context, data):
    return utils.cross_above(sma_fast.outputs.SMA_FAST,
                             sma_slow.outputs.SMA_SLOW)


@strat.analyze(num_plots=1)
def extra_plot(context, results, pos):
    viz.plot_column(results,
                    'SMA_FAST',
示例#13
0
def load_from_cli(
    market_indicators,
    machine_learning_models,
    dataset,
    columns,
    data_indicators,
    json_file,
    python_script,
):
    strat = Strategy()

    if python_script is not None:
        strat = get_strat(python_script)

    columns = list(columns)

    for i in market_indicators:
        click.echo(f"Attaching indicator: {i.upper()}")
        strat.add_market_indicator(i.upper())

    for i in machine_learning_models:
        click.echo(f"Attaching ml model: {i.upper()}")
        strat.add_ml_models(i.upper())

    # currently assigns -i indicator to the column provided at the same index
    if dataset is not None:
        click.echo(f"Using dataset: {dataset}")
        strat.use_dataset(dataset, columns)
        for i, ind in enumerate(data_indicators):
            strat.add_data_indicator(dataset, ind.upper(), col=columns[i])

    if json_file is not None:
        click.echo(f"Loading from json file {json_file}")
        strat.load_json_file(json_file)

    click.secho(strat.serialize(), fg="white")
    return strat
示例#14
0
from kryptos.strategy import Strategy
from kryptos.strategy.indicators import technical
from catalyst.api import order_target_percent, order, record, get_open_orders

import logbook

log = logbook.Logger("DYNAMIC_REBALANCE")
log.level = logbook.INFO

strat = Strategy("DYNAMIC_REBALANCE", data_frequency="daily")


@strat.init
def initialize(context):
    context.i = 0
    context.base_price = None


@strat.handle_data
def trade_logic(context, data):

    # Cancel any outstanding orders
    orders = get_open_orders(context.asset) or []
    for order in orders:
        cancel_order(order)

    # Define base price and make initial trades to achieve target investment ratio of 0.5
    order_target_percent(context.asset, 0.5)

    # Retrieve current asset price from pricing data
    price = data.current(context.asset, "price")
示例#15
0
from kryptos.strategy import Strategy
from kryptos.strategy.indicators import technical
from catalyst.api import order_target_value, record

import logbook

log = logbook.Logger("BUY_AND_HODL")
log.level = logbook.INFO


strat = Strategy("BUY_AND_HODL", data_frequency="daily")


@strat.init
def init(context):
    log.info("Algo is being initialzed, setting up context")
    context.TARGET_HODL_RATIO = 0.8
    context.RESERVE_RATIO = 1.0 - context.TARGET_HODL_RATIO

    context.starting_cash = context.portfolio.starting_cash
    context.target_hodl_value = context.TARGET_HODL_RATIO * context.starting_cash
    context.reserve_value = context.RESERVE_RATIO * context.starting_cash

    context.is_buying = True
    context.i = 0


@strat.handle_data
def handle_data(context, data):
    context.i += 1
    if context.i == 1:
示例#16
0
from kryptos.strategy import Strategy
from kryptos.strategy.indicators import technical
# from kryptos.strategy.signals import utils
# from kryptos.utils import viz
# import matplotlib.pyplot as plt
import logbook

log = logbook.Logger('EXAMPLE')
log.level = logbook.INFO

strat = Strategy('MacdFix')

macdfix_9 = technical.get_indicator('MACDFIX', label='MACDFIX_9')

macdfix_18 = technical.get_indicator('MACDFIX', label='MACDFIX_18')
macdfix_18.update_param('signalperiod', 18)

strat.add_market_indicator(macdfix_9)
strat.add_market_indicator(macdfix_18)


@strat.init
def init(context):
    log.info('Algo is being initialzed, setting up context')
    context.i = 0


@strat.handle_data
def handle_data(context, data):
    log.debug('Processing new trading step')
    context.i += 1