Is it possible to combine stocks with crypto?
-
Hello,
I'm testing combining crypto with stocks for Q21 but I'm getting an error. We hope to help.
Thank you.
Below is my code
# Import basic libraries. import xarray as xr import pandas as pd import numpy as np # Import Quantiacs libraries. import qnt.data as qndata # load and manipulate data import qnt.output as qnout # manage output import qnt.backtester as qnbt # backtester import qnt.stats as qnstats # statistical functions for analysis import qnt.graph as qngraph # graphical tools import qnt.ta as qnta # indicators library import qnt.xr_talib as xr_talib # indicators library def load_data(period): futures = qndata.futures.load_data(tail=period).isel(asset=0) stocks = qndata.stocks.load_ndx_data(tail=period) crypto= qndata.crypto.load_data(tail=period) return {"futures": futures, "stocks": stocks, "crypto": crypto}, futures.time.values def window(data, max_date: np.datetime64, lookback_period: int): min_date = max_date - np.timedelta64(lookback_period, "D") return { "futures": data["futures"].sel(time=slice(min_date, max_date)), "stocks": data["stocks"].sel(time=slice(min_date, max_date)), "crypto": data["crypto"].sel(time=slice(min_date, max_date)), } def strategy(data): close_futures = data["crypto"].sel(field="close") close_stocks = data["stocks"].sel(field="close") sma20 = qnta.sma(close_futures, 20).isel(time=-1) sma20_stocks = qnta.sma(close_stocks, 20).isel(time=-1) is_liquid = data["stocks"].sel(field="is_liquid").isel(time=-1) weights = xr.where(sma20 < sma20_stocks, 1, -1) weights = weights * is_liquid weights = weights / 100.0 return weights qnbt.backtest( competition_type= "stocks_nasdaq100", load_data= load_data, lookback_period= 90, start_date= "2006-01-01", strategy= strategy, window= window )
-
@newbiequant96 said in Is it possible to combine stocks with crypto?:
Import basic libraries.
import xarray as xr
import pandas as pd
import numpy as npImport Quantiacs libraries.
import qnt.data as qndata # load and manipulate data
import qnt.output as qnout # manage output
import qnt.backtester as qnbt # backtester
import qnt.stats as qnstats # statistical functions for analysis
import qnt.graph as qngraph # graphical tools
import qnt.ta as qnta # indicators library
import qnt.xr_talib as xr_talib # indicators librarydef load_data(period):
futures = qndata.futures.load_data(tail=period).isel(asset=0)
stocks = qndata.stocks.load_ndx_data(tail=period)
crypto= qndata.crypto.load_data(tail=period)
return {"futures": futures, "stocks": stocks, "crypto": crypto}, futures.time.valuesdef window(data, max_date: np.datetime64, lookback_period: int):
min_date = max_date - np.timedelta64(lookback_period, "D")
return {
"futures": data["futures"].sel(time=slice(min_date, max_date)),
"stocks": data["stocks"].sel(time=slice(min_date, max_date)),
"crypto": data["crypto"].sel(time=slice(min_date, max_date)),
}def strategy(data):
close_futures = data["crypto"].sel(field="close")
close_stocks = data["stocks"].sel(field="close")
sma20 = qnta.sma(close_futures, 20).isel(time=-1)
sma20_stocks = qnta.sma(close_stocks, 20).isel(time=-1)
is_liquid = data["stocks"].sel(field="is_liquid").isel(time=-1)
weights = xr.where(sma20 < sma20_stocks, 1, -1)
weights = weights * is_liquid
weights = weights / 100.0
return weightsqnbt.backtest(
competition_type= "stocks_nasdaq100",
load_data= load_data,
lookback_period= 90,
start_date= "2006-01-01",
strategy= strategy,
window= window
)Hello. I don't have a good solution because cryptocurrency data is not available in 2006.
I changed the cryptocurrency loading to daily data, as your example used hourly data. I aligned the data by dates similar to this example: Example - Predicting NASDAQ 100 Stocks Using the SPX Index https://github.com/quantiacs/strategy-predict-NASDAQ100-use-SPX/blob/master/strategy.ipynb
This code should work correctly.
# Import basic libraries. import xarray as xr import pandas as pd import numpy as np # Import Quantiacs libraries. import qnt.data as qndata # load and manipulate data import qnt.output as qnout # manage output import qnt.backtester as qnbt # backtester import qnt.stats as qnstats # statistical functions for analysis import qnt.graph as qngraph # graphical tools import qnt.ta as qnta # indicators library import qnt.xr_talib as xr_talib # indicators library def load_data(period): futures = qndata.futures.load_data(tail=period, assets=["F_DX"]).isel(asset=0) stocks = qndata.stocks.load_ndx_data(tail=period) futures = xr.align(futures, stocks.isel(field=0), join='right')[0] try: crypto = qndata.cryptodaily.load_data(tail=period, assets=["BTC"]).isel(asset=0) crypto = xr.align(crypto, stocks.isel(field=0), join='right')[0] except Exception as e: print(f"Failed to load crypto data: {e}") crypto = futures # Fallback to futures data if crypto data loading fails return {"futures": futures, "stocks": stocks, "crypto": crypto}, stocks.time.values def window(data, max_date: np.datetime64, lookback_period: int): min_date = max_date - np.timedelta64(lookback_period, "D") return { "futures": data["futures"].sel(time=slice(min_date, max_date)), "stocks": data["stocks"].sel(time=slice(min_date, max_date)), "crypto": data["crypto"].sel(time=slice(min_date, max_date)), } def strategy(data): # close_futures = data["futures"].sel(field="close") close_crypto = data["crypto"].sel(field="close") close_stocks = data["stocks"].sel(field="close") sma20 = qnta.sma(close_crypto, 20) sma20_stocks = qnta.sma(close_stocks, 20) is_liquid = data["stocks"].sel(field="is_liquid") weights = xr.where(sma20 < sma20_stocks, 1, -1) weights = weights * is_liquid weights = weights / 100.0 return weights qnbt.backtest( competition_type="stocks_nasdaq100", load_data=load_data, lookback_period=90, start_date="2006-01-01", strategy=strategy, window=window )
-
@vyacheslav_b Thank you very much for your support.
I would like to ask, if I want to filter out the crypto codes with the highest sharpness, what should I do? Thank you. I tried using the get_best_instruments function but it didn't work
import qnt.stats as qnstats # data = qndata.stocks.load_ndx_data(tail = 17*365, dims = ("time", "field", "asset")) data = qndata.stocks.load_ndx_data(min_date="2005-01-01") def get_best_instruments(data, weights, top_size): # compute statistics: stats_per_asset = qnstats.calc_stat(data, weights, per_asset=True) # calculate ranks of assets by "sharpe_ratio": ranks = (-stats_per_asset.sel(field="sharpe_ratio")).rank("asset") # select top assets by rank "top_period" days ago: top_period = 1 rank = ranks.isel(time=-top_period) top = rank.where(rank <= top_size).dropna("asset").asset # select top stats: top_stats = stats_per_asset.sel(asset=top.values) # print results: print("SR tail of the top assets:") display(top_stats.sel(field="sharpe_ratio").to_pandas().tail()) print("avg SR = ", top_stats[-top_period:].sel(field="sharpe_ratio").mean("asset")[-1].item()) display(top_stats) return top_stats.coords["asset"].values get_best_instruments(data, weights, 10)