investfly-sdk 1.0__py3-none-any.whl → 1.2__py3-none-any.whl
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.
- investfly/__init__.py +5 -0
- investfly/api/IndicatorApiClient.py +24 -0
- investfly/api/InvestflyApiClient.py +27 -1
- investfly/api/MarketDataApiClient.py +4 -0
- investfly/api/PortfolioApiClient.py +4 -0
- investfly/api/RestApiClient.py +7 -2
- investfly/api/StrategyApiClient.py +45 -0
- investfly/api/__init__.py +17 -0
- investfly/cli/InvestflyCli.py +217 -0
- investfly/models/CommonModels.py +31 -0
- investfly/models/Indicator.py +89 -14
- investfly/models/MarketData.py +13 -2
- investfly/models/MarketDataIds.py +3 -1
- investfly/models/PortfolioModels.py +11 -0
- investfly/models/SecurityUniverseSelector.py +9 -1
- investfly/models/StrategyModels.py +62 -1
- investfly/models/TradingStrategy.py +67 -16
- investfly/models/__init__.py +9 -1
- investfly/samples/strategies/SmaCrossOverTemplate.py +1 -1
- investfly_sdk-1.2.dist-info/METADATA +194 -0
- investfly_sdk-1.2.dist-info/RECORD +39 -0
- {investfly_sdk-1.0.dist-info → investfly_sdk-1.2.dist-info}/WHEEL +1 -1
- investfly_sdk-1.2.dist-info/entry_points.txt +2 -0
- investfly/cli/CliApiClient.py +0 -46
- investfly/cli/commands.py +0 -78
- investfly_sdk-1.0.dist-info/METADATA +0 -53
- investfly_sdk-1.0.dist-info/RECORD +0 -38
- investfly_sdk-1.0.dist-info/entry_points.txt +0 -2
- {investfly_sdk-1.0.dist-info → investfly_sdk-1.2.dist-info}/LICENSE.txt +0 -0
- {investfly_sdk-1.0.dist-info → investfly_sdk-1.2.dist-info}/top_level.txt +0 -0
investfly/__init__.py
CHANGED
@@ -0,0 +1,24 @@
|
|
1
|
+
from typing import List, Dict, Any
|
2
|
+
|
3
|
+
from investfly.api.RestApiClient import RestApiClient
|
4
|
+
from investfly.models import IndicatorSpec
|
5
|
+
|
6
|
+
|
7
|
+
class IndicatorApiClient:
|
8
|
+
|
9
|
+
def __init__(self, restApiClient: RestApiClient) -> None:
|
10
|
+
self.restApiClient = restApiClient
|
11
|
+
|
12
|
+
def listIndicators(self) -> List[IndicatorSpec]:
|
13
|
+
indicatorsListDict = self.restApiClient.doGet('/indicator/list/custom')
|
14
|
+
result: List[IndicatorSpec] = []
|
15
|
+
for indicatorDict in indicatorsListDict:
|
16
|
+
result.append(IndicatorSpec.fromDict(indicatorDict))
|
17
|
+
return result
|
18
|
+
|
19
|
+
def getIndicatorCode(self, indicatorId: str) -> str:
|
20
|
+
return self.restApiClient.doGet(f'/indicator/custom/{indicatorId}/code')
|
21
|
+
|
22
|
+
def createUpdateIndicator(self, code: str) -> IndicatorSpec:
|
23
|
+
specDict: Dict[str, Any] = self.restApiClient.doPostCode('/indicator/custom/update', code)
|
24
|
+
return IndicatorSpec.fromDict(specDict)
|
@@ -1,23 +1,49 @@
|
|
1
1
|
import datetime
|
2
2
|
|
3
|
+
from investfly.api.IndicatorApiClient import IndicatorApiClient
|
3
4
|
from investfly.api.MarketDataApiClient import MarketDataApiClient
|
4
5
|
from investfly.api.PortfolioApiClient import PortfolioApiClient
|
5
6
|
from investfly.api.RestApiClient import RestApiClient
|
7
|
+
from investfly.api.StrategyApiClient import StrategyApiClient
|
8
|
+
from investfly.models import Session
|
6
9
|
|
7
10
|
|
8
11
|
class InvestflyApiClient:
|
12
|
+
"""
|
13
|
+
Investfly API Client. This class should be used as the entry point to make all API calls.
|
14
|
+
After authentication, access marketApi or portfolioApi to make calls to /market or /portfolio endpoints
|
15
|
+
"""
|
9
16
|
|
10
17
|
def __init__(self, baseUrl: str = "https://api.investfly.com"):
|
11
18
|
self.restApiClient = RestApiClient(baseUrl)
|
12
19
|
self.marketApi = MarketDataApiClient(self.restApiClient)
|
20
|
+
"""Class used to make calls to /marketdata and /symbol endpoint to get market and symbol data"""
|
13
21
|
self.portfolioApi = PortfolioApiClient(self.restApiClient)
|
22
|
+
"""Class used to make calls to /portfolio endpoint to get portfolio and brokerage account data"""
|
23
|
+
self.strategyApi = StrategyApiClient(self.restApiClient)
|
24
|
+
"""Class used to make calls to /strategy endpoint to operate on trading strategies"""
|
25
|
+
self.indicatorApi = IndicatorApiClient(self.restApiClient)
|
14
26
|
|
15
|
-
def login(self, username, password):
|
27
|
+
def login(self, username, password) -> Session:
|
28
|
+
"""
|
29
|
+
Login to investfly backend.
|
30
|
+
:param username: Username
|
31
|
+
:param password: Password
|
32
|
+
:return: Session object representing authenticated session
|
33
|
+
"""
|
16
34
|
return self.restApiClient.login(username, password)
|
17
35
|
|
18
36
|
def logout(self):
|
19
37
|
self.restApiClient.logout()
|
20
38
|
|
39
|
+
def isLoggedIn(self) -> bool:
|
40
|
+
return "investfly-client-id" in self.restApiClient.headers
|
41
|
+
|
42
|
+
def getSession(self) -> Session:
|
43
|
+
sessionJson = self.restApiClient.doGet('/user/session')
|
44
|
+
session: Session = Session.fromJsonDict(sessionJson)
|
45
|
+
return session
|
46
|
+
|
21
47
|
@staticmethod
|
22
48
|
def parseDatetime(date_str: str) -> datetime.datetime:
|
23
49
|
return datetime.datetime.strptime(date_str, '%Y-%m-%dT%H:%M:%S.%f%z')
|
@@ -4,6 +4,10 @@ from investfly.api.RestApiClient import RestApiClient
|
|
4
4
|
|
5
5
|
|
6
6
|
class MarketDataApiClient:
|
7
|
+
"""
|
8
|
+
MarketDataApiClient is intended to make calls to /marketdata and /symbol endpoint to get market and symbol data
|
9
|
+
from Investfly
|
10
|
+
"""
|
7
11
|
|
8
12
|
def __init__(self, restApiClient: RestApiClient) -> None:
|
9
13
|
self.restApiClient = restApiClient
|
@@ -6,6 +6,10 @@ from investfly.models.PortfolioModels import Broker, Portfolio, Balances, OpenPo
|
|
6
6
|
|
7
7
|
|
8
8
|
class PortfolioApiClient:
|
9
|
+
"""
|
10
|
+
This class is intended to make REST API calls to /portfolio endpoint to get information on virtual portfolio
|
11
|
+
and connected brokerage account
|
12
|
+
"""
|
9
13
|
|
10
14
|
def __init__(self, restApiClient: RestApiClient) -> None:
|
11
15
|
self.restApiClient = restApiClient
|
investfly/api/RestApiClient.py
CHANGED
@@ -12,6 +12,11 @@ warnings.simplefilter("ignore")
|
|
12
12
|
|
13
13
|
class RestApiClient:
|
14
14
|
|
15
|
+
"""
|
16
|
+
Internal class to make REST API requests. Users of the SDK do not use this class directly.
|
17
|
+
Please use investfly.api.InvestflyApiClient` instead
|
18
|
+
"""
|
19
|
+
|
15
20
|
def __init__(self, baseUrl: str) -> None:
|
16
21
|
self.headers: Dict[str, str] = {}
|
17
22
|
self.baseUrl = baseUrl
|
@@ -30,8 +35,8 @@ class RestApiClient:
|
|
30
35
|
|
31
36
|
def logout(self):
|
32
37
|
requests.post(self.baseUrl + "/user/logout", verify=False)
|
33
|
-
self.
|
34
|
-
self.
|
38
|
+
del self.headers['investfly-client-id']
|
39
|
+
del self.headers['investfly-client-token']
|
35
40
|
|
36
41
|
def doGet(self, url: str) -> Any:
|
37
42
|
res = requests.get(self.baseUrl + url, headers=self.headers, verify=False)
|
@@ -0,0 +1,45 @@
|
|
1
|
+
from typing import List, Any, Dict
|
2
|
+
from investfly.api.RestApiClient import RestApiClient
|
3
|
+
from investfly.models.CommonModels import Message
|
4
|
+
from investfly.models.StrategyModels import TradingStrategyModel, BacktestResult
|
5
|
+
|
6
|
+
|
7
|
+
class StrategyApiClient:
|
8
|
+
|
9
|
+
"""
|
10
|
+
Class used to make calls to /strategy endpoint to operate on trading strategies.
|
11
|
+
"""
|
12
|
+
|
13
|
+
def __init__(self, restApiClient: RestApiClient) -> None:
|
14
|
+
self.restApiClient = restApiClient
|
15
|
+
|
16
|
+
def listStrategies(self) -> List[TradingStrategyModel]:
|
17
|
+
strategiesList: List[Dict[str, Any]] = self.restApiClient.doGet('/strategy/list')
|
18
|
+
strategiesList = list(filter(lambda jsonDict: jsonDict['type'] == 'CUSTOM', strategiesList))
|
19
|
+
return list(map(lambda jsonDict: TradingStrategyModel.fromDict(jsonDict), strategiesList))
|
20
|
+
|
21
|
+
def getStrategy(self, strategyId: int) -> TradingStrategyModel:
|
22
|
+
strategyDict = self.restApiClient.doGet('/strategy/' + str(strategyId))
|
23
|
+
return TradingStrategyModel.fromDict(strategyDict)
|
24
|
+
|
25
|
+
def createStrategy(self, strategyModel: TradingStrategyModel) -> TradingStrategyModel:
|
26
|
+
strategyDict = strategyModel.toDict()
|
27
|
+
strategyDict['type'] = 'CUSTOM'
|
28
|
+
strategyDict = self.restApiClient.doPost('/strategy/create', strategyDict)
|
29
|
+
return TradingStrategyModel.fromDict(strategyDict)
|
30
|
+
|
31
|
+
def updateStrategyCode(self, strategyId: int, code: str) -> str:
|
32
|
+
return self.restApiClient.doPostCode('/strategy/' + str(strategyId) + '/update/code', code)
|
33
|
+
|
34
|
+
def startBacktest(self, strategyId: int) -> Message:
|
35
|
+
message = self.restApiClient.doPost(f'/backtest/{strategyId}/start', {})
|
36
|
+
return Message.fromDict(message)
|
37
|
+
|
38
|
+
def stopBacktest(self, strategyId: int) -> Message:
|
39
|
+
message = self.restApiClient.doPost(f'/backtest/{strategyId}/stop', {})
|
40
|
+
return Message.fromDict(message)
|
41
|
+
|
42
|
+
def getBacktestResult(self, strategyId: int) -> BacktestResult:
|
43
|
+
resultDict: Dict[str, Any] = self.restApiClient.doGet(f'/backtest/{strategyId}/result')
|
44
|
+
return BacktestResult.fromDict(resultDict)
|
45
|
+
|
investfly/api/__init__.py
CHANGED
@@ -0,0 +1,17 @@
|
|
1
|
+
""" This package contains REST API Client classes to make REST API calls to Investfly server.
|
2
|
+
The entry point is `investfly.api.InvestflyApiClient`
|
3
|
+
|
4
|
+
InvestflyApiClient has members to access specific endpoints such as strategyApi, portfolioApi etc
|
5
|
+
|
6
|
+
For now, only those API methods that are commonly used during in strategy development are added in the clients.
|
7
|
+
|
8
|
+
```
|
9
|
+
from investfly.api.InvestflyApiClient import InvestflyApiClient
|
10
|
+
api = InvestflyApiClient()
|
11
|
+
api.login("<YOUR USERNAME>", "<YOUR PASSWORD>")
|
12
|
+
pythonStrategies = api.strategyApi.getStrategies()
|
13
|
+
print(pythonStrategies)
|
14
|
+
api.logout()
|
15
|
+
```
|
16
|
+
|
17
|
+
"""
|
@@ -0,0 +1,217 @@
|
|
1
|
+
import argparse
|
2
|
+
import pickle
|
3
|
+
import os.path
|
4
|
+
import time
|
5
|
+
from typing import List
|
6
|
+
|
7
|
+
from investfly.api.InvestflyApiClient import InvestflyApiClient
|
8
|
+
from investfly.models import Session, IndicatorSpec
|
9
|
+
from investfly.models.StrategyModels import TradingStrategyModel, BacktestResult, BacktestStatus, BacktestResultStatus
|
10
|
+
|
11
|
+
from investfly import samples
|
12
|
+
import inspect
|
13
|
+
from pathlib import Path
|
14
|
+
import shutil
|
15
|
+
|
16
|
+
|
17
|
+
class InvestflyCli:
|
18
|
+
|
19
|
+
def __init__(self):
|
20
|
+
self.running: bool = True
|
21
|
+
self.investflyApi = InvestflyApiClient()
|
22
|
+
|
23
|
+
|
24
|
+
def __loginAction(self, args: argparse.Namespace) -> Session:
|
25
|
+
username = args.username
|
26
|
+
password = args.password
|
27
|
+
session = self.investflyApi.login(username, password)
|
28
|
+
return session
|
29
|
+
|
30
|
+
def __logoutAction(self, args: argparse.Namespace) -> None:
|
31
|
+
self.investflyApi.logout()
|
32
|
+
|
33
|
+
def __exitAction(self, args: argparse.Namespace|None) -> None:
|
34
|
+
if self.investflyApi.isLoggedIn():
|
35
|
+
self.investflyApi.logout()
|
36
|
+
self.running = False
|
37
|
+
|
38
|
+
def __copySamples(self, args: argparse.Namespace) -> str:
|
39
|
+
samplesPath = inspect.getfile(samples)
|
40
|
+
path = Path(samplesPath)
|
41
|
+
parentPath = path.parent
|
42
|
+
shutil.copytree(parentPath, './samples', dirs_exist_ok=True)
|
43
|
+
return "Samples copied to ./samples directory"
|
44
|
+
|
45
|
+
|
46
|
+
# ==== Strategy Command Handlers
|
47
|
+
|
48
|
+
def __listStrategies(self, args: argparse.Namespace) -> str:
|
49
|
+
strategies: List[TradingStrategyModel] = self.investflyApi.strategyApi.listStrategies()
|
50
|
+
strategiesDictList = list(map(lambda model: str({'strategyId': model.strategyId, 'strategyName': model.strategyName}), strategies))
|
51
|
+
return "\n".join(strategiesDictList)
|
52
|
+
|
53
|
+
def __createStrategy(self, args: argparse.Namespace) -> str:
|
54
|
+
name = args.name
|
55
|
+
path = args.file
|
56
|
+
with open(path, 'r') as source_file:
|
57
|
+
code = source_file.read()
|
58
|
+
tradingStrategyModel = TradingStrategyModel(strategyName=name, strategyDesc=name, pythonCode=code)
|
59
|
+
tradingStrategyModel = self.investflyApi.strategyApi.createStrategy(tradingStrategyModel)
|
60
|
+
return f'Created strategy {tradingStrategyModel.strategyId}'
|
61
|
+
|
62
|
+
def __downloadCode(self, args: argparse.Namespace) -> str:
|
63
|
+
strategyId = int(args.id)
|
64
|
+
path = args.file
|
65
|
+
strategyModel: TradingStrategyModel = self.investflyApi.strategyApi.getStrategy(strategyId)
|
66
|
+
with open(path, 'w') as out_file:
|
67
|
+
out_file.write(strategyModel.pythonCode)
|
68
|
+
return f"Strategy saved to {path}"
|
69
|
+
|
70
|
+
def __updateCode(self, args: argparse.Namespace) -> str:
|
71
|
+
strategyId = int(args.id)
|
72
|
+
path = args.file
|
73
|
+
with open(path, 'r') as source_file:
|
74
|
+
code = source_file.read()
|
75
|
+
self.investflyApi.strategyApi.updateStrategyCode(strategyId, code)
|
76
|
+
return 'Code Updated'
|
77
|
+
|
78
|
+
def __startBacktest(self, args: argparse.Namespace) -> str:
|
79
|
+
strategyId = int(args.id)
|
80
|
+
message = self.investflyApi.strategyApi.startBacktest(strategyId)
|
81
|
+
return str(message.toDict())
|
82
|
+
|
83
|
+
def __stopBacktest(self, args: argparse.Namespace) -> str:
|
84
|
+
strategyId = int(args.id)
|
85
|
+
message = self.investflyApi.strategyApi.stopBacktest(strategyId)
|
86
|
+
return str(message.toDict())
|
87
|
+
|
88
|
+
def __pollResults(self, args: argparse.Namespace) -> str:
|
89
|
+
strategyId = int(args.id)
|
90
|
+
backtestResult: BacktestResult = self.investflyApi.strategyApi.getBacktestResult(strategyId)
|
91
|
+
backtestStatus: BacktestResultStatus = backtestResult.status
|
92
|
+
print(str(backtestStatus.toDict()))
|
93
|
+
notFinished = backtestStatus.jobStatus == BacktestStatus.QUEUED or backtestStatus.jobStatus == BacktestStatus.INITIALIZING or backtestStatus.jobStatus == BacktestStatus.RUNNING
|
94
|
+
try:
|
95
|
+
while notFinished:
|
96
|
+
time.sleep(3)
|
97
|
+
backtestResult: BacktestResult = self.investflyApi.strategyApi.getBacktestResult(strategyId)
|
98
|
+
backtestStatus: BacktestResultStatus = backtestResult.status
|
99
|
+
print(str(backtestStatus.toDict()))
|
100
|
+
notFinished = backtestStatus.jobStatus == BacktestStatus.QUEUED or backtestStatus.jobStatus == BacktestStatus.INITIALIZING or backtestStatus.jobStatus == BacktestStatus.RUNNING
|
101
|
+
except KeyboardInterrupt as e:
|
102
|
+
print("Interrupted")
|
103
|
+
pass
|
104
|
+
return str(backtestResult.performance)
|
105
|
+
|
106
|
+
# ==== INDICATOR COMMAND HANDLERS
|
107
|
+
|
108
|
+
def __listIndicators(self, args: argparse.Namespace) -> str:
|
109
|
+
indicators: List[IndicatorSpec] = self.investflyApi.indicatorApi.listIndicators()
|
110
|
+
idList = list(map(lambda spec: spec.indicatorId, indicators))
|
111
|
+
return str(idList)
|
112
|
+
|
113
|
+
def __createUpdateIndicator(self, args: argparse.Namespace):
|
114
|
+
path = args.file
|
115
|
+
with open(path, 'r') as source_file:
|
116
|
+
code = source_file.read()
|
117
|
+
self.investflyApi.indicatorApi.createUpdateIndicator(code)
|
118
|
+
|
119
|
+
def __downloadIndicatorCode(self, args: argparse.Namespace):
|
120
|
+
indicatorId = args.id
|
121
|
+
path = args.file
|
122
|
+
code = self.investflyApi.indicatorApi.getIndicatorCode(indicatorId)
|
123
|
+
with open(path, 'w') as out_file:
|
124
|
+
out_file.write(code)
|
125
|
+
return f"Indicator saved to {path}"
|
126
|
+
|
127
|
+
def runCli(self) -> None:
|
128
|
+
parser = argparse.ArgumentParser(prog="investfly-cli")
|
129
|
+
subparser = parser.add_subparsers(help='Available Commands', dest="command")
|
130
|
+
|
131
|
+
parser_login = subparser.add_parser('login', help='Login to Investfly')
|
132
|
+
parser_login.add_argument('-u', '--username', required=True, help='Input username')
|
133
|
+
parser_login.add_argument('-p', '--password', required=True, help='Input user password')
|
134
|
+
parser_login.set_defaults(func=self.__loginAction)
|
135
|
+
|
136
|
+
parser_logout = subparser.add_parser('logout', help="Logout from Investfly")
|
137
|
+
parser_logout.set_defaults(func=self.__logoutAction)
|
138
|
+
|
139
|
+
parser_copySamples = subparser.add_parser('copysamples', help='Copy Strategy and Indicator Samples from SDK')
|
140
|
+
parser_copySamples.set_defaults(func=self.__copySamples)
|
141
|
+
|
142
|
+
parser_exit = subparser.add_parser('exit', help='Stop and Exit CLI')
|
143
|
+
parser_exit.set_defaults(func = self.__exitAction)
|
144
|
+
|
145
|
+
# ======= STRATEGY COMMANDS ==========
|
146
|
+
|
147
|
+
parser_listStrategies = subparser.add_parser('strategy.list', help='List Python Strategies')
|
148
|
+
parser_listStrategies.set_defaults(func=self.__listStrategies)
|
149
|
+
|
150
|
+
parser_createStrategy = subparser.add_parser('strategy.create', help='Create a new trading strategy')
|
151
|
+
parser_createStrategy.add_argument('-n', '--name', required=True, help='Strategy Name')
|
152
|
+
parser_createStrategy.add_argument('-f', '--file', required=True, help='Python File Path relative to the project root that contains strategy code')
|
153
|
+
parser_createStrategy.set_defaults(func=self.__createStrategy)
|
154
|
+
|
155
|
+
parser_downloadStrategy = subparser.add_parser('strategy.download', help='Download one of your strategy python code and save it to a file')
|
156
|
+
parser_downloadStrategy.add_argument('-i', '--id', required=True, help='Strategy ID')
|
157
|
+
parser_downloadStrategy.add_argument('-f', '--file', required=True, help='File path (with file name) to save strategy python code')
|
158
|
+
parser_downloadStrategy.set_defaults(func=self.__downloadCode)
|
159
|
+
|
160
|
+
parser_updateCode = subparser.add_parser('strategy.update', help='Update strategy Python Code')
|
161
|
+
parser_updateCode.add_argument('-i', '--id', required=True, help='Strategy ID')
|
162
|
+
parser_updateCode.add_argument('-f', '--file', required=True, help='File path (with file name) that contains strategy code')
|
163
|
+
parser_updateCode.set_defaults(func=self.__updateCode)
|
164
|
+
|
165
|
+
parser_startBacktest = subparser.add_parser('strategy.backtest.start', help='Start backtest for strategy')
|
166
|
+
parser_startBacktest.add_argument('-i', '--id', required=True, help='Strategy ID')
|
167
|
+
parser_startBacktest.set_defaults(func=self.__startBacktest)
|
168
|
+
|
169
|
+
parser_stopBacktest = subparser.add_parser('strategy.backtest.stop', help='Stop backtest for strategy')
|
170
|
+
parser_stopBacktest.add_argument('-i', '--id', required=True, help='Strategy ID')
|
171
|
+
parser_stopBacktest.set_defaults(func=self.__stopBacktest)
|
172
|
+
|
173
|
+
parser_resultBacktest = subparser.add_parser('strategy.backtest.result', help='Get backtest result, waiting if backtest is still running')
|
174
|
+
parser_resultBacktest.add_argument('-i', '--id', required=True, help='Strategy ID')
|
175
|
+
parser_resultBacktest.set_defaults(func=self.__pollResults)
|
176
|
+
|
177
|
+
# ====== INDICATOR COMMANDS ====
|
178
|
+
|
179
|
+
parser_listIndicators = subparser.add_parser('indicator.list', help='List Custom Indicators')
|
180
|
+
parser_listIndicators.set_defaults(func=self.__listIndicators)
|
181
|
+
|
182
|
+
parser_downloadIndicator = subparser.add_parser('indicator.download', help='Download indicator python code and save it to a file')
|
183
|
+
parser_downloadIndicator.add_argument('-i', '--id', required=True, help='IndicatorId ID')
|
184
|
+
parser_downloadIndicator.add_argument('-f', '--file', required=True, help='File path (with file name) to save indicator python code')
|
185
|
+
parser_downloadIndicator.set_defaults(func=self.__downloadIndicatorCode)
|
186
|
+
|
187
|
+
parser_createUpdateIndicator = subparser.add_parser('indicator.update', help='Create or update indicator. Indicator ID is retried from ClassName')
|
188
|
+
parser_createUpdateIndicator.add_argument('-f', '--file', required=True, help='File path (with file name) that contains indicator code')
|
189
|
+
parser_createUpdateIndicator.set_defaults(func=self.__createUpdateIndicator)
|
190
|
+
|
191
|
+
while self.running:
|
192
|
+
try:
|
193
|
+
data = input("\ninvestfly-cli$ ")
|
194
|
+
args = parser.parse_args(data.split())
|
195
|
+
if args.command is None:
|
196
|
+
# When user hits Enter without any command
|
197
|
+
parser.print_help()
|
198
|
+
else:
|
199
|
+
result = args.func(args)
|
200
|
+
if result is not None:
|
201
|
+
print(result)
|
202
|
+
except SystemExit:
|
203
|
+
# System exit is caught because when -h is used, argparser displays help and exists the apputils with SystemExit
|
204
|
+
pass
|
205
|
+
except KeyboardInterrupt:
|
206
|
+
self.__exitAction(None)
|
207
|
+
except Exception as e:
|
208
|
+
print("Received exception " + str(e))
|
209
|
+
|
210
|
+
|
211
|
+
|
212
|
+
def main():
|
213
|
+
investflyCli = InvestflyCli()
|
214
|
+
investflyCli.runCli()
|
215
|
+
|
216
|
+
if __name__ == '__main__':
|
217
|
+
main()
|
investfly/models/CommonModels.py
CHANGED
@@ -10,6 +10,9 @@ from investfly.models.ModelUtils import ModelUtils
|
|
10
10
|
|
11
11
|
@dataclass
|
12
12
|
class DatedValue:
|
13
|
+
"""
|
14
|
+
Data Container class to hold Time,Value for timed numeric values
|
15
|
+
"""
|
13
16
|
date: datetime
|
14
17
|
value: float | int
|
15
18
|
|
@@ -25,6 +28,11 @@ class DatedValue:
|
|
25
28
|
|
26
29
|
|
27
30
|
class TimeUnit(str, Enum):
|
31
|
+
|
32
|
+
"""
|
33
|
+
TimeUnit Enum (MINUTES, HOURS, DAYS)
|
34
|
+
"""
|
35
|
+
|
28
36
|
MINUTES = "MINUTES"
|
29
37
|
HOURS = "HOURS"
|
30
38
|
DAYS = "DAYS"
|
@@ -38,6 +46,7 @@ class TimeUnit(str, Enum):
|
|
38
46
|
|
39
47
|
@dataclass
|
40
48
|
class TimeDelta:
|
49
|
+
""" TimeDelta container class similar to python timedelta """
|
41
50
|
value: int
|
42
51
|
unit: TimeUnit
|
43
52
|
|
@@ -58,9 +67,31 @@ class TimeDelta:
|
|
58
67
|
return TimeDelta(json_dict['value'], TimeUnit[json_dict['unit']])
|
59
68
|
|
60
69
|
|
70
|
+
class MessageType(str, Enum):
|
71
|
+
ERROR = "ERROR"
|
72
|
+
SUCCESS = "SUCCESS"
|
73
|
+
WARN = "WARN"
|
74
|
+
|
75
|
+
@dataclass
|
76
|
+
class Message:
|
77
|
+
type: MessageType
|
78
|
+
message: str
|
79
|
+
|
80
|
+
def toDict(self) -> Dict[str, Any]:
|
81
|
+
return self.__dict__.copy()
|
82
|
+
|
83
|
+
@staticmethod
|
84
|
+
def fromDict(json_dict: Dict[str, Any]) -> Message:
|
85
|
+
return Message(MessageType[json_dict['type']], json_dict['message'])
|
86
|
+
|
87
|
+
|
88
|
+
|
61
89
|
|
62
90
|
@dataclass
|
63
91
|
class Session:
|
92
|
+
|
93
|
+
""" Class that represents logged in user session with the Investfly server """
|
94
|
+
|
64
95
|
username: str
|
65
96
|
clientId: str
|
66
97
|
clientToken: str
|
investfly/models/Indicator.py
CHANGED
@@ -1,3 +1,5 @@
|
|
1
|
+
from __future__ import annotations
|
2
|
+
|
1
3
|
from abc import ABC, abstractmethod
|
2
4
|
from dataclasses import dataclass
|
3
5
|
from enum import Enum
|
@@ -9,6 +11,9 @@ from investfly.models.SecurityFilterModels import DataSource, DataParam
|
|
9
11
|
|
10
12
|
|
11
13
|
class ParamType(str, Enum):
|
14
|
+
|
15
|
+
""" Indicator Param Type """
|
16
|
+
|
12
17
|
INTEGER = 'INTEGER'
|
13
18
|
FLOAT = 'FLOAT'
|
14
19
|
BOOLEAN = 'BOOLEAN'
|
@@ -24,12 +29,22 @@ class ParamType(str, Enum):
|
|
24
29
|
|
25
30
|
@dataclass
|
26
31
|
class IndicatorParamSpec:
|
32
|
+
|
33
|
+
""" Class that represents Indicator Parameter Specification """
|
34
|
+
|
27
35
|
paramType: ParamType
|
36
|
+
""" Parameter Type (INTEGER, FLOAT, BOOLEAN, STRING, BARINTERVAL) """
|
28
37
|
|
29
38
|
required: bool = True
|
39
|
+
""" Whether this parameter is required or optional"""
|
40
|
+
|
30
41
|
# The default value here is just a "hint" to the UI to auto-fill indicator value with reasonable default
|
31
42
|
defaultValue: Any | None = None
|
43
|
+
""" The default value for the parameter to auto-populate mainly in UI """
|
44
|
+
|
32
45
|
options: List[Any] | None = None
|
46
|
+
""" Valid value options (if any). If specified, then in the UI, this parameter renders as a dropdown select list.
|
47
|
+
If left as None, parameter renders and freeform input text field. """
|
33
48
|
|
34
49
|
PERIOD_VALUES: ClassVar[List[int]] = [2, 3, 4, 5, 8, 9, 10, 12, 14, 15, 20, 26, 30, 40, 50, 60, 70, 80, 90, 100, 120, 130, 140, 150, 180, 200, 250, 300]
|
35
50
|
|
@@ -37,10 +52,20 @@ class IndicatorParamSpec:
|
|
37
52
|
d = self.__dict__.copy()
|
38
53
|
return d
|
39
54
|
|
55
|
+
@staticmethod
|
56
|
+
def fromDict(json_dict: Dict[str, Any]) -> IndicatorParamSpec:
|
57
|
+
paramType = ParamType[json_dict['paramType']]
|
58
|
+
required = json_dict['required']
|
59
|
+
defaultValue = json_dict.get('defaultValue')
|
60
|
+
options = json_dict.get('options')
|
61
|
+
return IndicatorParamSpec(paramType, required, defaultValue, options)
|
62
|
+
|
40
63
|
|
41
64
|
class IndicatorValueType(str, Enum):
|
42
|
-
|
43
|
-
|
65
|
+
"""
|
66
|
+
Indicator ValueType can possibly used by Investfly to validate expression and optimize experience for users
|
67
|
+
For e.g, all Indicators of same valueType can be plotted in the same y-axis
|
68
|
+
"""
|
44
69
|
|
45
70
|
PRICE = "PRICE"
|
46
71
|
|
@@ -92,28 +117,85 @@ class IndicatorSpec:
|
|
92
117
|
jsonDict['params'] = paramsDict
|
93
118
|
return jsonDict
|
94
119
|
|
120
|
+
@staticmethod
|
121
|
+
def fromDict(json_dict: Dict[str, Any]) -> IndicatorSpec:
|
122
|
+
name = json_dict['name']
|
123
|
+
indicatorSpec: IndicatorSpec = IndicatorSpec(name)
|
124
|
+
indicatorSpec.indicatorId = json_dict['indicatorId']
|
125
|
+
indicatorSpec.description = json_dict.get('description')
|
126
|
+
indicatorSpec.valueType = IndicatorValueType[json_dict['valueType']]
|
127
|
+
for key, value in json_dict['params'].items():
|
128
|
+
indicatorSpec.params[key] = IndicatorParamSpec.fromDict(value)
|
129
|
+
return indicatorSpec
|
130
|
+
|
95
131
|
def __str__(self):
|
96
132
|
return str(self.__dict__)
|
97
133
|
|
98
134
|
|
99
135
|
class Indicator(ABC):
|
136
|
+
"""
|
137
|
+
The primary class to implement a custom Indicator. A Custom Indicator is like standard indicator (e.g SMA, RSI)
|
138
|
+
and can be used in any place that standard indicator can be used (e.g screener, charts, strategy etc)
|
139
|
+
Investfly comes with a set of standard indicators. If you find that the indicator you want is not supported
|
140
|
+
or you can a small variation (e.g SMA but with using Heikin Ashi Candles), then you can use this function
|
141
|
+
"""
|
100
142
|
|
101
143
|
@abstractmethod
|
102
144
|
def getIndicatorSpec(self) -> IndicatorSpec:
|
103
|
-
|
104
|
-
|
145
|
+
"""
|
146
|
+
Return IndicatorSpec with name, description, required params, and valuetype
|
147
|
+
See IndicatorSpec abstract class for more details
|
148
|
+
:return: `IndicatorSpec`
|
149
|
+
"""
|
150
|
+
|
105
151
|
pass
|
106
152
|
|
107
153
|
def getDataSourceType(self) -> DataSource:
|
108
|
-
|
109
|
-
|
154
|
+
"""
|
155
|
+
Return the DataSource that this indicator is based on. Possible values are:
|
156
|
+
DataSource.BARS, DataSource.QUOTE, DataSource.NEWS, DataSource.FINANCIAL
|
157
|
+
:return: `investfly.models.SecurityFilterModels.DataSource`
|
158
|
+
"""
|
159
|
+
|
110
160
|
return DataSource.BARS
|
111
161
|
|
112
162
|
@abstractmethod
|
113
163
|
def computeSeries(self, params: Dict[str, Any], data: List[Any]) -> List[DatedValue]:
|
114
|
-
|
164
|
+
"""
|
165
|
+
Compute indicator series based on provided input timed data series and parameter values.
|
166
|
+
This function must return List of indicator values instead of only the most recent single value because indicator
|
167
|
+
series is required to plot in the price chart and also to use in backtest
|
168
|
+
The timestamps in the `investfly.models.CommonModels.DatedValue` must correspond to timestamps in input data
|
169
|
+
The length of input data depends on context (e.g is this indicator being evaluated for backtest or screener?)
|
170
|
+
and `dataCountToComputeCurrentValue` function below
|
171
|
+
|
172
|
+
:param params: User supplied indicator parameter values. The keys match the keys from `IndicatorSpec.params`
|
173
|
+
:param data: List of timed data values as specified in `Indicator.getDataSourceType`.
|
174
|
+
:return: List of `investfly.models.CommonModels.DatedValue` representing indicator values for each timeunit
|
175
|
+
"""
|
176
|
+
|
115
177
|
pass
|
116
178
|
|
179
|
+
def dataCountToComputeCurrentValue(self, params: Dict[str, Any]) -> int | None:
|
180
|
+
"""
|
181
|
+
When this indicator is used in screener and trading strategy when is evaluated in real-time, only
|
182
|
+
the "current" value of the indicator is required. The historical values are NOT required. Therefore,
|
183
|
+
when the system calls `computeSeries` above with all available data (e.g 10 years of historical bars),
|
184
|
+
then it is un-necessarily slow and wasteful. This function is used to control the size of input data
|
185
|
+
that will be passed to `computeSeries` method above.
|
186
|
+
|
187
|
+
The default implementation tries to make the best guess, but override as needed
|
188
|
+
|
189
|
+
:param params: User supplied input parameter values
|
190
|
+
:return: integer representing how many input data points are required to compute the 'current' indicator value.
|
191
|
+
For e.g, if this was SMA indicator with period=5, then you should return 5
|
192
|
+
"""
|
193
|
+
total = 0
|
194
|
+
for key, value in params.items():
|
195
|
+
if isinstance(value, int) and key != DataParam.COUNT:
|
196
|
+
total += value
|
197
|
+
return max(total, 1)
|
198
|
+
|
117
199
|
def validateParams(self, paramVals: Dict[str, Any]):
|
118
200
|
spec: IndicatorSpec = self.getIndicatorSpec()
|
119
201
|
for paramName, paramSpec in spec.params.items():
|
@@ -139,13 +221,6 @@ class Indicator(ABC):
|
|
139
221
|
raise Exception(f"Param {paramName} provided value {paramVal} is not one of the allowed value")
|
140
222
|
|
141
223
|
|
142
|
-
def dataCountToComputeCurrentValue(self, params: Dict[str, Any]) -> int | None:
|
143
|
-
total = 0
|
144
|
-
for key, value in params.items():
|
145
|
-
if isinstance(value, int) and key != DataParam.COUNT:
|
146
|
-
total += value
|
147
|
-
return max(total, 1)
|
148
|
-
|
149
224
|
def addStandardParamsToDef(self, indicatorDef: IndicatorSpec):
|
150
225
|
# Note that setting default values for optional params impact alias/key generation for indicator instances (e.g SMA_5_1MIN_1)
|
151
226
|
# Hence, its better to leave them as None
|