<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Acess previous weights]]></title><description><![CDATA[<p dir="auto">Hello all,<br />
I hope everyone is doing well.<br />
I have a question regarding the access of previous weights during the backtesting/prediction phase. The following is my code:<br />
<img src="/community/assets/uploads/files/1712276819319-bildschirmfoto-2024-04-05-um-02.24.16.png" alt="Bildschirmfoto 2024-04-05 um 02.24.16.png" class="img-responsive img-markdown" /><br />
I would like to include the last row (commented out) to improve the weights, but as my code predicts each time step I think the previous predictions are not saved.<br />
Is there a better way to write the predictions or in general have the previous weights stored, in order to apply the lower slippage function?<br />
thx a lot.<br />
Regards</p>
]]></description><link>http://quantiacs.com/community/topic/555/acess-previous-weights</link><generator>RSS for Node</generator><lastBuildDate>Tue, 10 Mar 2026 09:53:10 GMT</lastBuildDate><atom:link href="http://quantiacs.com/community/topic/555.rss" rel="self" type="application/rss+xml"/><pubDate>Fri, 05 Apr 2024 00:31:45 GMT</pubDate><ttl>60</ttl><item><title><![CDATA[Reply to Acess previous weights on Fri, 24 May 2024 07:27:44 GMT]]></title><description><![CDATA[<p dir="auto"><a class="plugin-mentions-user plugin-mentions-a" href="http://quantiacs.com/community/uid/3328">@blackpearl</a> Hello. I don’t use machine learning in trading, and I don’t have similar examples. If you know Python and know how to develop such systems, or if you use ChatGPT (or similar tools) for development, you should not have difficulties modifying existing examples. You will need to change the model training and prediction functions.</p>
<p dir="auto">One of the competitive advantages of the Quantiacs platform is the ability to test machine learning models from a financial performance perspective.</p>
<p dir="auto">I haven’t encountered similar tools. Typically, models are evaluated using metrics like F1 score and cross-validation (for example, in the classification task of predicting whether the price will rise tomorrow).</p>
<p dir="auto">However, there are several problems:</p>
<ul>
<li>It is unclear how much profit this model can generate. In real trading, there will be commissions, slippage, data errors, and the F1 score doesn’t account for these factors.</li>
<li>It is possible to inadvertently look into the future. For instance, data preprocessing techniques like standardization can leak future information into the past. If you subtract the mean or maximum value from each point in the time series, the maximum value reached in 2021 would be known in 2015, which is unacceptable.</li>
</ul>
<p dir="auto">The Quantiacs platform provides a tool for evaluating models from a financial performance perspective.</p>
<p dir="auto">However, practice shows that finding a good machine learning model requires significant computational resources and time for training and testing. My results when testing strategies on real data have not been very good.</p>
]]></description><link>http://quantiacs.com/community/post/1693</link><guid isPermaLink="true">http://quantiacs.com/community/post/1693</guid><dc:creator><![CDATA[Vyacheslav_B]]></dc:creator><pubDate>Fri, 24 May 2024 07:27:44 GMT</pubDate></item><item><title><![CDATA[Reply to Acess previous weights on Fri, 24 May 2024 02:43:32 GMT]]></title><description><![CDATA[<p dir="auto"><a class="plugin-mentions-user plugin-mentions-a" href="http://quantiacs.com/community/uid/5"><a class="plugin-mentions-user plugin-mentions-a" href="http://quantiacs.com/community/uid/5">@vyacheslav_b</a></a> Hello. I would like to ask if Quantiacs provides any examples of using reinforcement learning or deep reinforcement learning models? Thank you.</p>
<p dir="auto"><a class="plugin-mentions-user plugin-mentions-a" href="http://quantiacs.com/community/uid/12">@support</a> <a class="plugin-mentions-user plugin-mentions-a" href="http://quantiacs.com/community/uid/5"><a class="plugin-mentions-user plugin-mentions-a" href="http://quantiacs.com/community/uid/5">@vyacheslav_b</a></a></p>
]]></description><link>http://quantiacs.com/community/post/1692</link><guid isPermaLink="true">http://quantiacs.com/community/post/1692</guid><dc:creator><![CDATA[BlackPearl]]></dc:creator><pubDate>Fri, 24 May 2024 02:43:32 GMT</pubDate></item><item><title><![CDATA[Reply to Acess previous weights on Thu, 23 May 2024 08:39:51 GMT]]></title><description><![CDATA[<p dir="auto"><a class="plugin-mentions-user plugin-mentions-a" href="http://quantiacs.com/community/uid/3391">@machesterdragon</a> Hello. I have already answered this question for you. see a few posts above.</p>
<p dir="auto">Single-pass Version for Participation in the Contest<br />
This code helps submissions get processed faster in the contest. The backtest system calculates the weights for each day, while the provided function calculates weights for only one day.</p>
]]></description><link>http://quantiacs.com/community/post/1691</link><guid isPermaLink="true">http://quantiacs.com/community/post/1691</guid><dc:creator><![CDATA[Vyacheslav_B]]></dc:creator><pubDate>Thu, 23 May 2024 08:39:51 GMT</pubDate></item><item><title><![CDATA[Reply to Acess previous weights on Thu, 23 May 2024 08:17:12 GMT]]></title><description><![CDATA[<p dir="auto"><a class="plugin-mentions-user plugin-mentions-a" href="http://quantiacs.com/community/uid/5"><a class="plugin-mentions-user plugin-mentions-a" href="http://quantiacs.com/community/uid/5">@Vyacheslav_B</a></a>  Hi, I just tried both ml backtest and single backtest. This is the ml_backtest result<br />
<img src="/community/assets/uploads/files/1716452212809-screenshot-2024-05-23-151636.png" alt="Screenshot 2024-05-23 151636.png" class="img-responsive img-markdown" /></p>
<p dir="auto">However, when adding the single cell backtest after ml_backtest, the result is Nan, so how can I submit the strategy according to the single backtest? Looking forward to your answer. Thank you.<br />
<img src="/community/assets/uploads/files/1716452213266-screenshot-2024-05-23-151409.png" alt="Screenshot 2024-05-23 151409.png" class="img-responsive img-markdown" /></p>
<p dir="auto"><a class="plugin-mentions-user plugin-mentions-a" href="http://quantiacs.com/community/uid/12">@support</a> <a class="plugin-mentions-user plugin-mentions-a" href="http://quantiacs.com/community/uid/5"><a class="plugin-mentions-user plugin-mentions-a" href="http://quantiacs.com/community/uid/5">@Vyacheslav_B</a></a></p>
]]></description><link>http://quantiacs.com/community/post/1690</link><guid isPermaLink="true">http://quantiacs.com/community/post/1690</guid><dc:creator><![CDATA[machesterdragon]]></dc:creator><pubDate>Thu, 23 May 2024 08:17:12 GMT</pubDate></item><item><title><![CDATA[Reply to Acess previous weights on Wed, 22 May 2024 15:28:55 GMT]]></title><description><![CDATA[<p dir="auto">Hi <a class="plugin-mentions-user plugin-mentions-a" href="http://quantiacs.com/community/uid/5">@vyacheslav_b</a>,<br />
I just quickly checked the template and it seems to be very helpful.<br />
Thx a lot for the update!<br />
Regards</p>
]]></description><link>http://quantiacs.com/community/post/1688</link><guid isPermaLink="true">http://quantiacs.com/community/post/1688</guid><dc:creator><![CDATA[magenta.kabuto]]></dc:creator><pubDate>Wed, 22 May 2024 15:28:55 GMT</pubDate></item><item><title><![CDATA[Reply to Acess previous weights on Wed, 22 May 2024 05:51:24 GMT]]></title><description><![CDATA[<p dir="auto"><a class="plugin-mentions-user plugin-mentions-a" href="http://quantiacs.com/community/uid/2784">@illustrious-felice</a> Hi,</p>
<p dir="auto"><a href="https://github.com/quantiacs/strategy-ml_lstm_state/blob/master/strategy.ipynb" rel="nofollow ugc">https://github.com/quantiacs/strategy-ml_lstm_state/blob/master/strategy.ipynb</a></p>
<p dir="auto">This repository provides an example of using state, calculating complex indicators, dynamically selecting stocks for trading, and implementing basic risk management measures, such as normalizing and reducing large positions. It also includes recommendations for submitting strategies to the competition.</p>
]]></description><link>http://quantiacs.com/community/post/1687</link><guid isPermaLink="true">http://quantiacs.com/community/post/1687</guid><dc:creator><![CDATA[Vyacheslav_B]]></dc:creator><pubDate>Wed, 22 May 2024 05:51:24 GMT</pubDate></item><item><title><![CDATA[Reply to Acess previous weights on Sat, 18 May 2024 14:48:12 GMT]]></title><description><![CDATA[<p dir="auto">hello again to all,<br />
I hope everyone is fine.<br />
I again came across a question, which should have occurred to me earlier, namely when we use a stateful machine learning strategy for submission, how can we pass on the states without using the ml_backtester, assuming the notebook is rerun at each point in time.<br />
Thank you.<br />
Regards</p>
]]></description><link>http://quantiacs.com/community/post/1679</link><guid isPermaLink="true">http://quantiacs.com/community/post/1679</guid><dc:creator><![CDATA[magenta.kabuto]]></dc:creator><pubDate>Sat, 18 May 2024 14:48:12 GMT</pubDate></item><item><title><![CDATA[Reply to Acess previous weights on Thu, 16 May 2024 01:57:30 GMT]]></title><description><![CDATA[<p dir="auto"><a class="plugin-mentions-user plugin-mentions-a" href="http://quantiacs.com/community/uid/5">@vyacheslav_b</a> Thank you for your response<br />
Here is the code I used from your example. I added some other features (eg: trend = qnta.roc(qnta.lwma(data.sel(field='close'), 40), 1),...) and noticed that after passing ml_backtest, every indexes are all nan. Pnl is a straight line. I have tried changing many other features but the result is still the same, all indicators are nan</p>
<pre><code>import xarray as xr
import qnt.data as qndata
import qnt.backtester as qnbt
import qnt.ta as qnta
import qnt.stats as qns
import qnt.graph as qngraph
import qnt.output as qnout
import numpy as np
import pandas as pd
import torch
from torch import nn, optim
import random

asset_name_all = ['NAS:AAPL', 'NAS:GOOGL']
lookback_period = 155
train_period = 100


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):
        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():
    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_seed(42)
    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)
    trend = qnta.roc(qnta.lwma(close_price ), 40), 1)
    features = xr.concat([log_close, log_open, high_price, trend], "feature")
    return features


def get_target_classes(data):
    price_current = data.sel(field='open')
    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 &gt; 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, state):
    last_time = data.time.values[-1]
    data_last = data.sel(time=slice(last_time, None)) 
    
    weights = xr.zeros_like(data_last.sel(field='close'))
    for asset_name in asset_name_all:
        features_all = get_features(data_last)
        features_cur = features_all.sel(asset=asset_name).dropna('time', 'any')
        if len(features_cur.time) &lt; 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
        
        
    weights = weights * data_last.sel(field="is_liquid")
    
    # state may be null, so define a default value
    if state is None:
        default = xr.zeros_like(data_last.sel(field='close')).isel(time=-1)
        state = {
            "previus_weights": default,
        }
        
    previus_weights = state['previus_weights']
    
    
    # align the arrays to prevent problems in case the asset list changes
    previus_weights, weights = xr.align(previus_weights, weights, join='right') 
    

    weights_avg = (previus_weights + weights) / 2
    
    
    next_state = {
        "previus_weights": weights_avg.isel(time=-1),
    }
    
#     print(last_time)
#     print("previus_weights")
#     print(previus_weights)
#     print(weights)
#     print("weights_avg")
#     print(weights_avg.isel(time=-1))

    return weights_avg, next_state


weights = qnbt.backtest_ml(
    load_data=load_data,
    train=train_model,
    predict=predict,
    train_period=train_period,
    retrain_interval=360,
    retrain_interval_after_submit=1,
    predict_each_day=True,
    competition_type='stocks_nasdaq100',
    lookback_period=lookback_period,
    start_date='2006-01-01',
    build_plots=True
)
</code></pre>
<p dir="auto"><img src="/community/assets/uploads/files/1715824621964-screenshot-2024-05-16-085531.png" alt="Screenshot 2024-05-16 085531.png" class="img-responsive img-markdown" /><br />
<img src="/community/assets/uploads/files/1715824621739-screenshot-2024-05-16-085555.png" alt="Screenshot 2024-05-16 085555.png" class="img-responsive img-markdown" /><br />
<img src="/community/assets/uploads/files/1715824642580-screenshot-2024-05-16-085716.png" alt="Screenshot 2024-05-16 085716.png" class="img-responsive img-markdown" /></p>
]]></description><link>http://quantiacs.com/community/post/1677</link><guid isPermaLink="true">http://quantiacs.com/community/post/1677</guid><dc:creator><![CDATA[illustrious.felice]]></dc:creator><pubDate>Thu, 16 May 2024 01:57:30 GMT</pubDate></item><item><title><![CDATA[Reply to Acess previous weights on Wed, 15 May 2024 15:20:27 GMT]]></title><description><![CDATA[<p dir="auto"><a class="plugin-mentions-user plugin-mentions-a" href="http://quantiacs.com/community/uid/2784">@illustrious-felice</a> Hello.</p>
<p dir="auto">Show me an example of the code.</p>
<p dir="auto">I don't quite understand what you are trying to do.</p>
<p dir="auto">Maybe you just don't have enough data in the functions to get the value.</p>
<p dir="auto">Please note that in the lines I intentionally reduce the data size to 1 day to predict only the last day.</p>
<pre><code class="language-python">last_time = data.time.values[-1]
data_last = data.sel(time=slice(last_time, None))
</code></pre>
<p dir="auto">Calculate your indicators before this code, and then slice the values.</p>
]]></description><link>http://quantiacs.com/community/post/1676</link><guid isPermaLink="true">http://quantiacs.com/community/post/1676</guid><dc:creator><![CDATA[Vyacheslav_B]]></dc:creator><pubDate>Wed, 15 May 2024 15:20:27 GMT</pubDate></item><item><title><![CDATA[Reply to Acess previous weights on Wed, 15 May 2024 13:37:48 GMT]]></title><description><![CDATA[<p dir="auto"><a class="plugin-mentions-user plugin-mentions-a" href="http://quantiacs.com/community/uid/5">@vyacheslav_b</a> Hello, I was trying the code you gave and realized that using state for train ml_backtest only works when the get feature function is a feature like ohlc or log of ohlc (open, high, low, close).</p>
<p dir="auto">I added some other features (eg: trend = qnta.roc(qnta.lwma(data.sel(field='close'), 40), 1),...) and noticed that after passing ml_backtest, every The indexes are all nan. Looking forward to your help. Thank you.</p>
<p dir="auto"><a class="plugin-mentions-user plugin-mentions-a" href="http://quantiacs.com/community/uid/5">@Vyacheslav_B</a></p>
]]></description><link>http://quantiacs.com/community/post/1675</link><guid isPermaLink="true">http://quantiacs.com/community/post/1675</guid><dc:creator><![CDATA[illustrious.felice]]></dc:creator><pubDate>Wed, 15 May 2024 13:37:48 GMT</pubDate></item><item><title><![CDATA[Reply to Acess previous weights on Thu, 09 May 2024 15:33:17 GMT]]></title><description><![CDATA[<p dir="auto"><a class="plugin-mentions-user plugin-mentions-a" href="http://quantiacs.com/community/uid/3391">@machesterdragon</a><br />
That's how it should be. This code is needed so that submissions are processed faster when sent to the contest. The backtest system will calculate the weights for each day. The function I provided calculates weights for only one day.</p>
]]></description><link>http://quantiacs.com/community/post/1664</link><guid isPermaLink="true">http://quantiacs.com/community/post/1664</guid><dc:creator><![CDATA[Vyacheslav_B]]></dc:creator><pubDate>Thu, 09 May 2024 15:33:17 GMT</pubDate></item><item><title><![CDATA[Reply to Acess previous weights on Thu, 09 May 2024 15:25:09 GMT]]></title><description><![CDATA[<p dir="auto"><a class="plugin-mentions-user plugin-mentions-a" href="http://quantiacs.com/community/uid/5">@vyacheslav_b</a> said in <a href="/community/post/1662">Acess previous weights</a>:</p>
<blockquote>
<p dir="auto">If you use a state and a function that returns the prediction for one day, you will not get correct results with precheck.<br />
Theoretically, you can specify the number of partitions as all available days. or you can return all predictions<br />
I have not checked how the precheck works.<br />
If it works in parallel, you will not see the correct result even more so.<br />
State in strategy limits you. I recommend not using it.</p>
</blockquote>
<p dir="auto">Thank you so much <a class="plugin-mentions-user plugin-mentions-a" href="http://quantiacs.com/community/uid/5">@Vyacheslav_B</a>.<br />
I just tried applying the single pass you suggested but the results were nan. Looking forward to your help when you have time. thank you very much<br />
<img src="/community/assets/uploads/files/1715268254192-screenshot-2024-05-09-221907.png" alt="Screenshot 2024-05-09 221907.png" class="img-responsive img-markdown" /></p>
<p dir="auto"><img src="/community/assets/uploads/files/1715268254620-screenshot-2024-05-09-222002.png" alt="Screenshot 2024-05-09 222002.png" class="img-responsive img-markdown" /></p>
<p dir="auto"><img src="/community/assets/uploads/files/1715268254726-screenshot-2024-05-09-222009.png" alt="Screenshot 2024-05-09 222009.png" class="img-responsive img-markdown" /></p>
]]></description><link>http://quantiacs.com/community/post/1663</link><guid isPermaLink="true">http://quantiacs.com/community/post/1663</guid><dc:creator><![CDATA[machesterdragon]]></dc:creator><pubDate>Thu, 09 May 2024 15:25:09 GMT</pubDate></item><item><title><![CDATA[Reply to Acess previous weights on Thu, 09 May 2024 14:57:53 GMT]]></title><description><![CDATA[<p dir="auto"><a class="plugin-mentions-user plugin-mentions-a" href="http://quantiacs.com/community/uid/3391">@machesterdragon</a> Hello.</p>
<p dir="auto">If you use a state and a function that returns the prediction for one day, you will not get correct results with precheck.</p>
<p dir="auto">Theoretically, you can specify the number of partitions as all available days. or you can return all predictions</p>
<p dir="auto">I have not checked how the precheck works.</p>
<p dir="auto">If it works in parallel, you will not see the correct result even more so.</p>
<p dir="auto">State in strategy limits you. I recommend not using it.</p>
<p dir="auto">Here is an example of a version for one pass; I couldn't test it because my submission did not calculate even one day.</p>
<p dir="auto">init.ipynb</p>
<pre><code class="language-python">! pip install torch==2.2.1
</code></pre>
<p dir="auto">strategy.ipynb</p>
<pre><code class="language-python">import gzip
import pickle

from qnt.data import get_env
from qnt.log import log_err, log_info


def state_write(state, path=None):
    if path is None:
        path = get_env("OUT_STATE_PATH", "state.out.pickle.gz")
    try:
        with gzip.open(path, 'wb') as gz:
            pickle.dump(state, gz)
        log_info("State saved: " + str(state))
    except Exception as e:
        log_err(f"Error saving state: {e}")


def state_read(path=None):
    if path is None:
        path = get_env("OUT_STATE_PATH", "state.out.pickle.gz")
    try:
        with gzip.open(path, 'rb') as gz:
            state = pickle.load(gz)
        log_info("State loaded.")
        return state
    except Exception as e:
        log_err(f"Can't load state: {e}")
        return None


state = state_read()
print(state)


# separate cell

def print_stats(data, weights):
    stats = qns.calc_stat(data, weights)
    display(stats.to_pandas().tail())
    performance = stats.to_pandas()["equity"]
    qngraph.make_plot_filled(performance.index, performance, name="PnL (Equity)", type="log")


data_train = load_data(train_period)
models = train_model(data_train)

data_predict = load_data(lookback_period)

last_time = data_predict.time.values[-1]

if last_time &lt; np.datetime64('2006-01-02'):
    print("The first state should be None")
    state_write(None)
    state = state_read()
    print(state)

weights_predict, state_new = predict(models, data_predict, state)

print_stats(data_predict, weights_predict)
state_write(state_new)
print(state_new)
qnout.write(weights_predict)  # To participate in the competition, save this code in a separate cell.

</code></pre>
<p dir="auto">But I hope it will work correctly.</p>
<p dir="auto">Do not expect any responses from me during this week.</p>
]]></description><link>http://quantiacs.com/community/post/1662</link><guid isPermaLink="true">http://quantiacs.com/community/post/1662</guid><dc:creator><![CDATA[Vyacheslav_B]]></dc:creator><pubDate>Thu, 09 May 2024 14:57:53 GMT</pubDate></item><item><title><![CDATA[Reply to Acess previous weights on Thu, 09 May 2024 03:46:27 GMT]]></title><description><![CDATA[<p dir="auto"><a class="plugin-mentions-user plugin-mentions-a" href="http://quantiacs.com/community/uid/5">@vyacheslav_b</a> I tried your way but when prechecking there was an error: some dates are missed in the portfolio_history and the sharpness was very low.<br />
<img src="/community/assets/uploads/files/1715226255009-screenshot-2024-05-09-101653.png" alt="Screenshot 2024-05-09 101653.png" class="img-responsive img-markdown" /></p>
<p dir="auto">I went to precheck result html file and this is the error result and sharpe is nan<br />
<img src="/community/assets/uploads/files/1715226346278-screenshot-2024-05-09-104520.png" alt="Screenshot 2024-05-09 104520.png" class="img-responsive img-markdown" /></p>
<p dir="auto">We look forward to receiving your support. Thank you<br />
<a class="plugin-mentions-user plugin-mentions-a" href="http://quantiacs.com/community/uid/12">@support</a> <a class="plugin-mentions-user plugin-mentions-a" href="http://quantiacs.com/community/uid/5">@Vyacheslav_B</a></p>
]]></description><link>http://quantiacs.com/community/post/1661</link><guid isPermaLink="true">http://quantiacs.com/community/post/1661</guid><dc:creator><![CDATA[machesterdragon]]></dc:creator><pubDate>Thu, 09 May 2024 03:46:27 GMT</pubDate></item><item><title><![CDATA[Reply to Acess previous weights on Wed, 08 May 2024 20:41:31 GMT]]></title><description><![CDATA[<p dir="auto"><a class="plugin-mentions-user plugin-mentions-a" href="http://quantiacs.com/community/uid/5">@vyacheslav_b</a> the problem with not using states as I understand is the following: lets say the model estimated in t (single pass) gives an estimate for NAS:AAPL = 0.04 (weight allocation). So thats the position assigned to the stock in t for t+1.<br />
In t+1 the model is reestimated but with the information of NAS:AAPL in t and assigns weights 0.03 for t+1 and 0.035 for t+2 in t+1. When I do not use states, and apply get_lower_slippage function , I will have weight allocation 0.035 for t+2 in t+1 whereas with the states I will have 0.04 for t+2 in t+1 and I will not have impact of the transaction costs.<br />
Thank you.<br />
Regards</p>
]]></description><link>http://quantiacs.com/community/post/1659</link><guid isPermaLink="true">http://quantiacs.com/community/post/1659</guid><dc:creator><![CDATA[magenta.kabuto]]></dc:creator><pubDate>Wed, 08 May 2024 20:41:31 GMT</pubDate></item><item><title><![CDATA[Reply to Acess previous weights on Wed, 08 May 2024 16:17:56 GMT]]></title><description><![CDATA[<p dir="auto">Hi <a class="plugin-mentions-user plugin-mentions-a" href="http://quantiacs.com/community/uid/5">@vyacheslav_b</a> ,<br />
thank you very much for the solution.<br />
I did not know that the ML_backtester is capable of handling two outputs (weights and state) but I will from now on use it.<br />
Regards</p>
]]></description><link>http://quantiacs.com/community/post/1658</link><guid isPermaLink="true">http://quantiacs.com/community/post/1658</guid><dc:creator><![CDATA[magenta.kabuto]]></dc:creator><pubDate>Wed, 08 May 2024 16:17:56 GMT</pubDate></item><item><title><![CDATA[Reply to Acess previous weights on Wed, 08 May 2024 16:02:49 GMT]]></title><description><![CDATA[<p dir="auto"><a class="plugin-mentions-user plugin-mentions-a" href="http://quantiacs.com/community/uid/5">@vyacheslav_b</a> Hi. I would like to ask how to switch from ml_backtest to single backtest to submit? And will this move lead to forward looking risks?</p>
<p dir="auto">If so, is there no way to satisfy submission without exceeding time while eliminating forward looking? Looking forward to your answers and support. Thank you.</p>
]]></description><link>http://quantiacs.com/community/post/1657</link><guid isPermaLink="true">http://quantiacs.com/community/post/1657</guid><dc:creator><![CDATA[machesterdragon]]></dc:creator><pubDate>Wed, 08 May 2024 16:02:49 GMT</pubDate></item><item><title><![CDATA[Reply to Acess previous weights on Wed, 08 May 2024 15:41:44 GMT]]></title><description><![CDATA[<p dir="auto"><a class="plugin-mentions-user plugin-mentions-a" href="http://quantiacs.com/community/uid/1799">@magenta-kabuto</a> Hello. Use the following example.<br />
Note that the backtest parameters are set for daily prediction of values.<br />
The prediction function is designed to return a value for one day. Later, I will show how to create a single-pass version.</p>
<pre><code class="language-python">import xarray as xr
import qnt.data as qndata
import qnt.backtester as qnbt
import qnt.ta as qnta
import qnt.stats as qns
import qnt.graph as qngraph
import qnt.output as qnout
import numpy as np
import pandas as pd
import torch
from torch import nn, optim
import random

asset_name_all = ['NAS:AAPL', 'NAS:GOOGL']
lookback_period = 155
train_period = 100


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):
        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():
    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_seed(42)
    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='open')
    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 &gt; 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, state):
    last_time = data.time.values[-1]
    data_last = data.sel(time=slice(last_time, None)) 
    
    weights = xr.zeros_like(data_last.sel(field='close'))
    for asset_name in asset_name_all:
        features_all = get_features(data_last)
        features_cur = features_all.sel(asset=asset_name).dropna('time', 'any')
        if len(features_cur.time) &lt; 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
        
        
    weights = weights * data_last.sel(field="is_liquid")
    
    # state may be null, so define a default value
    if state is None:
        default = xr.zeros_like(data_last.sel(field='close')).isel(time=-1)
        state = {
            "previus_weights": default,
        }
        
    previus_weights = state['previus_weights']
    
    
    # align the arrays to prevent problems in case the asset list changes
    previus_weights, weights = xr.align(previus_weights, weights, join='right') 
    

    weights_avg = (previus_weights + weights) / 2
    
    
    next_state = {
        "previus_weights": weights_avg.isel(time=-1),
    }
    
#     print(last_time)
#     print("previus_weights")
#     print(previus_weights)
#     print(weights)
#     print("weights_avg")
#     print(weights_avg.isel(time=-1))

    return weights_avg, next_state


weights = qnbt.backtest_ml(
    load_data=load_data,
    train=train_model,
    predict=predict,
    train_period=train_period,
    retrain_interval=360,
    retrain_interval_after_submit=1,
    predict_each_day=True,
    competition_type='stocks_nasdaq100',
    lookback_period=lookback_period,
    start_date='2006-01-01',
    build_plots=True
)
</code></pre>
<p dir="auto">I recommend not using state at all, but rather using the approach I mentioned above.<br />
Because it's faster.<br />
If you need to use a single-pass version, it's better to load more data and calculate the weight values for previous days, then combine them. You will have calculated weights for the previous days.</p>
]]></description><link>http://quantiacs.com/community/post/1656</link><guid isPermaLink="true">http://quantiacs.com/community/post/1656</guid><dc:creator><![CDATA[Vyacheslav_B]]></dc:creator><pubDate>Wed, 08 May 2024 15:41:44 GMT</pubDate></item><item><title><![CDATA[Reply to Acess previous weights on Mon, 06 May 2024 21:19:43 GMT]]></title><description><![CDATA[<p dir="auto">Hi <a class="plugin-mentions-user plugin-mentions-a" href="http://quantiacs.com/community/uid/12">@support</a>,<br />
just wanted to thank for the suggestion of the stateful backtester, as this solves the issue.<br />
I incorporated the DL model into the stateful backtester, which seems to work (backtesting right-now).<br />
And the get_lower slippage function in the ML- templates is subject to forward looking, overfitting the holding period.<br />
Regards</p>
]]></description><link>http://quantiacs.com/community/post/1655</link><guid isPermaLink="true">http://quantiacs.com/community/post/1655</guid><dc:creator><![CDATA[magenta.kabuto]]></dc:creator><pubDate>Mon, 06 May 2024 21:19:43 GMT</pubDate></item><item><title><![CDATA[Reply to Acess previous weights on Sat, 04 May 2024 10:27:57 GMT]]></title><description><![CDATA[<p dir="auto"><a class="plugin-mentions-user plugin-mentions-a" href="http://quantiacs.com/community/uid/12">@support</a> thx for your reply.<br />
I also saw some discussion related to a similar topic in the general discussion.<br />
I will try to explain what I mean, if it doesnt make sense just ignore it and if I get something wrong, pls let me know.<br />
The point i am making is lets imagine the evaluation period starts on 01.06.2024 and my Deep Learning model meets the criteria for evaluation.<br />
Now since 01.06.2024 is the first day, the model will predict for this day and assign the weights for assets traded on 01.06.2024, one day before, where it is trained.<br />
Now to my understanding, the model is retrained everyday for the single-pass submission of the DL-Model, which therefore will have different weights (model weights, not allocation weights) for the next day training (01.06.2024) and will predict one step ahead, the allocations for 02.06.2024, and so on.<br />
So my question is, that under this framework I do not have access to the previous weights, right ? (For 01.06.2024 model training, I do not know what allocation weights I assigned on 31.05.2024)(I dont know whether with the stateful model I can have access to lets say up to 60 days of previous allocations)<br />
The weights  assigned however, are saved somewhere with quantiacs ,as these allocation were made in the past but are not accessible to me ,lets say on 03.06.2024.<br />
SO if I want to reduce slippage, so that I on 03.06.2024 want to change allocations only if the predictions are larger since the beginning of the evaluation, how can I do that.<br />
I hope it makes sense what I am trying to say.<br />
Regards</p>
]]></description><link>http://quantiacs.com/community/post/1654</link><guid isPermaLink="true">http://quantiacs.com/community/post/1654</guid><dc:creator><![CDATA[magenta.kabuto]]></dc:creator><pubDate>Sat, 04 May 2024 10:27:57 GMT</pubDate></item><item><title><![CDATA[Reply to Acess previous weights on Tue, 30 Apr 2024 16:32:42 GMT]]></title><description><![CDATA[<p dir="auto"><a class="plugin-mentions-user plugin-mentions-a" href="http://quantiacs.com/community/uid/1799">@magenta-kabuto</a> Hi, I am not sure I understand you correctly, maybe you can use the stateful version of the backtester as we described here:</p>
<p dir="auto"><a href="https://quantiacs.com/documentation/en/reference/evaluation.html#stateful-multi-pass-backtesting" rel="nofollow ugc">https://quantiacs.com/documentation/en/reference/evaluation.html#stateful-multi-pass-backtesting</a></p>
<p dir="auto">which will preserve in memory previous state.</p>
]]></description><link>http://quantiacs.com/community/post/1639</link><guid isPermaLink="true">http://quantiacs.com/community/post/1639</guid><dc:creator><![CDATA[support]]></dc:creator><pubDate>Tue, 30 Apr 2024 16:32:42 GMT</pubDate></item><item><title><![CDATA[Reply to Acess previous weights on Mon, 29 Apr 2024 11:33:34 GMT]]></title><description><![CDATA[<p dir="auto">Hey <a class="plugin-mentions-user plugin-mentions-a" href="http://quantiacs.com/community/uid/12">@support</a>,<br />
can you maybe help?<br />
Is there a way to download or access weights like its done for data? (which is updated for each time step)<br />
Thank you.<br />
Regards</p>
]]></description><link>http://quantiacs.com/community/post/1636</link><guid isPermaLink="true">http://quantiacs.com/community/post/1636</guid><dc:creator><![CDATA[magenta.kabuto]]></dc:creator><pubDate>Mon, 29 Apr 2024 11:33:34 GMT</pubDate></item><item><title><![CDATA[Reply to Acess previous weights on Sun, 28 Apr 2024 07:55:40 GMT]]></title><description><![CDATA[<p dir="auto">Hi <a class="plugin-mentions-user plugin-mentions-a" href="http://quantiacs.com/community/uid/5">@vyacheslav_b</a> , thx for your reply.<br />
Sry I expressed myself badly. What I mean is that as I understand if I predict each time step, my for example machine learning model, will take a position in t (lets say 0.5). Now in t+1 when the notebook is run again for prediction that information is lost ,isnt it? So if I want to apply the lower slippage, how can I do that?<br />
An example is the screenshot I posted above, which makes a one step prediction, by assigning a weight for selected assets on the latest index at time step t. No tomorrow in t+1 it will assign a new weight for the selcted assets without knowledge what was assigned in t with the knowledge in t, as in t+1 I could take the value of the prediction for (which is part of the batch) but will be different from the weights I assigned in t because of forward looking.<br />
I hope I didnt overcomplicate in my expression.<br />
Regards</p>
]]></description><link>http://quantiacs.com/community/post/1631</link><guid isPermaLink="true">http://quantiacs.com/community/post/1631</guid><dc:creator><![CDATA[magenta.kabuto]]></dc:creator><pubDate>Sun, 28 Apr 2024 07:55:40 GMT</pubDate></item></channel></rss>