Navigation

    Quantiacs Community

    • Register
    • Login
    • Search
    • Categories
    • News
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    1. Home
    2. illustrious.felice
    3. Topics
    • Profile
    • Following 0
    • Followers 0
    • Topics 20
    • Posts 61
    • Best 8
    • Groups 0
    • Blog

    Topics created by illustrious.felice

    • illustrious.felice

      Strategy trades illiquid instruments
      Support • • illustrious.felice

      5
      0
      Votes
      5
      Posts
      238
      Views

      V

      @illustrious-felice Hello. The reason you're still seeing a large number of tickers (e.g., around 300) even after applying the filter is that the "best" instrument by Sharpe ratio changes over time. The rank_assets_by function returns a time-dependent mask, selecting the top N assets at each time step. So the total number of unique assets that were selected at any point in time may be much larger than top_assets.

      This is expected behavior.

      To illustrate this more clearly, let's consider a minimal working example that selects only 1 top asset at each point in time and shows all the intermediate steps:

      import qnt.data as qndata import qnt.ta as qnta import qnt.stats as qnstats import qnt.output as qnout import qnt.filter as qnfilter import xarray as xr import pandas as pd top_assets = 1 data = qndata.stocks.load_spx_data(min_date="2005-06-01") weights = data.sel(field="is_liquid") stats_per_asset = qnstats.calc_stat(data, weights, per_asset=True) sharpe_ratio = stats_per_asset.sel(field="sharpe_ratio") asset_filter = qnfilter.rank_assets_by(data, sharpe_ratio, top_assets, ascending=False) weights = weights * asset_filter stats = qnstats.calc_stat(data, weights.sel(time=slice("2005-06-01", None))) display(asset_filter.to_pandas().tail()) display(stats.to_pandas().tail()) display(sharpe_ratio.to_pandas().tail()) display(weights.to_pandas().tail())

      If you want to see which asset was the best on specific dates, you can do something like this:

      dates = ["2015-01-15", "2020-01-15", "2025-01-15"] records = [] for date_str in dates: best_mask = asset_filter.sel(time=date_str) assets = best_mask.where(best_mask > 0, drop=True).asset.values srs = sharpe_ratio.sel(time=date_str, asset=assets).values for a, s in zip(assets, srs): records.append({"time": date_str, "asset": a.item(), "sharpe_ratio": float(s)}) df = pd.DataFrame(records).set_index("time") display(df) asset sharpe_ratio time 2025-05-22 NYS:HRL 1.084683 2025-05-22 NAS:KDP 1.093528 2025-05-22 NAS:AAPL 0.968039

      Or simply for a single date:

      date = "2020-05-22" best_mask = asset_filter.sel(time=date) best_assets = best_mask.where(best_mask > 0, drop=True).asset best_sr = sharpe_ratio.sel(time=date, asset=best_assets) print(best_sr.to_pandas())

      This shows clearly that only one asset is selected at each time step, but over the full time range, many different assets can appear in the top list depending on how their Sharpe ratios change.

    • illustrious.felice

      Accessing Quantiacs takes too long
      Support • • illustrious.felice

      5
      1
      Votes
      5
      Posts
      311
      Views

      illustrious.felice

      @support Hello. My strategy has the id #16934018 and was submitted in early May, but pnl OS has not been updated yet. Please check this issue. Thank you.

    • illustrious.felice

      Test out sample performance
      Support • • illustrious.felice

      2
      0
      Votes
      2
      Posts
      172
      Views

      support

      @illustrious-felice Hi, you can in the notebook, not in the submission area because of resource reasons.

    • illustrious.felice

      Extend strategy submission time Q21
      Support • • illustrious.felice

      2
      0
      Votes
      2
      Posts
      177
      Views

      support

      @illustrious-felice Hi, sorry for the delay, we extended the deadline.

      As far as looking forward is going on, this does not take place during the real-time simulation, as the code cannot access by construction the new data. This is true even if the code is written in a single-pass way.

      If the user uses a single-pass implementation, however, looking forward in the in-sample period is possible of course, there it is responsibility of the user to prevent it. Single-pass has access to all the time series.

    • illustrious.felice

      TypeError: __init__() got an unexpected keyword argument 'max_value'
      Strategy help • • illustrious.felice

      2
      0
      Votes
      2
      Posts
      248
      Views

      support

      @illustrious-felice
      Hello, sorry for late reply, can you please let us know about the progressbar2 version installed from environment you are currently using? Be sure that "progressbar2" package is installed and not "progressbar".

      Best regards,

    • illustrious.felice

      RuntimeError: expand(torch.DoubleTensor{[694, 6]}, size=[694]): the number of sizes provided (1) must be greater or equal to the number of dimensions in the tensor (2)
      Strategy help • • illustrious.felice

      4
      0
      Votes
      4
      Posts
      234
      Views

      illustrious.felice

      @support Thank you so much. I have resolved this error

    • illustrious.felice

      backtest_ml has too long a run time
      Strategy help • • illustrious.felice

      14
      1
      Votes
      14
      Posts
      890
      Views

      V

      @illustrious-felice

      Incorporating seed initialization into your PyTorch code ensures reproducibility by making the random number generation predictable. This involves setting seeds for the PyTorch engine, NumPy, and the Python random module if you're using it. Below, I'll show you how to integrate seed initialization into your existing code. Remember, while this can make your experiments more reproducible, it does not guarantee identical results across different hardware or PyTorch versions due to the inherent nondeterminism in some GPU operations.

      import xarray as xr # xarray for data manipulation import qnt.data as qndata # functions for loading data import qnt.backtester as qnbt # built-in backtester import qnt.ta as qnta # technical analysis library import numpy as np import pandas as pd import torch from torch import nn, optim import random # Seed initialization function def set_seed(seed_value=42): """Set seed for reproducibility.""" random.seed(seed_value) np.random.seed(seed_value) torch.manual_seed(seed_value) torch.cuda.manual_seed(seed_value) torch.cuda.manual_seed_all(seed_value) # if you are using multi-GPU. torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False # Set the seed for reproducibility set_seed(42) asset_name_all = ['NAS:AAPL', 'NAS:AMZN', 'NAS:MSFT'] class LSTM(nn.Module): """ Class to define our LSTM network. """ def __init__(self, input_dim=3, hidden_layers=64): super(LSTM, self).__init__() self.hidden_layers = hidden_layers self.lstm1 = nn.LSTMCell(input_dim, self.hidden_layers) self.lstm2 = nn.LSTMCell(self.hidden_layers, self.hidden_layers) self.linear = nn.Linear(self.hidden_layers, 1) def forward(self, y, future_preds=0): outputs = [] n_samples = y.size(0) h_t = torch.zeros(n_samples, self.hidden_layers, dtype=torch.float32) c_t = torch.zeros(n_samples, self.hidden_layers, dtype=torch.float32) h_t2 = torch.zeros(n_samples, self.hidden_layers, dtype=torch.float32) c_t2 = torch.zeros(n_samples, self.hidden_layers, dtype=torch.float32) for time_step in range(y.size(1)): x_t = y[:, time_step, :] # Ensure x_t is [batch, input_dim] h_t, c_t = self.lstm1(x_t, (h_t, c_t)) h_t2, c_t2 = self.lstm2(h_t, (h_t2, c_t2)) output = self.linear(h_t2) outputs.append(output.unsqueeze(1)) outputs = torch.cat(outputs, dim=1).squeeze(-1) return outputs def get_model(): model = LSTM(input_dim=3) return model def get_features(data): close_price = data.sel(field="close").ffill('time').bfill('time').fillna(1) open_price = data.sel(field="open").ffill('time').bfill('time').fillna(1) high_price = data.sel(field="high").ffill('time').bfill('time').fillna(1) log_close = np.log(close_price) log_open = np.log(open_price) features = xr.concat([log_close, log_open, high_price], "feature") return features def get_target_classes(data): price_current = data.sel(field='close') price_future = qnta.shift(price_current, -1) class_positive = 1 # prices goes up class_negative = 0 # price goes down target_price_up = xr.where(price_future > price_current, class_positive, class_negative) return target_price_up def load_data(period): return qndata.stocks.load_ndx_data(tail=period, assets=asset_name_all) def train_model(data): features_all = get_features(data) target_all = get_target_classes(data) models = dict() for asset_name in asset_name_all: model = get_model() target_cur = target_all.sel(asset=asset_name).dropna('time', 'any') features_cur = features_all.sel(asset=asset_name).dropna('time', 'any') target_for_learn_df, feature_for_learn_df = xr.align(target_cur, features_cur, join='inner') criterion = nn.MSELoss() optimiser = optim.LBFGS(model.parameters(), lr=0.08) epochs = 1 for i in range(epochs): def closure(): optimiser.zero_grad() feature_data = feature_for_learn_df.transpose('time', 'feature').values in_ = torch.tensor(feature_data, dtype=torch.float32).unsqueeze(0) out = model(in_) target = torch.zeros(1, len(target_for_learn_df.values)) target[0, :] = torch.tensor(np.array(target_for_learn_df.values)) loss = criterion(out, target) loss.backward() return loss optimiser.step(closure) models[asset_name] = model return models def predict(models, data): weights = xr.zeros_like(data.sel(field='close')) for asset_name in asset_name_all: features_all = get_features(data) features_cur = features_all.sel(asset=asset_name).dropna('time', 'any') if len(features_cur.time) < 1: continue feature_data = features_cur.transpose('time', 'feature').values in_ = torch.tensor(feature_data, dtype=torch.float32).unsqueeze(0) out = models[asset_name](in_) prediction = out.detach()[0] weights.loc[dict(asset=asset_name, time=features_cur.time.values)] = prediction return weights weights = qnbt.backtest_ml( load_data=load_data, train=train_model, predict=predict, train_period=55, retrain_interval=55, retrain_interval_after_submit=1, predict_each_day=False, competition_type='stocks_nasdaq100', lookback_period=55, start_date='2024-01-01', build_plots=True )

      I think I won't be available next week. If you have any more questions, don’t expect an answer from me next week.

    • illustrious.felice

      Translating code from Quantiacs Legacy
      Support • • illustrious.felice

      6
      0
      Votes
      6
      Posts
      230
      Views

      illustrious.felice

      @vyacheslav_b Thank you so much

    • illustrious.felice

      Sharpe decreases when submitting strategy
      Support • • illustrious.felice

      6
      0
      Votes
      6
      Posts
      227
      Views

      illustrious.felice

      @vyacheslav_b Thank you so much

    • illustrious.felice

      IndentationError: unindent does not match any outer indentation level
      Support • • illustrious.felice

      5
      0
      Votes
      5
      Posts
      183
      Views

      support

      @illustrious-felice Hi, just insist and test other ideas, it is not easy but you will manage!

    • illustrious.felice

      What is forward looking and why it's effective badly to strategy?
      Strategy help • • illustrious.felice

      8
      0
      Votes
      8
      Posts
      477
      Views

      support

      @illustrious-felice Hi, that is not automatic as all trades are punished by slippage, and that is a subtraction from profits irrespective on the sign of the weights.

    • illustrious.felice

      Difference between relative_return & mean_return
      Support • • illustrious.felice

      6
      1
      Votes
      6
      Posts
      211
      Views

      illustrious.felice

      @vyacheslav_b Thank you so much

    • illustrious.felice

      Please create the program "Quantiacs Tips"
      Strategy help • • illustrious.felice

      3
      0
      Votes
      3
      Posts
      181
      Views

      illustrious.felice

      @support Thank you for your feedback. I also hope Quantiacs updates new strategy examples on how to use technical analysis (besides sma, trix_ema, atr_lwma,...), and strategies on using ML/DL models effectively (not an example that strategy forward-looking),...

      Hopefully in the future Quantiacs will release new data sets such as news, sentiment, macro, options,... Create new contests that allow merging strategies to build portfolios,...

      Hopefully, Quantiacs will continue to grow. Sincere thanks to Quantiacs for creating extremely high-quality contests.

    • illustrious.felice

      Not enough bid information when submit
      Support • • illustrious.felice

      5
      0
      Votes
      5
      Posts
      204
      Views

      illustrious.felice

      @support Thanks for your respond. Now I understand the cause and fixed it

    • illustrious.felice

      How to select and combine strategies to optimize your portfolio
      Strategy help • • illustrious.felice

      3
      0
      Votes
      3
      Posts
      183
      Views

      illustrious.felice

      @support. Thank you. So as I understand it, I will give higher weight to strategies with lower correlation and vice versa, right? According to your answer, I understand that I can also give high weight to low-volatility strategies and vice versa. So what about equal risk portfolio? In your opinion, is this an effective way to optimize your portfolio?

    • illustrious.felice

      How to use complex indicator in fundamental data
      Support • • illustrious.felice

      7
      0
      Votes
      7
      Posts
      314
      Views

      illustrious.felice

      @support Ohh, I understand. Thank you for your support.

    • illustrious.felice

      Strategies deleted
      Support • • illustrious.felice

      3
      0
      Votes
      3
      Posts
      172
      Views

      illustrious.felice

      @support Thank you very much. Please delete all my strategies in the deleted section.

    • illustrious.felice

      Technique to reduce max_drawdown
      Strategy help • • illustrious.felice

      3
      0
      Votes
      3
      Posts
      231
      Views

      illustrious.felice

      @magenta-kabuto Thank you very much for your advice. I will research to apply your suggestions to the algorithm

    • Documentation
    • About
    • Career
    • My account
    • Privacy policy
    • Terms and Conditions
    • Cookies policy
    Home
    Copyright © 2014 - 2021 Quantiacs LLC.
    Powered by NodeBB | Contributors