Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
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)
# 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
asset_df = market_data[0]
spot_df = market_data[1]
spot_df2 = market_data[2]
basket_dict = market_data[3]
# contract_value_df = market_data[4]
# optional database output
contract_value_df = None
if len(market_data) == 5:
contract_value_df = market_data[4]
if hasattr(br, 'tech_params'):
tech_params = br.tech_params
else:
tech_params = TechParams()
cum_results = pandas.DataFrame(index=asset_df.index)
port_leverage = pandas.DataFrame(index=asset_df.index)
from collections import OrderedDict
ret_stats_results = OrderedDict()
bask_results = {}
bask_keys = basket_dict.keys()
# each portfolio key calculate returns - can put parts of the portfolio in the key
if market_constants.backtest_thread_no[market_constants.generic_plat] > 1 and run_in_parallel:
swim_pool = SwimPool(multiprocessing_library=market_constants.multiprocessing_library)
pool = swim_pool.create_pool(thread_technique=market_constants.backtest_thread_technique,
def __init__(self):
super(MarketDataRequest, self).__init__()
self.__signal_name = None
# output parameters for backtest (should we add returns statistics on legends, write CSVs with returns etc.)
self.__plot_start = None
self.__calc_stats = True
self.__write_csv = False
self.__write_csv_pnl = False
self.__plot_interim = False
self.__include_benchmark = False
self.__tech_params = TechParams()
# default parameters for portfolio level vol adjustment
self.__portfolio_vol_adjust = False
self.__portfolio_vol_period_shift = 0
self.__portfolio_vol_rebalance_freq = None
self.__portfolio_vol_resample_freq = None
self.__portfolio_vol_resample_type = 'mean'
self.__portfolio_vol_target = 0.1 # 10% vol target
self.__portfolio_vol_max_leverage = None
self.__portfolio_vol_periods = 20
self.__portfolio_vol_obs_in_year = 252
# default parameters for signal level vol adjustment
self.__signal_vol_adjust = False
self.__signal_vol_period_shift = 0
self.__signal_vol_rebalance_freq = None
from findatapy.util.loggermanager import LoggerManager
logger = LoggerManager().getLogger(__name__)
chart = Chart(engine='bokeh')
tech_ind = TechIndicator()
# Load data from local file
df = pd.read_csv("/Volumes/Data/s&p500.csv", index_col=0, parse_dates=['Date'],
date_parser=lambda x: pd.datetime.strptime(x, '%Y-%m-%d'))
# Calculate Volume Weighted Average Price (VWAP)
tech_params = TechParams()
tech_ind.create_tech_ind(df, 'VWAP', tech_params)
df = tech_ind.get_techind()
print(df)
style = Style()
style.title = 'S&P500 VWAP'
style.scale_factor = 2
df = tech_ind.get_techind()
chart.plot(df, style=style)
# downloaded S&P500
md_request = MarketDataRequest(
start_date = "01 Jan 2000", # start date
data_source = 'quandl', # use Quandl as data source
tickers = ['S&P500'],
fields = ['close', 'open', 'high', 'low'], # which fields to download
vendor_tickers = ['YAHOO/INDEX_GSPC'], # ticker (Bloomberg)
vendor_fields = ['close', 'open', 'high', 'low'], # which Bloomberg fields to download
cache_algo = 'internet_load_return') # how to return data
df = market.fetch_market(md_request)
print(df)
tech_params = TechParams()
tech_params.atr_period = 14
tech_ind.create_tech_ind(df, 'ATR', tech_params)
style = Style()
style.title = 'S&P500 ATR'
style.scale_factor = 2
style.file_output = "sp500.png"
style.source = 'Quandl/Yahoo'
df = tech_ind.get_techind()
chart.plot(df, style=style)