How to use finmarketpy - 10 common examples

To help you get started, we’ve selected a few finmarketpy examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github cuemacro / finmarketpy / finmarketpy_examples / backtest_example.py View on Github external
# for logging
    from findatapy.util import LoggerManager

    # for signal generation
    from finmarketpy.economics import TechIndicator, TechParams

    # for plotting
    from chartpy import Chart, Style

    logger = LoggerManager().getLogger(__name__)

    import datetime

    backtest = Backtest()
    br = BacktestRequest()
    fxconv = FXConv()

    # get all asset data
    br.start_date = "02 Jan 1990"
    br.finish_date = datetime.datetime.utcnow()
    br.spot_tc_bp = 2.5  # 2.5 bps bid/ask spread
    br.ann_factor = 252

    tech_params = TechParams();
    tech_params.sma_period = 200;
    indicator = 'SMA'
    tech_params.only_allow_longs = True
    # tech_params.only_allow_shorts = True

    # pick EUR/USD
    # note: we are calculating returns from spot (it is much better to use to total return
github cuemacro / finmarketpy / finmarketpy_examples / backtest_example.py View on Github external
# for logging
    from findatapy.util.loggermanager import LoggerManager

    # for signal generation
    from finmarketpy.economics import TechIndicator, TechParams

    # for plotting
    from chartpy import Chart, Style

    logger = LoggerManager().getLogger(__name__)

    import datetime

    backtest = Backtest()
    br = BacktestRequest()
    fxconv = FXConv()

    # get all asset data
    br.start_date = "02 Jan 1990"
    br.finish_date = datetime.datetime.utcnow()
    br.spot_tc_bp = 2.5  # 2.5 bps bid/ask spread
    br.ann_factor = 252

    # have vol target for each signal
    br.signal_vol_adjust = True
    br.signal_vol_target = 0.05
    br.signal_vol_max_leverage = 3
    br.signal_vol_periods = 60
    br.signal_vol_obs_in_year = 252
    br.signal_vol_rebalance_freq = 'BM'
    br.signal_vol_resample_freq = None
github cuemacro / finmarketpy / finmarketpy / backtest / backtestengine.py View on Github external
from findatapy.util import SwimPool
from findatapy.util import LoggerManager

import pickle
#import zlib
#import lz4framed    # conda install -c conda-forge py-lz4framed

# make blosc optional (only when trying to run backtests in parallel)
try:
    import blosc
except:
    pass

import pickle

market_constants = MarketConstants()


class Backtest(object):
    """Conducts backtest for strategies trading assets. Assumes we have an input of total returns. Reports historical return statistics
    and returns time series.

    """

    def __init__(self):
        self._pnl = None
        self._portfolio = None
        return

    def calculate_diagnostic_trading_PnL(self, asset_a_df, signal_df, further_df=[], further_df_labels=[]):
        """Calculates P&L table which can be used for debugging purposes,
github cuemacro / finmarketpy / finmarketpy_examples / backtest_example.py View on Github external
logger = LoggerManager().getLogger(__name__)

    import datetime

    backtest = Backtest()
    br = BacktestRequest()
    fxconv = FXConv()

    # get all asset data
    br.start_date = "02 Jan 1990"
    br.finish_date = datetime.datetime.utcnow()
    br.spot_tc_bp = 2.5  # 2.5 bps bid/ask spread
    br.ann_factor = 252

    tech_params = TechParams();
    tech_params.sma_period = 200;
    indicator = 'SMA'
    tech_params.only_allow_longs = True
    # tech_params.only_allow_shorts = True

    # pick EUR/USD
    # note: we are calculating returns from spot (it is much better to use to total return
    # indices for FX, which include carry)
    logger.info("Loading asset data...")

    md_request = MarketDataRequest(
        start_date="01 Jan 1989",  # start date
        finish_date=datetime.date.today(),  # finish date
        freq='daily',  # daily data
        data_source='quandl',  # use Quandl as data source
        tickers=['EURUSD'],  # ticker (findatapy)
github cuemacro / finmarketpy / finmarketpy / backtest / tradeanalysis.py View on Github external
def _run_strategy(self, trading_model, asset_df, spot_df, spot_df2, br, contract_value_df, pretty_portfolio_name):

        logger = LoggerManager().getLogger(__name__)

        logger.info("Calculating... " + str(pretty_portfolio_name))

        signal_df = trading_model.construct_signal(spot_df, spot_df2, br.tech_params, br, run_in_parallel=False)

        backtest = Backtest()

        backtest.calculate_trading_PnL(br, asset_df, signal_df, contract_value_df, False)
        ret_stats = backtest.portfolio_pnl_ret_stats()
        stats = str(backtest.portfolio_pnl_desc()[0])

        port = backtest.portfolio_cum().resample('B').mean()
        port.columns = [str(pretty_portfolio_name) + ' ' + stats]

        return port, ret_stats
github cuemacro / finmarketpy / finmarketpy_examples / backtest_example.py View on Github external
from findatapy.util.fxconv import FXConv

    # for logging
    from findatapy.util.loggermanager import LoggerManager

    # for signal generation
    from finmarketpy.economics import TechIndicator, TechParams

    # for plotting
    from chartpy import Chart, Style

    logger = LoggerManager().getLogger(__name__)

    import datetime

    backtest = Backtest()
    br = BacktestRequest()
    fxconv = FXConv()

    # get all asset data
    br.start_date = "02 Jan 1990"
    br.finish_date = datetime.datetime.utcnow()
    br.spot_tc_bp = 2.5  # 2.5 bps bid/ask spread
    br.ann_factor = 252

    # have vol target for each signal
    br.signal_vol_adjust = True
    br.signal_vol_target = 0.05
    br.signal_vol_max_leverage = 3
    br.signal_vol_periods = 60
    br.signal_vol_obs_in_year = 252
    br.signal_vol_rebalance_freq = 'BM'
github cuemacro / finmarketpy / finmarketpy_examples / backtest_example.py View on Github external
from findatapy.timeseries import Calculations

    # for logging
    from findatapy.util import LoggerManager

    # for signal generation
    from finmarketpy.economics import TechIndicator, TechParams

    # for plotting
    from chartpy import Chart, Style

    logger = LoggerManager().getLogger(__name__)

    import datetime

    backtest = Backtest()
    br = BacktestRequest()
    fxconv = FXConv()

    # get all asset data
    br.start_date = "02 Jan 1990"
    br.finish_date = datetime.datetime.utcnow()
    br.spot_tc_bp = 2.5  # 2.5 bps bid/ask spread
    br.ann_factor = 252

    tech_params = TechParams();
    tech_params.sma_period = 200;
    indicator = 'SMA'
    tech_params.only_allow_longs = True
    # tech_params.only_allow_shorts = True

    # pick EUR/USD
github cuemacro / finmarketpy / finmarketpy / backtest / backtestengine.py View on Github external
spot_df2 : pandas.DataFrame
            Secondary Market time series for generated signals (can be of different frequency)

        tech_params : TechParams
            Parameters for generating signals

        contract_value_df : pandas.DataFrame
            Dataframe with the contract sizes for each asset

        Returns
        -------
        portfolio_cum : pandas.DataFrame
        backtest : Backtest
        """
        backtest = Backtest()

        logger = LoggerManager().getLogger(__name__)

        logger.info("Calculating trading signals for " + key + "...")

        signal = self.construct_signal(spot_df, spot_df2, tech_params, br, run_in_parallel=run_in_parallel)

        logger.info("Calculated trading signals for " + key)

        backtest.calculate_trading_PnL(br, asset_df, signal,
                                       contract_value_df,
                                       run_in_parallel)  # calculate P&L (and adjust signals for vol etc)

        if br.write_csv: backtest.pnl_cum().to_csv(self.DUMP_CSV + key + ".csv")

        if br.calc_stats:
github cuemacro / finmarketpy / finmarketpy / backtest / tradeanalysis.py View on Github external
import datetime

# import matplotlib
# import matplotlib.pyplot as plt
import pandas
import copy

from chartpy import Chart, Style, ChartConstants
from findatapy.timeseries import Calculations, Timezone
from findatapy.util.loggermanager import LoggerManager
from finmarketpy.backtest import Backtest

from finmarketpy.util.marketconstants import MarketConstants
from findatapy.util.swimpool import SwimPool

market_constants = MarketConstants()


class TradeAnalysis(object):
    """Applies some basic trade analysis for a trading strategy (as defined by TradingModel). Use PyFolio to create some
    basic trading statistics. Also allows you test multiple parameters for a specific strategy (like TC).

    """

    def __init__(self, engine=ChartConstants().chartfactory_default_engine):
        # self.logger = LoggerManager().getLogger(__name__)
        self.DUMP_PATH = 'output_data/' + datetime.date.today().strftime("%Y%m%d") + ' '
        self.DEFAULT_PLOT_ENGINE = engine
        self.chart = Chart(engine=self.DEFAULT_PLOT_ENGINE)

        return
github cuemacro / finmarketpy / finmarketpy_examples / backtest_example.py View on Github external
# get all asset data
    br.start_date = "02 Jan 1990"
    br.finish_date = datetime.datetime.utcnow()
    br.spot_tc_bp = 2.5  # 2.5 bps bid/ask spread
    br.ann_factor = 252

    # have vol target for each signal
    br.signal_vol_adjust = True
    br.signal_vol_target = 0.05
    br.signal_vol_max_leverage = 3
    br.signal_vol_periods = 60
    br.signal_vol_obs_in_year = 252
    br.signal_vol_rebalance_freq = 'BM'
    br.signal_vol_resample_freq = None

    tech_params = TechParams();
    tech_params.sma_period = 200;
    indicator = 'SMA'

    # pick USD crosses in G10 FX
    # note: we are calculating returns from spot (it is much better to use to total return
    # indices for FX, which include carry)
    logger.info("Loading asset data...")

    tickers = ['EURUSD', 'USDJPY', 'GBPUSD', 'AUDUSD', 'USDCAD',
               'NZDUSD', 'USDCHF', 'USDNOK', 'USDSEK']

    vendor_tickers = ['FRED/DEXUSEU', 'FRED/DEXJPUS', 'FRED/DEXUSUK', 'FRED/DEXUSAL', 'FRED/DEXCAUS',
                      'FRED/DEXUSNZ', 'FRED/DEXSZUS', 'FRED/DEXNOUS', 'FRED/DEXSDUS']

    md_request = MarketDataRequest(
        start_date="01 Jan 1989",  # start date