M_730185 commited on
Commit
1db1092
·
1 Parent(s): d5fb961

Set up Strategy Interpreter Space

Browse files
Files changed (1) hide show
  1. app.py +175 -0
app.py ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from transformers import AutoModelForCausalLM, AutoTokenizer
3
+ import json
4
+ from jsonschema import validate, ValidationError
5
+ import logging
6
+
7
+ # Initialize logging
8
+ logging.basicConfig(level=logging.INFO)
9
+ logger = logging.getLogger("StrategyInterpreterSpace")
10
+
11
+ # Load model and tokenizer
12
+ model_name = "EleutherAI/gpt-j-6B"
13
+ logger.info(f"Loading model '{model_name}'...")
14
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
15
+ model = AutoModelForCausalLM.from_pretrained(model_name)
16
+ logger.info("Model loaded successfully.")
17
+
18
+ # Define JSON schema
19
+ schema = {
20
+ "type": "object",
21
+ "required": [
22
+ "strategy_name",
23
+ "market_type",
24
+ "assets",
25
+ "trade_parameters",
26
+ "conditions",
27
+ "risk_management"
28
+ ],
29
+ "properties": {
30
+ "strategy_name": {"type": "string"},
31
+ "market_type": {"type": "string", "enum": ["spot", "futures", "margin"]},
32
+ "assets": {"type": "array", "items": {"type": "string"}},
33
+ "trade_parameters": {
34
+ "type": "object",
35
+ "required": ["leverage", "order_type", "position_size"],
36
+ "properties": {
37
+ "leverage": {"type": "number"},
38
+ "order_type": {"type": "string"},
39
+ "position_size": {"type": "number"}
40
+ }
41
+ },
42
+ "conditions": {
43
+ "type": "object",
44
+ "required": ["entry", "exit"],
45
+ "properties": {
46
+ "entry": {
47
+ "type": "array",
48
+ "items": {"$ref": "#/definitions/condition"}
49
+ },
50
+ "exit": {
51
+ "type": "array",
52
+ "items": {"$ref": "#/definitions/condition"}
53
+ }
54
+ }
55
+ },
56
+ "risk_management": {
57
+ "type": "object",
58
+ "required": ["stop_loss", "take_profit", "trailing_stop_loss"],
59
+ "properties": {
60
+ "stop_loss": {"type": "number"},
61
+ "take_profit": {"type": "number"},
62
+ "trailing_stop_loss": {"type": "number"}
63
+ }
64
+ }
65
+ },
66
+ "definitions": {
67
+ "condition": {
68
+ "type": "object",
69
+ "required": ["indicator", "operator", "value", "timeframe"],
70
+ "properties": {
71
+ "indicator": {"type": "string"},
72
+ "operator": {"type": "string", "enum": [">", "<", "==", ">=", "<="]},
73
+ "value": {"type": ["string", "number"]},
74
+ "timeframe": {"type": "string"},
75
+ "indicator_parameters": {
76
+ "type": "object",
77
+ "properties": {
78
+ "period": {"type": "number"},
79
+ },
80
+ "additionalProperties": True
81
+ }
82
+ }
83
+ }
84
+ }
85
+ }
86
+
87
+ def interpret_strategy(description: str) -> str:
88
+ prompt = f"""
89
+ You are an expert crypto trading assistant. Convert the following trading strategy description into a JSON format following this schema:
90
+
91
+ {json.dumps(schema, indent=2)}
92
+
93
+ Include all indicators (only ones available in Ta-lib and pandas-ta), their parameters (only ones that are standard for ccxt and backtrader to support), assets (only ones that are available through BitGet) as trading pairs, conditions (only those supported by bitget, backtrader, finta, pandas-ta), risk management settings, and trade execution details (only those supported by ccxt, bitget and backtrader).
94
+ Response should only return the JSON with the correct parameters, nothing else.
95
+ Strategy Description:
96
+ {description}
97
+
98
+ JSON:
99
+ """
100
+ inputs = tokenizer.encode(prompt, return_tensors="pt")
101
+ outputs = model.generate(
102
+ inputs,
103
+ max_length=1000,
104
+ temperature=0.7,
105
+ top_p=0.9,
106
+ do_sample=True,
107
+ eos_token_id=tokenizer.eos_token_id,
108
+ )
109
+ generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
110
+ response_text = generated_text[len(prompt):].strip()
111
+
112
+ # Validate JSON
113
+ try:
114
+ strategy_data = json.loads(response_text)
115
+ validate(instance=strategy_data, schema=schema)
116
+ return json.dumps(strategy_data, indent=2)
117
+ except (json.JSONDecodeError, ValidationError) as e:
118
+ logger.error(f"Error interpreting strategy: {e}")
119
+ return f"Error interpreting strategy: {e}"
120
+
121
+ def suggest_strategy(risk_level: str, market_type: str) -> str:
122
+ prompt = f"""Please create a unique crypto trading strategy suitable for a '{risk_level}' risk appetite in the '{market_type}' market.
123
+ Ensure the JSON matches this schema:
124
+ {json.dumps(schema, indent=2)}
125
+
126
+ Use indicators and conditions that can be applied by ccxt, bitget, pandas-ta, and backtrader.
127
+
128
+ JSON:"""
129
+
130
+ inputs = tokenizer.encode(prompt, return_tensors="pt")
131
+ outputs = model.generate(
132
+ inputs,
133
+ max_length=1000,
134
+ temperature=0.7,
135
+ top_p=0.9,
136
+ do_sample=True,
137
+ eos_token_id=tokenizer.eos_token_id,
138
+ )
139
+ generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
140
+ response_text = generated_text[len(prompt):].strip()
141
+
142
+ # Validate JSON
143
+ try:
144
+ strategy_data = json.loads(response_text)
145
+ validate(instance=strategy_data, schema=schema)
146
+ if strategy_data.get("market_type") != market_type:
147
+ raise ValueError("The generated strategy's market type does not match the selected market type.")
148
+ return json.dumps(strategy_data, indent=2)
149
+ except (json.JSONDecodeError, ValidationError, ValueError) as e:
150
+ logger.error(f"Error generating strategy: {e}")
151
+ return f"Error generating strategy: {e}"
152
+
153
+ iface = gr.Interface(
154
+ fn=interpret_strategy,
155
+ inputs=gr.inputs.Textbox(lines=10, placeholder="Enter your strategy description here..."),
156
+ outputs="text",
157
+ title="Strategy Interpreter",
158
+ description="Convert trading strategy descriptions into structured JSON format."
159
+ )
160
+
161
+ iface_suggest = gr.Interface(
162
+ fn=suggest_strategy,
163
+ inputs=[
164
+ gr.inputs.Textbox(lines=1, placeholder="Enter risk level (e.g., medium)...", label="Risk Level"),
165
+ gr.inputs.Textbox(lines=1, placeholder="Enter market type (e.g., spot)...", label="Market Type")
166
+ ],
167
+ outputs="text",
168
+ title="Strategy Suggester",
169
+ description="Generate a unique trading strategy based on risk level and market type."
170
+ )
171
+
172
+ app = gr.TabbedInterface([iface, iface_suggest], ["Interpret Strategy", "Suggest Strategy"])
173
+
174
+ if __name__ == "__main__":
175
+ app.launch()