liurenchaxin/docs/custom_modules_tutorial.md

163 lines
5.8 KiB
Markdown

# Developer Tutorial: Creating Custom Modules
Welcome, contributor! This guide will show you how to extend the "太公心易" system by creating your own custom `MythologyEngine` and `CycleModel`.
The system is built on the principle of decoupling, using Abstract Base Classes (ABCs) to separate the core logic of the `MarketFSM` from the specific cultural or analytical models it uses. By creating new classes that inherit from these ABCs, you can fundamentally change the system's narrative and analytical framework without touching the core FSM logic.
## Part 1: Creating a Custom Mythology Engine
A `MythologyEngine` is responsible for providing the narrative flavor to the system. It maps technical components to mythological figures and processes. Let's create a `GreekMythologyEngine` as an example.
### Step 1: Create a New Python File
Create a new file, for example, `greek_mythology.py`.
### Step 2: Import the `MythologyEngine` ABC
In your new file, import the abstract base class from `mythology.py`:
```python
# greek_mythology.py
from mythology import MythologyEngine
```
### Step 3: Implement the `MythologyEngine` Interface
Create a new class that inherits from `MythologyEngine` and implements all its abstract methods: `get_actor_name`, `get_process_metaphor`, and `get_system_narrative`.
```python
class GreekMythologyEngine(MythologyEngine):
"""
An implementation of the MythologyEngine based on Greek mythology.
"""
def __init__(self):
self._actor_map = {
'collector': 'The Muses',
'refiner': 'Hephaestus',
'verifier': 'Apollo',
'synthesizer': 'Zeus',
}
self._process_map = {
'multi_agent_debate': 'Symposium',
'refinement_process': 'Forging in Aetna',
'external_verification': 'Consulting the Oracle of Delphi',
'final_decision': 'Judgment from Olympus',
}
self._narrative = "This system views the market as a pantheon of competing gods and heroes, striving for dominance on Mount Olympus."
def get_actor_name(self, component: str) -> str:
return self._actor_map.get(component, "An Unknown Titan")
def get_process_metaphor(self, process: str) -> str:
return self._process_map.get(process, "A Herculean Task")
def get_system_narrative(self) -> str:
return self._narrative
```
### Step 4: Integrate with the FSM
Now, you can instantiate your new engine and inject it into the `MarketFSM`. The FSM will work seamlessly with your new narrative layer.
```python
# In your main application file
from market_fsm import MarketFSM
from greek_mythology import GreekMythologyEngine
from cycle_models import TwelveStagesOfLifeCycleModel # We can reuse the old cycle model
# Instantiate your custom engine
greek_engine = GreekMythologyEngine()
cycle_model = TwelveStagesOfLifeCycleModel()
# Inject it into the FSM
fsm = MarketFSM(
mythology_engine=greek_engine,
cycle_model=cycle_model
)
# Run the analysis
fsm.run_analysis({"mock_score": 8})
# The output will now be framed in the language of Greek mythology!
```
## Part 2: Creating a Custom Cycle Model
A `CycleModel` is responsible for analyzing market data and determining the current stage of a given cycle. Let's create a simple `MarketSentimentCycleModel` based on four stages: Greed, Fear, Hope, and Despair.
### Step 1: Create a New Python File
Create a file named `sentiment_cycle.py`.
### Step 2: Import the `CycleModel` ABC
```python
# sentiment_cycle.py
from cycle_models import CycleModel
from typing import Dict, Any, List
```
### Step 3: Implement the `CycleModel` Interface
Create a new class that inherits from `CycleModel` and implements `get_current_stage`, `get_stage_characteristics`, and `get_all_stages`.
```python
class MarketSentimentCycleModel(CycleModel):
"""
A cycle model based on the four stages of market sentiment.
"""
def __init__(self):
self._stages = ["Hope", "Greed", "Fear", "Despair"]
self._characteristics = {
"Hope": {"description": "The market is cautiously optimistic.", "strategy": "Accumulate"},
"Greed": {"description": "Euphoria and high expectations dominate.", "strategy": "Take profits"},
"Fear": {"description": "Panic and uncertainty are widespread.", "strategy": "Reduce risk"},
"Despair": {"description": "Capitulation, the market has given up hope.", "strategy": "Look for bargains"},
}
def get_current_stage(self, data: Dict[str, Any]) -> str:
# A real implementation would analyze news sentiment, VIX, etc.
# Here, we'll use a mock sentiment score from 0 to 1.
sentiment_score = data.get("sentiment", 0.5)
if sentiment_score > 0.75:
return "Greed"
elif sentiment_score > 0.5:
return "Hope"
elif sentiment_score > 0.25:
return "Fear"
else:
return "Despair"
def get_stage_characteristics(self, stage: str) -> Dict[str, Any]:
return self._characteristics.get(stage, {})
def get_all_stages(self) -> List[str]:
return self._stages
```
### Step 4: Integrate with the FSM
You can now use your new cycle model in the FSM, even combining it with a different mythology engine.
```python
# In your main application file
from market_fsm import MarketFSM
from mythology import DaoistMythologyEngine
from sentiment_cycle import MarketSentimentCycleModel
# Instantiate your custom cycle model
sentiment_model = MarketSentimentCycleModel()
daoist_engine = DaoistMythologyEngine()
# Inject it into the FSM
fsm = MarketFSM(
mythology_engine=daoist_engine,
cycle_model=sentiment_model
)
# Run the analysis with data your new model understands
fsm.run_analysis({"sentiment": 0.2})
# The FSM will now report the market is in a state of "Despair".
```
Congratulations! You have successfully extended the "太公心易" system.