ドキュメント
アプリケーション
マーク・フリック (Mark Fric) による最終更新日: 2022年1月21日
ストラテジーパラメータの表示と変更 - バージョン 2
これはこの例の改良版です: https://strategyquant.com/doc/programming-for-sq/changing-strategy-parameters-programmatically/
オリジナル ストラテジーパラメータヘルパー クラスにはパラメータの値を変更するメソッドが1つしかなかったが、ストラテジが持つ実際のパラメータのリストを取得するのは容易ではなかった。.
そこで私たちは新しいバージョンを作成しました – StrategyParametersHelperV2 パラメータとその値のリストを取得するためのメソッドも持つクラス。.
両方のクラスは、この記事の添付ファイルとしてダウンロード可能です。.
注意!SQの小さな問題により、最初にインポートしてコンパイルする必要があります StrategyParametersHelperV2 クラス、そしてその後に初めてインポート&コンパイルする 戦略パラメータ クラス.
この問題は次のSQビルド136で解決されます。.
StrategyParametersHelperV2 は以下のメソッドを持っています:
-
setParameters() – パラメータを設定(変更)する
-
getParameterNames() – パラメータ名のリストを返します
-
getParameterValues() – パラメータ名と値のリストを返す
-
toString() – 前のメソッドからのパラメータのリストを読みやすい文字列に変換します
例のデータバンクのコード断片でどのように使用できるかを見ることができます:
package SQ.Columns.Databanks;
import SQ.Utils.StrategyParametersHelperV2;
import com.strategyquant.lib.L;
import com.strategyquant.tradinglib.*;
import com.strategyquant.tradinglib.optimization.WalkForwardMatrixResult;
import com.strategyquant.lib.ValuesMap;
public class StrategyParameters extends DatabankColumn {
public StrategyParameters() {
super(L.tsq("Strategy Parameters"), DatabankColumn.Text, ValueTypes.Maximize, 0, 0, 1);
setWidth(200);
}
//------------------------------------------------------------------------
@Override
public double getNumericValue(ResultsGroup results, String resultKey, byte direction, byte plType, byte sampleType) throws Exception {
return 0;
}
//------------------------------------------------------------------------
@Override
public String getValue(ResultsGroup results, String resultKey, byte direction, byte plType, byte sampleType) throws Exception {
try {
ValuesMap parameterTypes = new ValuesMap();
parameterTypes.set(ParametrizationTypes.ParamTypePeriod, true);
parameterTypes.set(ParametrizationTypes.ParamTypeShift, false);
parameterTypes.set(ParametrizationTypes.ParamTypeConstant, false);
parameterTypes.set(ParametrizationTypes.ParamTypeOtherParam, false);
parameterTypes.set(ParametrizationTypes.ParamTypeEntryLevel, true);
parameterTypes.set(ParametrizationTypes.ParamTypeEntryLogic, false);
parameterTypes.set(ParametrizationTypes.ParamTypeExitUsed, true);
parameterTypes.set(ParametrizationTypes.ParamTypeExitUnused, false);
parameterTypes.set(ParametrizationTypes.ParamTypeBoolean, false);
parameterTypes.set(ParametrizationTypes.ParamTypeTradingOptions, false);
boolean sameVariablesForLongShort = true;
return StrategyParametersHelperV2.toString(StrategyParametersHelperV2.getParameterValues(results, parameterTypes, sameVariablesForLongShort));
} catch(Exception e) {
return "Error: " + e.getMessage();
}
}
}
ヘルパーメソッドを使用してパラメータを取得し、それを文字列に変換していることがわかります。.
結果(新しいデータバンクの列)はこのようになります。指定された戦略のパラメータがリスト表示されます:
オプティマイザーや他のパラメータ設定と同様に、表示したいパラメータのタイプを定義できること、またロング側とショート側で同じ変数を使用するかどうかを指定できることに注意してください。.
完全なコードは StrategyParametersHelperV2 クラスは:
package SQ.Utils;
import com.strategyquant.datalib.TradingException;
import com.strategyquant.lib.SQTime;
import com.strategyquant.lib.ValuesMap;
import com.strategyquant.lib.XMLUtil;
import com.strategyquant.tradinglib.*;
import com.strategyquant.tradinglib.options.TradingOptionsList;
import com.strategyquant.tradinglib.propertygrid.IPGParameter;
import com.strategyquant.tradinglib.propertygrid.ParametersTableItemProperties;
import org.jdom2.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class StrategyParametersHelperV2 {
public static final Logger Log = LoggerFactory.getLogger(StrategyParametersHelper.class);
public static final String ValueDelimiter = "=";
public static final String ParamDelimiter = ",";
/**
* Applies parameter values into strategy
* @param rg
* @param parameters - colon delimited list of parameters and their values - e.g. param1=123,param2=25.4
* @param symmetricVariables
* @param modifyLastSettings
* @throws Exception
*/
public static void setParameters(ResultsGroup rg, String parameters, boolean symmetricVariables, boolean modifyLastSettings) throws Exception {
//Load XML and update variables
StrategyBase strategyBase = getStrategyBase(rg, symmetricVariables);
Variables variables = strategyBase.variables();
String[] params = parameters.split(ParamDelimiter);
HashMap<String, String> paramMap = new HashMap<>();
for(int i=0; i<params.length; i++) {
String[] values = params[i].split(ValueDelimiter);
paramMap.put(values[0], values[1]);
}
for(int a=0; a<variables.size(); a++) {
Variable variable = variables.get(a);
if(paramMap.containsKey(variable.getName())) {
variable.setFromString(paramMap.get(variable.getName()));
}
}
strategyBase.transformToNumbers();
rg.portfolio().addStrategyXml(strategyBase.getStrategyXml());
rg.specialValues().setString(StatsKey.OPTIMIZATION_PARAMETERS, parameters);
if(modifyLastSettings){
try {
Element lastSettings = XMLUtil.stringToElement(rg.getLastSettings());
Element elParams = lastSettings.getChild("Options").getChild("BuildTradingOptions").getChild("Params");
List<Element> paramElems = elParams.getChildren("Param");
List<TradingOption> tradingOptions = TradingOptionsList.getInstance().getAvailableClasses();
for(String paramName : paramMap.keySet()) {
boolean processed = false;
//we must find the right trading option
for(int i=0; i<tradingOptions.size(); i++) {
if(processed) break;
TradingOption option = tradingOptions.get(i);
String optionClass = option.getClass().getSimpleName();
ArrayList<IPGParameter> optionParams = option.getParams();
//go through its params and find the one with matching name
for(int z=0; z<optionParams.size(); z++) {
if(processed) break;
IPGParameter optionParam = optionParams.get(z);
String paramKey = optionParam.getKey();
if(!optionParam.getName().equals(paramName)) continue;
//now find the right Param element in settings XML and update its value
for(int s=0; s<paramElems.size(); s++) {
Element elParam = paramElems.get(s);
String elParamClass = elParam.getAttributeValue("className");
String elParamKey = elParam.getAttributeValue("key");
if(elParamClass != null && elParamKey != null && elParamClass.equals(optionClass) && elParamKey.equals(paramKey)) {
String value = paramMap.get(paramName);
if(optionParam.getType() == ParametersTableItemProperties.TYPE_TIME) {
value = "" + SQTime.HHMMToMinutes(Integer.parseInt(value)) * 60;
}
elParam.setText(value);
processed = true;
break;
}
}
}
}
}
rg.setLastSettings(XMLUtil.elementToString(lastSettings));
}
catch(Exception e){
Log.error("Cannot apply trading options params to last settings", e);
}
}
}
/**
* Returns an ArrayList of strategy parameter names
* @param rg
* @param parameterTypes
* @param symmetricVariables
* @return
* @throws Exception
*/
public static ArrayList<String> getParameterNames(ResultsGroup rg, ValuesMap parameterTypes, boolean symmetricVariables) throws Exception {
HashMap<String, String> paramsMap = getParameterValues(rg, parameterTypes, symmetricVariables);
ArrayList<String> list = new ArrayList<>();
list.addAll(paramsMap.keySet());
return list;
}
/**
* Returns a map containing strategy parameter names and values
* @param rg
* @param parameterTypes - ValuesMap specifying ParametrizationTypes to check. If null, recommended parameter types are used.
* @param symmetricVariables
* @return
* @throws Exception
*/
public static HashMap<String, String> getParameterValues(ResultsGroup rg, ValuesMap parameterTypes, boolean symmetricVariables) throws Exception {
StrategyBase strategyBase = getStrategyBase(rg, symmetricVariables);
Variables variables = strategyBase.variables();
HashMap<String, String> paramsList = new HashMap<>();
boolean useRecommended = parameterTypes == null || parameterTypes.getBoolean(ParametrizationTypes.ParamTypeRecommended, false);
if(useRecommended){
parameterTypes = new ValuesMap();
parameterTypes.set(ParametrizationTypes.ParamTypePeriod, true);
parameterTypes.set(ParametrizationTypes.ParamTypeEntryLevel, true);
parameterTypes.set(ParametrizationTypes.ParamTypeExitUsed, true);
}
for(int a=0; a<variables.size(); a++) {
Variable variable = variables.get(a);
String variableType = variable.getParamType();
String varName = variable.getName();
if(varName.equals("LongEntrySignal") || varName.equals("ShortEntrySignal") || varName.equals("LongExitSignal") || varName.equals("ShortExitSignal") || varName.equals("MagicNumber")) {
// skip parameters that don't need to be set here
continue;
}
if(variableType == null || parameterTypes.getBoolean(variableType, false)){
paramsList.put(variable.getName(), variable.getValue());
}
}
return paramsList;
}
/**
* Returns a value of selected parameter
* @param rg
* @param symmetricVariables
* @param parameterName
* @return
* @throws Exception
*/
public static String getParameterValue(ResultsGroup rg, boolean symmetricVariables, String parameterName) throws Exception {
StrategyBase strategyBase = getStrategyBase(rg, symmetricVariables);
Variables variables = strategyBase.variables();
Variable variable = variables.get(parameterName);
if(variable == null) return null;
return variable.getValue();
}
/**
* Converts parameter map to string
* @param parametersMap
* @return
*/
public static String toString(HashMap<String, String> parametersMap){
if(parametersMap == null) return null;
StringBuilder sb = new StringBuilder();
for(String name : parametersMap.keySet()){
sb.append(ParamDelimiter);
sb.append(name);
sb.append(ValueDelimiter);
sb.append(parametersMap.get(name));
}
return sb.length() > ParamDelimiter.length() ? sb.substring(ParamDelimiter.length()) : sb.toString();
}
private static StrategyBase getStrategyBase(ResultsGroup rg, boolean symmetricVariables) throws Exception {
StrategyBase xmlS = StrategyBase.createXmlStrategy(rg.getStrategyXml());
xmlS.transformToVariables(symmetricVariables);
return xmlS;
}
}
この記事は参考になりましたか? この記事は役に立った この記事は役に立たなかった

まさに探していたものでした!!とても助かります
どうもありがとうございます!!!!!
非常に興味深いですね。マーク、ありがとうございます!
143とは互換性がなくなってしまったため、この拡張機能のアップデートが来ることを願っています。.
それは戦略内のストップロスデータを破損させます。143以降と互換性を持つように更新できますか?
フィードバックありがとうございます。確認いたします。