autohedge 0.0.1__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- autohedge-0.0.1/LICENSE +21 -0
- autohedge-0.0.1/PKG-INFO +96 -0
- autohedge-0.0.1/README.md +67 -0
- autohedge-0.0.1/autohedge/__init__.py +0 -0
- autohedge-0.0.1/autohedge/main.py +396 -0
- autohedge-0.0.1/pyproject.toml +57 -0
autohedge-0.0.1/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2023 Eternal Reclaimer
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
autohedge-0.0.1/PKG-INFO
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: autohedge
|
|
3
|
+
Version: 0.0.1
|
|
4
|
+
Summary: autohedge - TGSC
|
|
5
|
+
Home-page: https://github.com/The-Swarm-Corporation/AutoHedge
|
|
6
|
+
License: MIT
|
|
7
|
+
Keywords: artificial intelligence,deep learning,optimizers,Prompt Engineering
|
|
8
|
+
Author: Kye Gomez
|
|
9
|
+
Author-email: kye@apac.ai
|
|
10
|
+
Requires-Python: >=3.10,<4.0
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
19
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
20
|
+
Requires-Dist: loguru
|
|
21
|
+
Requires-Dist: pydantic
|
|
22
|
+
Requires-Dist: swarm-models
|
|
23
|
+
Requires-Dist: swarms
|
|
24
|
+
Requires-Dist: tickr-agent
|
|
25
|
+
Project-URL: Documentation, https://github.com/The-Swarm-Corporation/AutoHedge
|
|
26
|
+
Project-URL: Repository, https://github.com/The-Swarm-Corporation/AutoHedge
|
|
27
|
+
Description-Content-Type: text/markdown
|
|
28
|
+
|
|
29
|
+
[](https://discord.com/servers/agora-999382051935506503)
|
|
30
|
+
|
|
31
|
+
# Python Package Template
|
|
32
|
+
|
|
33
|
+
[](https://discord.gg/agora-999382051935506503) [](https://www.youtube.com/@kyegomez3242) [](https://www.linkedin.com/in/kye-g-38759a207/) [](https://x.com/kyegomezb)
|
|
34
|
+
|
|
35
|
+
A easy, reliable, fluid template for python packages complete with docs, testing suites, readme's, github workflows, linting and much much more
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
## Installation
|
|
39
|
+
|
|
40
|
+
You can install the package using pip
|
|
41
|
+
|
|
42
|
+
```bash
|
|
43
|
+
pip install -e .
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
# Usage
|
|
47
|
+
```python
|
|
48
|
+
print("hello world")
|
|
49
|
+
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
### Code Quality 🧹
|
|
55
|
+
|
|
56
|
+
- `make style` to format the code
|
|
57
|
+
- `make check_code_quality` to check code quality (PEP8 basically)
|
|
58
|
+
- `black .`
|
|
59
|
+
- `ruff . --fix`
|
|
60
|
+
|
|
61
|
+
### Tests 🧪
|
|
62
|
+
|
|
63
|
+
[`pytests`](https://docs.pytest.org/en/7.1.x/) is used to run our tests.
|
|
64
|
+
|
|
65
|
+
### Publish on PyPi 🚀
|
|
66
|
+
|
|
67
|
+
**Important**: Before publishing, edit `__version__` in [src/__init__](/src/__init__.py) to match the wanted new version.
|
|
68
|
+
|
|
69
|
+
```
|
|
70
|
+
poetry build
|
|
71
|
+
poetry publish
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
### CI/CD 🤖
|
|
75
|
+
|
|
76
|
+
We use [GitHub actions](https://github.com/features/actions) to automatically run tests and check code quality when a new PR is done on `main`.
|
|
77
|
+
|
|
78
|
+
On any pull request, we will check the code quality and tests.
|
|
79
|
+
|
|
80
|
+
When a new release is created, we will try to push the new code to PyPi. We use [`twine`](https://twine.readthedocs.io/en/stable/) to make our life easier.
|
|
81
|
+
|
|
82
|
+
The **correct steps** to create a new realease are the following:
|
|
83
|
+
- edit `__version__` in [src/__init__](/src/__init__.py) to match the wanted new version.
|
|
84
|
+
- create a new [`tag`](https://git-scm.com/docs/git-tag) with the release name, e.g. `git tag v0.0.1 && git push origin v0.0.1` or from the GitHub UI.
|
|
85
|
+
- create a new release from GitHub UI
|
|
86
|
+
|
|
87
|
+
The CI will run when you create the new release.
|
|
88
|
+
|
|
89
|
+
# Docs
|
|
90
|
+
We use MK docs. This repo comes with the zeta docs. All the docs configurations are already here along with the readthedocs configs.
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
# License
|
|
95
|
+
MIT
|
|
96
|
+
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
[](https://discord.com/servers/agora-999382051935506503)
|
|
2
|
+
|
|
3
|
+
# Python Package Template
|
|
4
|
+
|
|
5
|
+
[](https://discord.gg/agora-999382051935506503) [](https://www.youtube.com/@kyegomez3242) [](https://www.linkedin.com/in/kye-g-38759a207/) [](https://x.com/kyegomezb)
|
|
6
|
+
|
|
7
|
+
A easy, reliable, fluid template for python packages complete with docs, testing suites, readme's, github workflows, linting and much much more
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
## Installation
|
|
11
|
+
|
|
12
|
+
You can install the package using pip
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
pip install -e .
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
# Usage
|
|
19
|
+
```python
|
|
20
|
+
print("hello world")
|
|
21
|
+
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
### Code Quality 🧹
|
|
27
|
+
|
|
28
|
+
- `make style` to format the code
|
|
29
|
+
- `make check_code_quality` to check code quality (PEP8 basically)
|
|
30
|
+
- `black .`
|
|
31
|
+
- `ruff . --fix`
|
|
32
|
+
|
|
33
|
+
### Tests 🧪
|
|
34
|
+
|
|
35
|
+
[`pytests`](https://docs.pytest.org/en/7.1.x/) is used to run our tests.
|
|
36
|
+
|
|
37
|
+
### Publish on PyPi 🚀
|
|
38
|
+
|
|
39
|
+
**Important**: Before publishing, edit `__version__` in [src/__init__](/src/__init__.py) to match the wanted new version.
|
|
40
|
+
|
|
41
|
+
```
|
|
42
|
+
poetry build
|
|
43
|
+
poetry publish
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
### CI/CD 🤖
|
|
47
|
+
|
|
48
|
+
We use [GitHub actions](https://github.com/features/actions) to automatically run tests and check code quality when a new PR is done on `main`.
|
|
49
|
+
|
|
50
|
+
On any pull request, we will check the code quality and tests.
|
|
51
|
+
|
|
52
|
+
When a new release is created, we will try to push the new code to PyPi. We use [`twine`](https://twine.readthedocs.io/en/stable/) to make our life easier.
|
|
53
|
+
|
|
54
|
+
The **correct steps** to create a new realease are the following:
|
|
55
|
+
- edit `__version__` in [src/__init__](/src/__init__.py) to match the wanted new version.
|
|
56
|
+
- create a new [`tag`](https://git-scm.com/docs/git-tag) with the release name, e.g. `git tag v0.0.1 && git push origin v0.0.1` or from the GitHub UI.
|
|
57
|
+
- create a new release from GitHub UI
|
|
58
|
+
|
|
59
|
+
The CI will run when you create the new release.
|
|
60
|
+
|
|
61
|
+
# Docs
|
|
62
|
+
We use MK docs. This repo comes with the zeta docs. All the docs configurations are already here along with the readthedocs configs.
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
# License
|
|
67
|
+
MIT
|
|
File without changes
|
|
@@ -0,0 +1,396 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import uuid
|
|
3
|
+
from datetime import datetime
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import Dict, List, Optional
|
|
6
|
+
|
|
7
|
+
from loguru import logger
|
|
8
|
+
from pydantic import BaseModel
|
|
9
|
+
from swarm_models import OpenAIChat
|
|
10
|
+
from swarms import Agent
|
|
11
|
+
from tickr_agent.main import TickrAgent
|
|
12
|
+
|
|
13
|
+
model = OpenAIChat(
|
|
14
|
+
model_name = "gpt-4o",
|
|
15
|
+
openai_api_key = os.getenv("OPENAI_API_KEY")
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
# Director Agent - Manages overall strategy and coordinates other agents
|
|
20
|
+
DIRECTOR_PROMPT = """
|
|
21
|
+
You are a Trading Director AI, responsible for orchestrating the trading process.
|
|
22
|
+
|
|
23
|
+
Your primary objectives are:
|
|
24
|
+
1. Conduct in-depth market analysis to identify opportunities and challenges.
|
|
25
|
+
2. Develop comprehensive trading theses, encompassing both technical and fundamental aspects.
|
|
26
|
+
3. Collaborate with specialized agents to ensure a cohesive strategy.
|
|
27
|
+
4. Make informed, data-driven decisions on trade executions.
|
|
28
|
+
|
|
29
|
+
For each stock under consideration, please provide the following:
|
|
30
|
+
|
|
31
|
+
- A concise market thesis, outlining the overall market position and expected trends.
|
|
32
|
+
- Key technical and fundamental factors influencing the stock's performance.
|
|
33
|
+
- A detailed risk assessment, highlighting potential pitfalls and mitigation strategies.
|
|
34
|
+
- Trade parameters, including entry and exit points, position sizing, and risk management guidelines.
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
# Quant Analysis Agent
|
|
39
|
+
QUANT_PROMPT = """
|
|
40
|
+
You are a Quantitative Analysis AI, tasked with providing in-depth numerical analysis to support trading decisions. Your primary objectives are:
|
|
41
|
+
|
|
42
|
+
1. **Technical Indicator Analysis**: Evaluate various technical indicators such as moving averages, relative strength index (RSI), and Bollinger Bands to identify trends, patterns, and potential reversals.
|
|
43
|
+
2. **Statistical Pattern Evaluation**: Apply statistical methods to identify patterns in historical data, including mean reversion, momentum, and volatility analysis.
|
|
44
|
+
3. **Risk Metric Calculation**: Calculate risk metrics such as Value-at-Risk (VaR), Expected Shortfall (ES), and Greeks to quantify potential losses and position sensitivity.
|
|
45
|
+
4. **Trade Success Probability**: Provide probability scores for trade success based on historical data analysis, technical indicators, and risk metrics.
|
|
46
|
+
|
|
47
|
+
To accomplish these tasks, you will receive a trading thesis from the Director Agent, outlining the stock under consideration, market position, expected trends, and key factors influencing the stock's performance. Your analysis should build upon this thesis, providing detailed numerical insights to support or challenge the Director's hypothesis.
|
|
48
|
+
|
|
49
|
+
In your analysis, include confidence scores for each aspect of your evaluation, indicating the level of certainty in your findings. This will enable the Director to make informed decisions, weighing the potential benefits against the risks associated with each trade.
|
|
50
|
+
|
|
51
|
+
Your comprehensive analysis will be instrumental in refining the trading strategy, ensuring that it is grounded in empirical evidence and statistical rigor. By working together with the Director Agent, you will contribute to a cohesive and data-driven approach to trading, ultimately enhancing the overall performance of the trading system.
|
|
52
|
+
"""
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class AutoHedgeOutput(BaseModel):
|
|
56
|
+
id: str = uuid.uuid4().hex
|
|
57
|
+
name: Optional[str] = None
|
|
58
|
+
description: Optional[str] = None
|
|
59
|
+
stocks: Optional[list] = None
|
|
60
|
+
task: Optional[str] = None
|
|
61
|
+
thesis: Optional[str] = None
|
|
62
|
+
risk_assessment: Optional[str] = None
|
|
63
|
+
order: Optional[str] = None
|
|
64
|
+
timestamp: str = datetime.now().isoformat()
|
|
65
|
+
current_stock: str
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
# Risk Assessment Agent
|
|
69
|
+
RISK_PROMPT = """You are a Risk Assessment AI. Your primary objective is to evaluate and mitigate potential risks associated with a given trade.
|
|
70
|
+
|
|
71
|
+
Your responsibilities include:
|
|
72
|
+
|
|
73
|
+
1. Evaluating position sizing to determine the optimal amount of capital to allocate to a trade.
|
|
74
|
+
2. Calculating potential drawdown to anticipate and prepare for potential losses.
|
|
75
|
+
3. Assessing market risk factors, such as volatility, liquidity, and market sentiment.
|
|
76
|
+
4. Monitoring correlation risks to identify potential relationships between different assets.
|
|
77
|
+
|
|
78
|
+
To accomplish these tasks, you will be provided with a comprehensive thesis and analysis from the Quantitative Analysis Agent.
|
|
79
|
+
|
|
80
|
+
The thesis will include:
|
|
81
|
+
- A clear direction (long or short) for the trade
|
|
82
|
+
- A confidence level indicating the strength of the trade signal
|
|
83
|
+
- An entry price and stop loss level to define the trade's parameters
|
|
84
|
+
- A take profit level to determine the trade's potential upside
|
|
85
|
+
- A timeframe for the trade, indicating the expected duration
|
|
86
|
+
- Key factors influencing the trade, such as technical indicators or fundamental metrics
|
|
87
|
+
- Potential risks associated with the trade, such as market volatility or economic uncertainty
|
|
88
|
+
|
|
89
|
+
The analysis will include:
|
|
90
|
+
- Technical scores indicating the strength of the trade signal based on technical indicators
|
|
91
|
+
- Volume scores indicating the level of market participation and conviction
|
|
92
|
+
- Trend strength scores indicating the direction and magnitude of the market trend
|
|
93
|
+
- Key levels, such as support and resistance, to identify potential areas of interest
|
|
94
|
+
|
|
95
|
+
Using this information, please provide clear risk metrics and trade size recommendations, including:
|
|
96
|
+
- A recommended position size based on the trade's potential risk and reward
|
|
97
|
+
- A maximum drawdown risk to anticipate and prepare for potential losses
|
|
98
|
+
- A market risk exposure assessment to identify potential risks and opportunities
|
|
99
|
+
- An overall risk score to summarize the trade's potential risks and rewards
|
|
100
|
+
|
|
101
|
+
Your output should be in a structured format, including all relevant metrics and recommendations.
|
|
102
|
+
"""
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
class RiskManager:
|
|
106
|
+
def __init__(self):
|
|
107
|
+
self.risk_agent = Agent(
|
|
108
|
+
agent_name="Risk-Manager",
|
|
109
|
+
system_prompt=RISK_PROMPT,
|
|
110
|
+
llm=model,
|
|
111
|
+
max_loops=1,
|
|
112
|
+
verbose=True,
|
|
113
|
+
context_length=16000,
|
|
114
|
+
)
|
|
115
|
+
|
|
116
|
+
def assess_risk(
|
|
117
|
+
self, stock: str, thesis: str, quant_analysis: str
|
|
118
|
+
) -> str:
|
|
119
|
+
prompt = f"""
|
|
120
|
+
Stock: {stock}
|
|
121
|
+
Thesis: {thesis}
|
|
122
|
+
Quant Analysis: {quant_analysis}
|
|
123
|
+
|
|
124
|
+
Provide risk assessment including:
|
|
125
|
+
1. Recommended position size
|
|
126
|
+
2. Maximum drawdown risk
|
|
127
|
+
3. Market risk exposure
|
|
128
|
+
4. Overall risk score
|
|
129
|
+
"""
|
|
130
|
+
assessment = self.risk_agent.run(prompt)
|
|
131
|
+
|
|
132
|
+
return assessment
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
# Execution Agent
|
|
136
|
+
EXECUTION_PROMPT = """You are a Trade Execution AI. Your responsibilities:
|
|
137
|
+
1. Generate structured order parameters
|
|
138
|
+
2. Set precise entry/exit levels
|
|
139
|
+
3. Determine order types
|
|
140
|
+
4. Specify time constraints
|
|
141
|
+
|
|
142
|
+
Provide exact trade execution details in structured format.
|
|
143
|
+
"""
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
class ExecutionAgent:
|
|
147
|
+
def __init__(self):
|
|
148
|
+
self.execution_agent = Agent(
|
|
149
|
+
agent_name="Execution-Agent",
|
|
150
|
+
system_prompt=EXECUTION_PROMPT,
|
|
151
|
+
llm=model,
|
|
152
|
+
max_loops=1,
|
|
153
|
+
verbose=True,
|
|
154
|
+
context_length=16000,
|
|
155
|
+
)
|
|
156
|
+
|
|
157
|
+
def generate_order(
|
|
158
|
+
self, stock: str, thesis: Dict, risk_assessment: Dict
|
|
159
|
+
) -> str:
|
|
160
|
+
prompt = f"""
|
|
161
|
+
Stock: {stock}
|
|
162
|
+
Thesis: {thesis}
|
|
163
|
+
Risk Assessment: {risk_assessment}
|
|
164
|
+
|
|
165
|
+
Generate trade order including:
|
|
166
|
+
1. Order type (market/limit)
|
|
167
|
+
2. Quantity
|
|
168
|
+
3. Entry price
|
|
169
|
+
4. Stop loss
|
|
170
|
+
5. Take profit
|
|
171
|
+
6. Time in force
|
|
172
|
+
"""
|
|
173
|
+
order = self.execution_agent.run(prompt)
|
|
174
|
+
return order
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
class TradingDirector:
|
|
178
|
+
"""
|
|
179
|
+
Trading Director Agent responsible for generating trading theses and coordinating strategy.
|
|
180
|
+
|
|
181
|
+
Attributes:
|
|
182
|
+
director_agent (Agent): Swarms agent for thesis generation
|
|
183
|
+
tickr (TickrAgent): Agent for market data collection
|
|
184
|
+
output_dir (Path): Directory for storing outputs
|
|
185
|
+
|
|
186
|
+
Methods:
|
|
187
|
+
generate_thesis: Generates trading thesis for a given stock
|
|
188
|
+
save_output: Saves thesis to JSON file
|
|
189
|
+
"""
|
|
190
|
+
|
|
191
|
+
def __init__(
|
|
192
|
+
self, stocks: List[str], output_dir: str = "outputs"
|
|
193
|
+
):
|
|
194
|
+
|
|
195
|
+
logger.info("Initializing Trading Director")
|
|
196
|
+
self.director_agent = Agent(
|
|
197
|
+
agent_name="Trading-Director",
|
|
198
|
+
system_prompt=DIRECTOR_PROMPT,
|
|
199
|
+
llm=model,
|
|
200
|
+
max_loops=1,
|
|
201
|
+
verbose=True,
|
|
202
|
+
context_length=16000,
|
|
203
|
+
)
|
|
204
|
+
self.tickr = TickrAgent(
|
|
205
|
+
stocks=stocks,
|
|
206
|
+
max_loops=1,
|
|
207
|
+
workers=10,
|
|
208
|
+
retry_attempts=1,
|
|
209
|
+
context_length=16000,
|
|
210
|
+
)
|
|
211
|
+
|
|
212
|
+
def generate_thesis(
|
|
213
|
+
self,
|
|
214
|
+
task: str = "Generate a thesis for the stock",
|
|
215
|
+
stock: str = None,
|
|
216
|
+
) -> str:
|
|
217
|
+
"""
|
|
218
|
+
Generate trading thesis for a given stock.
|
|
219
|
+
|
|
220
|
+
Args:
|
|
221
|
+
stock (str): Stock ticker symbol
|
|
222
|
+
|
|
223
|
+
Returns:
|
|
224
|
+
TradingThesis: Generated thesis
|
|
225
|
+
"""
|
|
226
|
+
logger.info(f"Generating thesis for {stock}")
|
|
227
|
+
try:
|
|
228
|
+
market_data = self.tickr.run(
|
|
229
|
+
f"{task} Analyze current market conditions and key metrics for {stock}"
|
|
230
|
+
)
|
|
231
|
+
|
|
232
|
+
prompt = f"""
|
|
233
|
+
Task: {task}
|
|
234
|
+
\n
|
|
235
|
+
Stock: {stock}
|
|
236
|
+
Market Data: {market_data}
|
|
237
|
+
"""
|
|
238
|
+
|
|
239
|
+
thesis = self.director_agent.run(prompt)
|
|
240
|
+
return thesis
|
|
241
|
+
|
|
242
|
+
except Exception as e:
|
|
243
|
+
logger.error(
|
|
244
|
+
f"Error generating thesis for {stock}: {str(e)}"
|
|
245
|
+
)
|
|
246
|
+
raise
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
class QuantAnalyst:
|
|
250
|
+
"""
|
|
251
|
+
Quantitative Analysis Agent responsible for technical and statistical analysis.
|
|
252
|
+
|
|
253
|
+
Attributes:
|
|
254
|
+
quant_agent (Agent): Swarms agent for analysis
|
|
255
|
+
output_dir (Path): Directory for storing outputs
|
|
256
|
+
"""
|
|
257
|
+
|
|
258
|
+
def __init__(self, output_dir: str = "outputs"):
|
|
259
|
+
self.output_dir = Path(output_dir)
|
|
260
|
+
self.output_dir.mkdir(exist_ok=True)
|
|
261
|
+
|
|
262
|
+
logger.info("Initializing Quant Analyst")
|
|
263
|
+
self.quant_agent = Agent(
|
|
264
|
+
agent_name="Quant-Analyst",
|
|
265
|
+
system_prompt=QUANT_PROMPT,
|
|
266
|
+
llm=model,
|
|
267
|
+
max_loops=1,
|
|
268
|
+
verbose=True,
|
|
269
|
+
context_length=16000,
|
|
270
|
+
)
|
|
271
|
+
|
|
272
|
+
def analyze(self, stock: str, thesis: str) -> str:
|
|
273
|
+
"""
|
|
274
|
+
Perform quantitative analysis for a stock.
|
|
275
|
+
|
|
276
|
+
Args:
|
|
277
|
+
stock (str): Stock ticker symbol
|
|
278
|
+
thesis (TradingThesis): Trading thesis
|
|
279
|
+
|
|
280
|
+
Returns:
|
|
281
|
+
QuantAnalysis: Quantitative analysis results
|
|
282
|
+
"""
|
|
283
|
+
logger.info(f"Performing quant analysis for {stock}")
|
|
284
|
+
try:
|
|
285
|
+
prompt = f"""
|
|
286
|
+
Stock: {stock}
|
|
287
|
+
Thesis from your Director: {thesis}
|
|
288
|
+
|
|
289
|
+
Generate quantitative analysis for the {stock}
|
|
290
|
+
|
|
291
|
+
"ticker": str,
|
|
292
|
+
"technical_score": float (0-1),
|
|
293
|
+
"volume_score": float (0-1),
|
|
294
|
+
"trend_strength": float (0-1),
|
|
295
|
+
"volatility": float,
|
|
296
|
+
"probability_score": float (0-1),
|
|
297
|
+
"key_levels": {{
|
|
298
|
+
"support": float,
|
|
299
|
+
"resistance": float,
|
|
300
|
+
"pivot": float
|
|
301
|
+
}}
|
|
302
|
+
"""
|
|
303
|
+
|
|
304
|
+
analysis = self.quant_agent.run(prompt)
|
|
305
|
+
return analysis
|
|
306
|
+
|
|
307
|
+
except Exception as e:
|
|
308
|
+
logger.error(
|
|
309
|
+
f"Error in quant analysis for {stock}: {str(e)}"
|
|
310
|
+
)
|
|
311
|
+
raise
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
class AutomatedTradingSystem:
|
|
315
|
+
"""
|
|
316
|
+
Main trading system that coordinates all agents and manages the trading cycle.
|
|
317
|
+
|
|
318
|
+
Attributes:
|
|
319
|
+
stocks (List[str]): List of stock tickers to trade
|
|
320
|
+
director (TradingDirector): Trading director agent
|
|
321
|
+
quant (QuantAnalyst): Quantitative analysis agent
|
|
322
|
+
risk (RiskManager): Risk management agent
|
|
323
|
+
execution (ExecutionAgent): Trade execution agent
|
|
324
|
+
output_dir (Path): Directory for storing outputs
|
|
325
|
+
"""
|
|
326
|
+
|
|
327
|
+
def __init__(
|
|
328
|
+
self,
|
|
329
|
+
stocks: List[str],
|
|
330
|
+
name: str = "autohedge",
|
|
331
|
+
description: str = "fully autonomous hedgefund",
|
|
332
|
+
output_dir: str = "outputs",
|
|
333
|
+
):
|
|
334
|
+
self.name = name
|
|
335
|
+
self.description = description
|
|
336
|
+
self.stocks = stocks
|
|
337
|
+
self.output_dir = Path(output_dir)
|
|
338
|
+
self.output_dir.mkdir(exist_ok=True)
|
|
339
|
+
|
|
340
|
+
logger.info("Initializing Automated Trading System")
|
|
341
|
+
self.director = TradingDirector(stocks, output_dir)
|
|
342
|
+
self.quant = QuantAnalyst()
|
|
343
|
+
self.risk = RiskManager()
|
|
344
|
+
self.execution = ExecutionAgent()
|
|
345
|
+
self.logs = []
|
|
346
|
+
|
|
347
|
+
def run_trading_cycle(self, task: str, *args, **kwargs):
|
|
348
|
+
"""Execute one complete trading cycle for all stocks"""
|
|
349
|
+
logger.info("Starting trading cycle")
|
|
350
|
+
logs = []
|
|
351
|
+
|
|
352
|
+
try:
|
|
353
|
+
for stock in self.stocks:
|
|
354
|
+
logger.info(f"Processing {stock}")
|
|
355
|
+
|
|
356
|
+
# Generate thesis
|
|
357
|
+
thesis = self.director.generate_thesis(
|
|
358
|
+
task=task, stock=stock
|
|
359
|
+
)
|
|
360
|
+
|
|
361
|
+
# Perform analysis
|
|
362
|
+
analysis = self.quant.analyze(stock, thesis)
|
|
363
|
+
|
|
364
|
+
# Assess risk
|
|
365
|
+
risk_assessment = self.risk.assess_risk(
|
|
366
|
+
stock, thesis, analysis
|
|
367
|
+
)
|
|
368
|
+
|
|
369
|
+
# # Generate order if approved
|
|
370
|
+
order = self.execution.generate_order(
|
|
371
|
+
stock, thesis, risk_assessment
|
|
372
|
+
)
|
|
373
|
+
# logger.info(
|
|
374
|
+
# f"Generated order for {stock}: {order}"
|
|
375
|
+
# )
|
|
376
|
+
|
|
377
|
+
log = AutoHedgeOutput(
|
|
378
|
+
name=self.name,
|
|
379
|
+
description=self.description,
|
|
380
|
+
stocks=self.stocks,
|
|
381
|
+
task=task,
|
|
382
|
+
thesis=thesis,
|
|
383
|
+
risk_assessment=risk_assessment,
|
|
384
|
+
current_stock = stock,
|
|
385
|
+
order=order,
|
|
386
|
+
)
|
|
387
|
+
|
|
388
|
+
logs.append(log.model_dump_json(indent=4))
|
|
389
|
+
|
|
390
|
+
return logs
|
|
391
|
+
|
|
392
|
+
except Exception as e:
|
|
393
|
+
logger.error(f"Error in trading cycle: {str(e)}")
|
|
394
|
+
raise
|
|
395
|
+
|
|
396
|
+
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["poetry-core>=1.0.0"]
|
|
3
|
+
build-backend = "poetry.core.masonry.api"
|
|
4
|
+
|
|
5
|
+
[tool.poetry]
|
|
6
|
+
name = "autohedge"
|
|
7
|
+
version = "0.0.1"
|
|
8
|
+
description = "autohedge - TGSC"
|
|
9
|
+
license = "MIT"
|
|
10
|
+
authors = ["Kye Gomez <kye@apac.ai>"]
|
|
11
|
+
homepage = "https://github.com/The-Swarm-Corporation/AutoHedge"
|
|
12
|
+
documentation = "https://github.com/The-Swarm-Corporation/AutoHedge" # Add this if you have documentation.
|
|
13
|
+
readme = "README.md" # Assuming you have a README.md
|
|
14
|
+
repository = "https://github.com/The-Swarm-Corporation/AutoHedge"
|
|
15
|
+
keywords = ["artificial intelligence", "deep learning", "optimizers", "Prompt Engineering"]
|
|
16
|
+
classifiers = [
|
|
17
|
+
"Development Status :: 4 - Beta",
|
|
18
|
+
"Intended Audience :: Developers",
|
|
19
|
+
"Topic :: Scientific/Engineering :: Artificial Intelligence",
|
|
20
|
+
"License :: OSI Approved :: MIT License",
|
|
21
|
+
"Programming Language :: Python :: 3.9"
|
|
22
|
+
]
|
|
23
|
+
|
|
24
|
+
[tool.poetry.dependencies]
|
|
25
|
+
python = "^3.10"
|
|
26
|
+
swarms = "*"
|
|
27
|
+
tickr-agent="*"
|
|
28
|
+
pydantic = "*"
|
|
29
|
+
loguru = "*"
|
|
30
|
+
swarm-models = "*"
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
[tool.poetry.group.lint.dependencies]
|
|
34
|
+
ruff = "^0.1.6"
|
|
35
|
+
types-toml = "^0.10.8.1"
|
|
36
|
+
types-redis = "^4.3.21.6"
|
|
37
|
+
types-pytz = "^2023.3.0.0"
|
|
38
|
+
black = "^23.1.0"
|
|
39
|
+
types-chardet = "^5.0.4.6"
|
|
40
|
+
mypy-protobuf = "^3.0.0"
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
[tool.autopep8]
|
|
44
|
+
max_line_length = 80
|
|
45
|
+
ignore = "E501,W6" # or ["E501", "W6"]
|
|
46
|
+
in-place = true
|
|
47
|
+
recursive = true
|
|
48
|
+
aggressive = 3
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
[tool.ruff]
|
|
52
|
+
line-length = 70
|
|
53
|
+
|
|
54
|
+
[tool.black]
|
|
55
|
+
line-length = 70
|
|
56
|
+
target-version = ['py38']
|
|
57
|
+
preview = true
|