Skip to content

Commit

Permalink
use strategy code instead number with StrategyFactory
Browse files Browse the repository at this point in the history
  • Loading branch information
msaltnet committed Mar 30, 2023
1 parent fb0cfa4 commit 3403c69
Show file tree
Hide file tree
Showing 18 changed files with 160 additions and 91 deletions.
2 changes: 1 addition & 1 deletion integration_tests/data/mass_simulation_config.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"title": "SMA-1Hour",
"budget": 50000,
"strategy": 1,
"strategy": "BNH",
"interval": 0.5,
"currency": "BTC",
"description": "mass-simulation-integration-test",
Expand Down
4 changes: 2 additions & 2 deletions integration_tests/simulator_ITG_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ def test_ITG_run_single_simulation(self, mock_print):
simulator = Simulator(
budget=1000000,
interval=interval,
strategy=0,
strategy="BNH",
from_dash_to=from_dash_to,
currency="BTC",
)
Expand All @@ -38,7 +38,7 @@ def test_ITG_run_simulation(self, mock_print, mock_input):
"200430.073000", # 시뮬레이션 기간 종료점
"0.1", # interval
"1000000", # budget
"0", # strategy
"BNH", # strategy
"ETH", # currency
"1", # 상태 출력
"r", # 시뮬레이션 시작
Expand Down
9 changes: 9 additions & 0 deletions smtm/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from .strategy_bnh import StrategyBuyAndHold
from .strategy_sma_0 import StrategySma0
from .strategy_rsi import StrategyRsi
from .strategy_factory import StrategyFactory
from .virtual_market import VirtualMarket
from .worker import Worker
from .simulator import Simulator
Expand All @@ -27,6 +28,7 @@
from .mass_simulator import MassSimulator

__all__ = [
"DateConverter",
"Operator",
"LogManager",
"Analyzer",
Expand All @@ -36,13 +38,20 @@
"StrategyBuyAndHold",
"StrategySma0",
"StrategyRsi",
"StrategyFactory",
"VirtualMarket",
"Worker",
"Simulator",
"UpbitTrader",
"BithumbTrader",
"BithumbDataProvider",
"DemoTrader",
"UpbitDataProvider",
"MassSimulator",
"Controller",
"JptController",
"TelegramController",
"DataRepository",
"Database",
]
__version__ = "1.1.0"
16 changes: 8 additions & 8 deletions smtm/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,13 @@
Example)
python -m smtm --mode 0
python -m smtm --mode 1
python -m smtm --mode 1 --budget 500 --from_dash_to 201220.170000-201221 --term 1 --strategy 0 --currency BTC
python -m smtm --mode 2 --budget 50000 --term 60 --strategy 0 --currency ETH
python -m smtm --mode 2 --budget 50000 --term 60 --strategy 0 --currency ETH --demo 1
python -m smtm --mode 1 --budget 500 --from_dash_to 201220.170000-201221 --term 1 --strategy BNH --currency BTC
python -m smtm --mode 2 --budget 50000 --term 60 --strategy BNH --currency ETH
python -m smtm --mode 2 --budget 50000 --term 60 --strategy BNH --currency ETH --demo 1
python -m smtm --mode 3
python -m smtm --mode 3 --demo 1
python -m smtm --mode 4 --config /data/sma0_simulation.json
python -m smtm --mode 5 --budget 50000 --title SMA_2H_week --strategy 1 --currency ETH --from_dash_to 210804.000000-210811.000000 --offset 120 --file generated_config.json
python -m smtm --mode 5 --budget 50000 --title SMA_2H_week --strategy SMA --currency ETH --from_dash_to 210804.000000-210811.000000 --offset 120 --file generated_config.json
"""
import argparse
from argparse import RawTextHelpFormatter
Expand All @@ -38,18 +38,18 @@
Example)
python -m smtm --mode 0
python -m smtm --mode 1 --budget 50000 --from_dash_to 201220.170000-201221 --term 0.1 --strategy 0 --currency BTC
python -m smtm --mode 2 --budget 50000 --term 60 --strategy 0 --currency ETH
python -m smtm --mode 1 --budget 50000 --from_dash_to 201220.170000-201221 --term 0.1 --strategy BNH --currency BTC
python -m smtm --mode 2 --budget 50000 --term 60 --strategy BNH --currency ETH
python -m smtm --mode 3
python -m smtm --mode 3 --demo 1 --token <telegram chat-bot token> --chatid <chat id>
python -m smtm --mode 4 --config /data/sma0_simulation.json
python -m smtm --mode 5 --budget 50000 --title SMA_6H_week --strategy 1 --currency ETH --from_dash_to 210804.000000-210811.000000 --offset 360 --file generated_config.json
python -m smtm --mode 5 --budget 50000 --title SMA_6H_week --strategy SMA --currency ETH --from_dash_to 210804.000000-210811.000000 --offset 360 --file generated_config.json
""",
formatter_class=RawTextHelpFormatter,
)
parser.add_argument("--budget", help="budget", type=int, default=10000)
parser.add_argument("--term", help="trading tick interval (seconds)", type=float, default="60")
parser.add_argument("--strategy", help="strategy 0: buy and hold, 1: sma0, 2: rsi", default="0")
parser.add_argument("--strategy", help="BNH: buy and hold, SMA: sma, RSI: rsi", default="BNH")
parser.add_argument("--trader", help="trader 0: Upbit, 1: Bithumb", default="0")
parser.add_argument("--currency", help="trading currency e.g.BTC", default="BTC")
parser.add_argument("--config", help="mass simulation config file", default="")
Expand Down
18 changes: 5 additions & 13 deletions smtm/controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,7 @@
UpbitDataProvider,
BithumbTrader,
BithumbDataProvider,
StrategyBuyAndHold,
StrategySma0,
StrategyRsi,
StrategyFactory,
Operator,
)

Expand All @@ -23,7 +21,7 @@ class Controller:
def __init__(
self,
interval=10,
strategy=0,
strategy="BNH",
budget=50000,
currency="BTC",
is_bithumb=False,
Expand All @@ -41,15 +39,9 @@ def __init__(
self.currency = currency
LogManager.set_stream_level(30)

strategy_num = int(strategy)
if strategy_num == 0:
self.strategy = StrategyBuyAndHold()
elif strategy_num == 1:
self.strategy = StrategySma0()
elif strategy_num == 2:
self.strategy = StrategyRsi()
else:
raise UserWarning(f"Invalid Strategy! {self.strategy}")
self.strategy = StrategyFactory.create(strategy)
if self.strategy == None:
raise UserWarning(f"Invalid Strategy! {strategy}")

def create_command(self):
"""명령어 정보를 생성한다"""
Expand Down
13 changes: 8 additions & 5 deletions smtm/jpt_controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,7 @@
UpbitDataProvider,
BithumbTrader,
BithumbDataProvider,
StrategyBuyAndHold,
StrategySma0,
StrategyFactory,
Operator,
)

Expand All @@ -29,7 +28,7 @@ def __init__(
):
self.interval = interval
self.budget = budget
self.strategy_num = strategy
self.strategy_code = strategy
self.strategy = None
self.market = market
self.commission_ratio = commission_ratio
Expand All @@ -40,9 +39,13 @@ def __init__(
def initialize(self, interval=10, strategy=0, budget=50000, is_bithumb=False):
"""설정 값으로 초기화"""
self.interval = interval
self.strategy_num = strategy
self.strategy_code = strategy
self.budget = budget
self.strategy = StrategyBuyAndHold() if self.strategy_num == 0 else StrategySma0()

self.strategy = StrategyFactory.create(self.strategy_code)
if self.strategy == None:
raise UserWarning(f"Invalid Strategy! {self.strategy_code}")

self.operator = Operator()
if is_bithumb:
data_provider = BithumbDataProvider(currency=self.market)
Expand Down
32 changes: 9 additions & 23 deletions smtm/mass_simulator.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,7 @@
LogManager,
DateConverter,
SimulationDataProvider,
StrategyBuyAndHold,
StrategySma0,
StrategyRsi,
StrategyFactory,
SimulationOperator,
SimulationTrader,
Analyzer,
Expand Down Expand Up @@ -119,7 +117,7 @@ def get_score_callback(report):
return last_report

@staticmethod
def get_initialized_operator(budget, strategy_num, interval, currency, start, end, tag):
def get_initialized_operator(budget, strategy_code, interval, currency, start, end, tag):
"""시뮬레이션 오퍼레이션 생성 후 주어진 설정 값으로 초기화 하여 반환"""
dt = DateConverter.to_end_min(start_iso=start, end_iso=end)
end = dt[0][1]
Expand All @@ -128,18 +126,11 @@ def get_initialized_operator(budget, strategy_num, interval, currency, start, en
data_provider = SimulationDataProvider(currency=currency)
data_provider.initialize_simulation(end=end, count=count)

strategy_number = int(strategy_num)
if strategy_number == 0:
strategy = StrategyBuyAndHold()
elif strategy_number == 1:
strategy = StrategySma0()
elif strategy_number == 2:
strategy = StrategyRsi()
else:
raise UserWarning(f"Invalid Strategy! {strategy_number}")
strategy = StrategyFactory.create(strategy_code)
if strategy == None:
raise UserWarning(f"Invalid Strategy! {strategy_code}")

strategy.is_simulation = True

trader = SimulationTrader(currency=currency)
trader.initialize_simulation(end=end, count=count, budget=budget)

Expand Down Expand Up @@ -261,15 +252,10 @@ def analyze_result(self, result_list, config):
title = config["title"]
period_list = config["period_list"]

strategy_number = int(config["strategy"])
if strategy_number == 0:
strategy_name = StrategyBuyAndHold.NAME
elif strategy_number == 1:
strategy_name = StrategySma0.NAME
elif strategy_number == 2:
strategy_name = StrategyRsi.NAME
else:
raise UserWarning(f"Invalid Strategy! {strategy_number}")
strategy_code = config["strategy"]
strategy_name = StrategyFactory.get_name(strategy_code)
if strategy_name == None:
raise UserWarning(f"Invalid Strategy! {strategy_code}")

final_return_list = []
min_return_list = []
Expand Down
27 changes: 13 additions & 14 deletions smtm/simulator.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,7 @@
Analyzer,
SimulationTrader,
SimulationDataProvider,
StrategyBuyAndHold,
StrategySma0,
StrategyRsi,
StrategyFactory,
SimulationOperator,
DateConverter,
)
Expand Down Expand Up @@ -38,7 +36,7 @@ def __init__(
self,
budget=50000,
interval=2,
strategy=0,
strategy="BNH",
from_dash_to="201220.170000-201220.180000",
currency="BTC",
):
Expand All @@ -48,7 +46,7 @@ def __init__(
self.end_str = "200430.180000"
self.interval = interval
self.operator = None
self.strategy = int(strategy)
self.strategy = strategy
self.budget = int(budget)
self.need_init = True
self.currency = currency
Expand Down Expand Up @@ -102,6 +100,12 @@ def __init__(
},
]

all = StrategyFactory.get_all_strategy_info()
strategy_guide = []
for strategy in all:
strategy_guide.append(strategy["code"])
strategy_guide = ", ".join(strategy_guide)
strategy_guide = "전략 코드 입력. " + strategy_guide
self.config_list = [
{
"guide": "년월일.시분초 형식으로 시작 시점 입력. 예. 201220.162300",
Expand All @@ -124,7 +128,7 @@ def __init__(
"action": self._set_budget,
},
{
"guide": "전략 번호 입력. 0: Buy and Hold, 1: SMA-0, 2: RSI",
"guide": strategy_guide,
"value": self.strategy,
"action": self._set_strategy,
},
Expand All @@ -142,13 +146,8 @@ def initialize(self):
end = dt[0][1]
count = dt[0][2]

if self.strategy == 0:
strategy = StrategyBuyAndHold()
elif self.strategy == 1:
strategy = StrategySma0()
elif self.strategy == 2:
strategy = StrategyRsi()
else:
strategy = StrategyFactory.create(self.strategy)
if strategy == None:
raise UserWarning(f"Invalid Strategy! {self.strategy}")

strategy.is_simulation = True
Expand Down Expand Up @@ -271,7 +270,7 @@ def _set_budget(self, value):
self.budget = next_value

def _set_strategy(self, value):
self.strategy = int(value)
self.strategy = value

def _set_currency(self, value):
self.currency = value
Expand Down
3 changes: 3 additions & 0 deletions smtm/strategy.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ class Strategy(metaclass=ABCMeta):
데이터를 받아서 매매 판단을 하고 결과를 받아서 다음 판단에 반영하는 전략 클래스
"""

CODE = "---"
NAME = "---"

@abstractmethod
def initialize(self, budget, min_price=100, add_spot_callback=None):
"""예산을 설정하고 초기화한다
Expand Down
1 change: 1 addition & 0 deletions smtm/strategy_bnh.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ class StrategyBuyAndHold(Strategy):
ISO_DATEFORMAT = "%Y-%m-%dT%H:%M:%S"
COMMISSION_RATIO = 0.0005
NAME = "BnH"
CODE = "BNH"

def __init__(self):
self.is_intialized = False
Expand Down
28 changes: 28 additions & 0 deletions smtm/strategy_factory.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
"""Strategy 정보 조회 및 생성을 담당하는 Factory 클래스"""

from . import StrategyBuyAndHold, StrategySma0, StrategyRsi


class StrategyFactory:
"""Strategy 정보 조회 및 생성을 담당하는 Factory 클래스"""

STRATEGY_LIST = [StrategyBuyAndHold, StrategySma0, StrategyRsi]

@staticmethod
def create(code):
for strategy in StrategyFactory.STRATEGY_LIST:
if strategy.CODE == code:
return strategy()

@staticmethod
def get_name(code):
for strategy in StrategyFactory.STRATEGY_LIST:
if strategy.CODE == code:
return strategy.NAME

@staticmethod
def get_all_strategy_info():
all = []
for strategy in StrategyFactory.STRATEGY_LIST:
all.append({"name": strategy.NAME, "code": strategy.CODE, "class": strategy})
return all
1 change: 1 addition & 0 deletions smtm/strategy_rsi.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ class StrategyRsi(Strategy):
RSI_HIGH = 70
RSI_COUNT = 14
NAME = "RSI"
CODE = "RSI"

def __init__(self):
self.is_intialized = False
Expand Down
1 change: 1 addition & 0 deletions smtm/strategy_sma_0.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ class StrategySma0(Strategy):
LONG = 60
STEP = 1
NAME = "SMA0-I"
CODE = "SMA"
STD_K = 25
STD_RATIO = 0.00015
PREDICT_N = 3
Expand Down
Loading

0 comments on commit 3403c69

Please sign in to comment.