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/models/MarketData.py
CHANGED
@@ -17,6 +17,10 @@ def formatDatetime(dt: datetime) -> str:
|
|
17
17
|
|
18
18
|
|
19
19
|
class SecurityType(str, Enum):
|
20
|
+
"""
|
21
|
+
Enum representing Security Type (STOCK, ETF)
|
22
|
+
"""
|
23
|
+
|
20
24
|
STOCK = "STOCK"
|
21
25
|
ETF = "ETF"
|
22
26
|
|
@@ -31,8 +35,15 @@ class SecurityType(str, Enum):
|
|
31
35
|
|
32
36
|
@dataclass(frozen=True)
|
33
37
|
class Security:
|
38
|
+
"""
|
39
|
+
Class representing a security instrument that is traded in the market
|
40
|
+
"""
|
41
|
+
|
34
42
|
symbol: str
|
43
|
+
""" Security Symbol """
|
44
|
+
|
35
45
|
securityType: SecurityType
|
46
|
+
""" Security Type """
|
36
47
|
|
37
48
|
@staticmethod
|
38
49
|
def createStock(symbol: str):
|
@@ -48,6 +59,7 @@ class Security:
|
|
48
59
|
|
49
60
|
@dataclass
|
50
61
|
class Quote:
|
62
|
+
""" Class representing Price Quote """
|
51
63
|
symbol: str
|
52
64
|
date: datetime
|
53
65
|
lastPrice: float
|
@@ -122,9 +134,8 @@ class Quote:
|
|
122
134
|
return bar
|
123
135
|
|
124
136
|
|
125
|
-
|
126
|
-
|
127
137
|
class BarInterval(str, Enum):
|
138
|
+
""" Enum to represent BarInterval """
|
128
139
|
ONE_MINUTE = "ONE_MINUTE"
|
129
140
|
FIVE_MINUTE = "FIVE_MINUTE"
|
130
141
|
FIFTEEN_MINUTE = "FIFTEEN_MINUTE"
|
@@ -2,6 +2,7 @@ from enum import Enum
|
|
2
2
|
|
3
3
|
|
4
4
|
class QuoteField(str, Enum):
|
5
|
+
""" Enum of all valid fields on Quote object """
|
5
6
|
# ------ Quote ---
|
6
7
|
LASTPRICE = "LASTPRICE"
|
7
8
|
DAY_OPEN = "DAY_OPEN"
|
@@ -14,7 +15,7 @@ class QuoteField(str, Enum):
|
|
14
15
|
DAY_CHANGE_OPEN = "DAY_CHANGE_OPEN"
|
15
16
|
|
16
17
|
class FinancialField(str, Enum):
|
17
|
-
|
18
|
+
"""Financial Fields supported by Invesfly"""
|
18
19
|
|
19
20
|
# SHARE
|
20
21
|
OUTSTANDING_SHARES = "OUTSTANDING_SHARES"
|
@@ -62,6 +63,7 @@ class FinancialField(str, Enum):
|
|
62
63
|
|
63
64
|
|
64
65
|
class StandardIndicatorId(str, Enum):
|
66
|
+
""" Technical Indicator supported by Investfly"""
|
65
67
|
|
66
68
|
# Works by default on DAILY bars
|
67
69
|
AVGVOL = "AVGVOLUME"
|
@@ -10,6 +10,8 @@ from investfly.models.MarketData import Security
|
|
10
10
|
from investfly.models.ModelUtils import ModelUtils
|
11
11
|
|
12
12
|
class PositionType(str, Enum):
|
13
|
+
""" PositionType Enum """
|
14
|
+
|
13
15
|
LONG = "LONG",
|
14
16
|
SHORT = "SHORT"
|
15
17
|
CLOSE = "CLOSE"
|
@@ -22,6 +24,8 @@ class PositionType(str, Enum):
|
|
22
24
|
|
23
25
|
|
24
26
|
class TradeType(str, Enum):
|
27
|
+
"""Trade Type Enum """
|
28
|
+
|
25
29
|
BUY = "BUY"
|
26
30
|
SELL = "SELL"
|
27
31
|
SHORT = "SHORT"
|
@@ -35,6 +39,8 @@ class TradeType(str, Enum):
|
|
35
39
|
|
36
40
|
|
37
41
|
class OrderType(str, Enum):
|
42
|
+
"""Order Type Enum """
|
43
|
+
|
38
44
|
MARKET_ORDER = "MARKET_ORDER"
|
39
45
|
LIMIT_ORDER = "LIMIT_ORDER"
|
40
46
|
STOP_ORDER = "STOP_ORDER"
|
@@ -43,6 +49,9 @@ class OrderType(str, Enum):
|
|
43
49
|
|
44
50
|
|
45
51
|
class Broker(str, Enum):
|
52
|
+
|
53
|
+
"""Broker Type Enum"""
|
54
|
+
|
46
55
|
INVESTFLY = "INVESTFLY"
|
47
56
|
TRADIER = "TRADIER"
|
48
57
|
TDAMERITRADE = "TDAMERITRADE"
|
@@ -57,6 +66,7 @@ class Broker(str, Enum):
|
|
57
66
|
|
58
67
|
@dataclass
|
59
68
|
class TradeOrder:
|
69
|
+
""" A class that represents a Trade Order """
|
60
70
|
security: Security
|
61
71
|
tradeType: TradeType
|
62
72
|
orderType: OrderType = OrderType.MARKET_ORDER
|
@@ -72,6 +82,7 @@ class TradeOrder:
|
|
72
82
|
|
73
83
|
@dataclass
|
74
84
|
class OrderStatus:
|
85
|
+
""" Trade Order Status"""
|
75
86
|
orderId: int
|
76
87
|
status: str
|
77
88
|
message: str | None = None
|
@@ -128,10 +128,18 @@ class FinancialQuery:
|
|
128
128
|
|
129
129
|
@dataclass
|
130
130
|
class SecurityUniverseSelector:
|
131
|
+
"""
|
132
|
+
This class is used to specify the set of stocks to use in trading strategy.
|
133
|
+
You can pick one of the standard list (e.g SP100) that we provide, provide your own list with comma separated symbols list,
|
134
|
+
or provide a query based on fundamental metrics like MarketCap, PE Ratio etc.
|
135
|
+
"""
|
131
136
|
universeType: SecurityUniverseType
|
137
|
+
"""The approach used to specify the stocks. Depending on the universeType, one of the attribute below must be specified"""
|
138
|
+
|
132
139
|
standardList: StandardSymbolsList | None = None
|
133
|
-
|
140
|
+
"Standard Symbol List (i.e SP500, SP100). Required if `universeType` is set to `STANDARD_LIST`"
|
134
141
|
|
142
|
+
customList: CustomSecurityList | None = None
|
135
143
|
financialQuery: FinancialQuery | None = None
|
136
144
|
|
137
145
|
@staticmethod
|
@@ -10,7 +10,7 @@ from typing import Dict, Any, List
|
|
10
10
|
from investfly.models.CommonModels import TimeDelta
|
11
11
|
from investfly.models.MarketData import Security
|
12
12
|
from investfly.models.ModelUtils import ModelUtils
|
13
|
-
from investfly.models.PortfolioModels import PositionType, Portfolio, TradeOrder
|
13
|
+
from investfly.models.PortfolioModels import PositionType, Portfolio, TradeOrder, PortfolioPerformance
|
14
14
|
from investfly.models.SecurityFilterModels import DataParam
|
15
15
|
|
16
16
|
|
@@ -122,3 +122,64 @@ class DeploymentLog:
|
|
122
122
|
def fromDict(json_dict: Dict[str, Any]) -> DeploymentLog:
|
123
123
|
return DeploymentLog(ModelUtils.parseDatetime(json_dict['date']), LogLevel(json_dict['level']), json_dict['message'])
|
124
124
|
|
125
|
+
class StandardOrCustom(str, Enum):
|
126
|
+
STANDARD = "STANDARD"
|
127
|
+
CUSTOM = "CUSTOM"
|
128
|
+
|
129
|
+
@dataclass
|
130
|
+
class TradingStrategyModel:
|
131
|
+
strategyName: str
|
132
|
+
strategyId: int | None = None
|
133
|
+
pythonCode: str | None = None
|
134
|
+
strategyDesc: str | None = None
|
135
|
+
|
136
|
+
@staticmethod
|
137
|
+
def fromDict(json_dict: Dict[str, Any]) -> TradingStrategyModel:
|
138
|
+
strategyId = json_dict['strategyId']
|
139
|
+
strategyName = json_dict['strategyName']
|
140
|
+
pythonCode = json_dict['pythonCode']
|
141
|
+
strategyDesc = json_dict.get('strategyDesc')
|
142
|
+
return TradingStrategyModel(strategyId=strategyId, strategyName=strategyName, pythonCode=pythonCode, strategyDesc=strategyDesc)
|
143
|
+
|
144
|
+
def toDict(self) -> Dict[str, Any]:
|
145
|
+
dict = self.__dict__.copy()
|
146
|
+
return dict
|
147
|
+
|
148
|
+
|
149
|
+
class BacktestStatus(str, Enum):
|
150
|
+
NOT_STARTED = "NOT_STARTED",
|
151
|
+
QUEUED = "QUEUED",
|
152
|
+
INITIALIZING = "INITIALIZING",
|
153
|
+
RUNNING = "RUNNING"
|
154
|
+
COMPLETE = "COMPLETE"
|
155
|
+
ERROR = "ERROR"
|
156
|
+
|
157
|
+
@dataclass
|
158
|
+
class BacktestResultStatus:
|
159
|
+
jobStatus: BacktestStatus
|
160
|
+
percentComplete: int
|
161
|
+
|
162
|
+
def toDict(self) -> Dict[str, Any]:
|
163
|
+
dict = self.__dict__.copy()
|
164
|
+
return dict
|
165
|
+
|
166
|
+
@staticmethod
|
167
|
+
def fromDict(json_dict: Dict[str, Any]) -> BacktestResultStatus:
|
168
|
+
status = BacktestStatus[json_dict['jobStatus']]
|
169
|
+
percentComplete = json_dict['percentComplete']
|
170
|
+
return BacktestResultStatus(status, percentComplete)
|
171
|
+
|
172
|
+
@dataclass
|
173
|
+
class BacktestResult:
|
174
|
+
status: BacktestResultStatus
|
175
|
+
performance: PortfolioPerformance
|
176
|
+
def toDict(self) -> Dict[str, Any]:
|
177
|
+
dict = self.__dict__.copy()
|
178
|
+
dict['performance'] = self.performance.toDict()
|
179
|
+
return dict
|
180
|
+
|
181
|
+
@staticmethod
|
182
|
+
def fromDict(json_dict: Dict[str, Any]) -> BacktestResult:
|
183
|
+
status = BacktestResultStatus.fromDict(json_dict['status'])
|
184
|
+
performance = PortfolioPerformance.fromDict(json_dict['performance'])
|
185
|
+
return BacktestResult(status, performance)
|
@@ -9,43 +9,94 @@ from investfly.utils.PercentBasedPortfolioAllocator import PercentBasedPortfolio
|
|
9
9
|
|
10
10
|
|
11
11
|
class TradingStrategy(ABC):
|
12
|
+
"""
|
13
|
+
This is the main interface (abstract class) used to implement a trading strategy.
|
14
|
+
"""
|
12
15
|
|
13
16
|
def __init__(self) -> None:
|
14
17
|
self.state: Dict[str, int | float | bool] = {}
|
18
|
+
"""The persisted state of the strategy. """
|
15
19
|
|
16
20
|
@abstractmethod
|
17
21
|
def getSecurityUniverseSelector(self) -> SecurityUniverseSelector:
|
22
|
+
"""
|
23
|
+
This function is used to narrow down the set of securities (i.e stocks) against which to run your logic.
|
24
|
+
You can pick one of the standard list (e.g SP100) that we provide, provide your own list with comma separated symbols list,
|
25
|
+
or provide a query based on fundamental metrics like MarketCap, PE Ratio etc.
|
26
|
+
See docs on
|
27
|
+
`investfly.models.SecurityUniverseSelector.SecurityUniverseSelector` for more details.
|
28
|
+
Returns
|
29
|
+
:return: `investfly.models.SecurityUniverseSelector.SecurityUniverseSelector`
|
30
|
+
"""
|
18
31
|
pass
|
19
32
|
|
20
|
-
|
21
|
-
This function must be annotated with OnData to indicate when should this function be called.
|
22
|
-
The function is called whenever a new data is available based on the subscribed data
|
23
|
-
This function is called separately for each security
|
24
|
-
@DataParams({
|
25
|
-
"sma2": {"datatype": DataType.INDICATOR, "indicator": "SMA", "barinterval": BarInterval.ONE_MINUTE, "period": 2, "count": 2},
|
26
|
-
"sma3": {"datatype": DataType.INDICATOR, "indicator": "SMA", "barinterval": BarInterval.ONE_MINUTE, "period": 3, "count": 2},
|
27
|
-
"allOneMinBars": {"datatype": DataType.BARS, "barinterval": BarInterval.ONE_MINUTE},
|
28
|
-
"latestDailyBar": {"datatype": DataType.BARS, "barinterval": BarInterval.ONE_DAY, "count":1},
|
29
|
-
"quote": {"datatype": DataType.QUOTE},
|
30
|
-
"lastprice": {"datatype": DataType.QUOTE, "field": QuoteField.LASTPRICE},
|
31
|
-
"allFinancials": {"datatype": DataType.FINANCIAL},
|
32
|
-
"revenue": {"datatype": DataType.FINANCIAL, "field": FinancialField.REVENUE}
|
33
|
-
|
34
|
-
})
|
35
|
-
"""
|
33
|
+
|
36
34
|
@abstractmethod
|
37
35
|
def evaluateOpenTradeCondition(self, security: Security, data: Dict[str, Any]) -> TradeSignal | None:
|
36
|
+
"""
|
37
|
+
This function must be annotated with @DataParams to indicate what data (i.e indicator values) are needed as shown below.
|
38
|
+
The function is called whenever a new data is available based on the subscribed data.
|
39
|
+
This function is called separately for each security.
|
40
|
+
```
|
41
|
+
@DataParams({
|
42
|
+
"sma2": {"datatype": DataType.INDICATOR, "indicator": "SMA", "barinterval": BarInterval.ONE_MINUTE, "period": 2, "count": 2},
|
43
|
+
"sma3": {"datatype": DataType.INDICATOR, "indicator": "SMA", "barinterval": BarInterval.ONE_MINUTE, "period": 3, "count": 2},
|
44
|
+
"allOneMinBars": {"datatype": DataType.BARS, "barinterval": BarInterval.ONE_MINUTE},
|
45
|
+
"latestDailyBar": {"datatype": DataType.BARS, "barinterval": BarInterval.ONE_DAY, "count":1},
|
46
|
+
"quote": {"datatype": DataType.QUOTE},
|
47
|
+
"lastprice": {"datatype": DataType.QUOTE, "field": QuoteField.LASTPRICE},
|
48
|
+
"allFinancials": {"datatype": DataType.FINANCIAL},
|
49
|
+
"revenue": {"datatype": DataType.FINANCIAL, "field": FinancialField.REVENUE}
|
50
|
+
|
51
|
+
})
|
52
|
+
```
|
53
|
+
:param security: The stock security against which this is evaluated. You use it to construct TradeSignal
|
54
|
+
:param data: Dictionary with the requested data based on @DataParams annotation.
|
55
|
+
|
56
|
+
The keys of the data param dictionary match the keys specified in @DataParams annotation. The value depends on the datatype parameter.
|
57
|
+
datatype=INDICATOR, value type = `investfly.models.CommonModels.DatedValue`
|
58
|
+
datatype=QUOTE, field is specified, value type = `investfly.models.CommonModels.DatedValue`
|
59
|
+
datatype=QUOTE, field is not specified, value type is `investfly.models.MarketData.Quote` object (has dayOpen, dayHigh, dayLow, prevOpen etc)
|
60
|
+
datatype=BARS, value type is `investfly.models.MarketData.Bar`
|
61
|
+
|
62
|
+
Further, if the count is specified and greater than 1, value is returned as a List
|
63
|
+
:return: `investfly.model.StrategyModels.TradeSignal` if open condition matches and to signal open trade, None if open trade condition does not match
|
64
|
+
"""
|
38
65
|
pass
|
39
66
|
|
40
67
|
def processOpenTradeSignals(self, portfolio: Portfolio, tradeSignals: List[TradeSignal]) -> List[TradeOrder]:
|
68
|
+
"""
|
69
|
+
This method is used to convert TradeSignals into TradeOrders. You must do this for couple reasons:
|
70
|
+
1. Assume 1000 stocks match the open trade condition and so you have 1000 TradeSignals, but that does not
|
71
|
+
mean that you want to open position for 1000 stocks in your portfolio. You may want to order those trade signals
|
72
|
+
by strength and limit to top 10 trade signals
|
73
|
+
2. Your portfolio may already have open position for a stock corresponding to particular trade signal. In that case,
|
74
|
+
you may wan to skip that trade signal, and prioritize opening new position for other stocks
|
75
|
+
3. Here, you also set TradeOrder speficiations such as order type, quantity etc
|
76
|
+
4. You may want to fully rebalance portfolio baseed on these new trade signals
|
77
|
+
:param portfolio: Current portfolio state
|
78
|
+
:param tradeSignals: Trade Signals correspoding to stocks matching open trade condition
|
79
|
+
:return: List of TradeOrders to execute
|
80
|
+
"""
|
41
81
|
portfolioAllocator = PercentBasedPortfolioAllocator(10, PositionType.LONG)
|
42
82
|
return portfolioAllocator.allocatePortfolio(portfolio, tradeSignals)
|
43
83
|
|
44
84
|
def getStandardCloseCondition(self) -> StandardCloseCriteria | None:
|
85
|
+
"""
|
86
|
+
TargetProfit, StopLoss, TrailingStop and Timeout are considered as standard close criteria. This function
|
87
|
+
is created so that you can specify those standard close/exit conditions easily
|
88
|
+
:return: `investfly.models.StrategyModels.StandardCloseCriteria`
|
89
|
+
"""
|
45
90
|
# Note that these are always executed as MARKET_ORDER
|
46
91
|
return None
|
47
92
|
|
48
93
|
def evaluateCloseTradeCondition(self, openPos: OpenPosition, data) -> TradeOrder | None:
|
94
|
+
"""
|
95
|
+
Implementing this method is optional. But when implemented, it should be implemented similar to evaluateOpenTradeCondition
|
96
|
+
:param openPos: The open position
|
97
|
+
:param data: Requested data that corresponds to the open position's security symbol
|
98
|
+
:return: TradeOrder if the position is supposed to be closed, None otherwise
|
99
|
+
"""
|
49
100
|
return None
|
50
101
|
|
51
102
|
def runAtInterval(self, portfolio: Portfolio) -> List[TradeOrder]:
|
investfly/models/__init__.py
CHANGED
@@ -1,10 +1,18 @@
|
|
1
|
+
""""
|
2
|
+
This package contains all data model classes used in Strategy and Indicator definition.
|
3
|
+
|
4
|
+
The main class for defining trading strategy is `investfly.models.TradingStrategy.TradingStrategy`
|
5
|
+
|
6
|
+
The main class for defining custom technical indicator is `investfly.models.Indicator.Indicator`
|
7
|
+
"""
|
8
|
+
|
1
9
|
from investfly.models.CommonModels import DatedValue, TimeUnit, TimeDelta, Session
|
2
10
|
from investfly.models.Indicator import ParamType, IndicatorParamSpec, IndicatorValueType, IndicatorSpec, Indicator
|
3
11
|
from investfly.models.MarketData import SecurityType, Security, Quote, BarInterval, Bar
|
4
12
|
from investfly.models.MarketDataIds import QuoteField, FinancialField, StandardIndicatorId
|
5
13
|
from investfly.models.PortfolioModels import PositionType, TradeType, Broker, TradeOrder, OrderStatus, PendingOrder, Balances, CompletedTrade, OpenPosition, ClosedPosition, Portfolio, PortfolioPerformance
|
6
14
|
from investfly.models.SecurityUniverseSelector import StandardSymbolsList, CustomSecurityList, SecurityUniverseType, SecurityUniverseSelector, FinancialQuery, FinancialCondition, ComparisonOperator
|
7
|
-
from investfly.models.StrategyModels import DataParams, ScheduleInterval, Schedule, TradeSignal, StandardCloseCriteria, PortfolioSecurityAllocator
|
15
|
+
from investfly.models.StrategyModels import DataParams, ScheduleInterval, Schedule, TradeSignal, StandardCloseCriteria, PortfolioSecurityAllocator, BacktestStatus
|
8
16
|
from investfly.models.TradingStrategy import TradingStrategy
|
9
17
|
from investfly.models.SecurityFilterModels import DataType, DataParam, DataSource
|
10
18
|
|
@@ -12,7 +12,7 @@ from typing import Any, List, Dict
|
|
12
12
|
import math
|
13
13
|
import statistics
|
14
14
|
import numpy as np
|
15
|
-
import talib
|
15
|
+
import talib # https://pypi.org/project/TA-Lib/
|
16
16
|
import pandas
|
17
17
|
# ! WARN ! Imports other than listed above are disallowed and won't pass validation
|
18
18
|
|
@@ -0,0 +1,194 @@
|
|
1
|
+
Metadata-Version: 2.1
|
2
|
+
Name: investfly-sdk
|
3
|
+
Version: 1.2
|
4
|
+
Summary: Investfly SDK
|
5
|
+
Author-email: "Investfly.com" <admin@investfly.com>
|
6
|
+
License: The MIT License (MIT)
|
7
|
+
|
8
|
+
Copyright (c) 2023+ Investfly, Finverse LLC
|
9
|
+
|
10
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
11
|
+
of this software and associated documentation files (the "Software"), to deal
|
12
|
+
in the Software without restriction, including without limitation the rights
|
13
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
14
|
+
copies of the Software, and to permit persons to whom the Software is
|
15
|
+
furnished to do so, subject to the following conditions:
|
16
|
+
|
17
|
+
The above copyright notice and this permission notice shall be included in all
|
18
|
+
copies or substantial portions of the Software.
|
19
|
+
|
20
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
21
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
22
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
23
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
24
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
25
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
26
|
+
SOFTWARE.
|
27
|
+
Project-URL: Homepage, https://www.investfly.com
|
28
|
+
Classifier: Programming Language :: Python :: 3
|
29
|
+
Classifier: License :: OSI Approved :: MIT License
|
30
|
+
Classifier: Operating System :: OS Independent
|
31
|
+
Requires-Python: >=3.7
|
32
|
+
Description-Content-Type: text/markdown
|
33
|
+
License-File: LICENSE.txt
|
34
|
+
Requires-Dist: certifi ==2023.7.22
|
35
|
+
Requires-Dist: charset-normalizer ==3.2.0
|
36
|
+
Requires-Dist: idna ==3.4
|
37
|
+
Requires-Dist: pandas ==2.0.3
|
38
|
+
Requires-Dist: pandas-stubs ==2.0.3.230814
|
39
|
+
Requires-Dist: pandas-ta ==0.3.14b0
|
40
|
+
Requires-Dist: python-dateutil ==2.8.2
|
41
|
+
Requires-Dist: pytz ==2023.3
|
42
|
+
Requires-Dist: requests ==2.31.0
|
43
|
+
Requires-Dist: types-requests ==2.31.0.2
|
44
|
+
Requires-Dist: six ==1.16.0
|
45
|
+
Requires-Dist: tzdata ==2023.3
|
46
|
+
Requires-Dist: urllib3 ==1.26.15
|
47
|
+
Requires-Dist: numpy ==1.26.4
|
48
|
+
Requires-Dist: TA-Lib ==0.4.28
|
49
|
+
|
50
|
+
# About
|
51
|
+
|
52
|
+
Python-SDK to work with Investfly API.
|
53
|
+
[Investfly](https://www.investfly.com)
|
54
|
+
|
55
|
+
Investfly offers a platform for developing automated stock trading strategies. Users can create trading strategies through an intuitive drag-and-drop interface or by coding in Python.
|
56
|
+
|
57
|
+
The Investfly SDK contains the API and tools needed to build and deploy Python-based trading strategies on the Investfly platform.
|
58
|
+
|
59
|
+
Although you can edit Python code in our browser-based editor, writing code in a familiar IDE (Pycharm, VSCode) is recommended due to all the benefits that rich IDE offers. This SDK and CLI that comes with it makes it possible to develop trading strategy locally using your favorite IDE and upload it your Investfly account.
|
60
|
+
|
61
|
+
# Quickstart
|
62
|
+
|
63
|
+
### SDK Installation and Setup
|
64
|
+
|
65
|
+
Investfly-SDK comes with all required Python classes used for strategy development as well as a command line tool (CLI) called `investfly-cli`
|
66
|
+
|
67
|
+
Using a terminal app, run the following commands.
|
68
|
+
|
69
|
+
**Setup Project and Virtual Environment**
|
70
|
+
|
71
|
+
```commandline
|
72
|
+
mkdir investfly
|
73
|
+
cd investfly
|
74
|
+
python3 -m venv venv
|
75
|
+
source venv/bin/activate
|
76
|
+
```
|
77
|
+
|
78
|
+
**Install investfly-sdk**
|
79
|
+
|
80
|
+
```commandline
|
81
|
+
pip install investfly-sdk
|
82
|
+
```
|
83
|
+
|
84
|
+
**Launch investfly-cli**
|
85
|
+
|
86
|
+
Install investfly-sdk also adds investfly-cli in your path inside the virtual environment. It can be launched simply by using `investfly-cli` command in the virtual env.
|
87
|
+
|
88
|
+
```commandline
|
89
|
+
(venv) user@host$ investfly-cli
|
90
|
+
|
91
|
+
investfly-cli$ -h
|
92
|
+
usage: investfly-cli [-h]
|
93
|
+
{login,logout,strategy.list,strategy.copysamples,strategy.create,strategy.download,strategy.update,strategy.backtest.start,strategy.backtest.stop,strategy.backtest.result,exit}
|
94
|
+
...
|
95
|
+
|
96
|
+
positional arguments:
|
97
|
+
{login,logout,strategy.list,strategy.copysamples,strategy.create,strategy.download,strategy.update,strategy.backtest.start,strategy.backtest.stop,strategy.backtest.result,exit}
|
98
|
+
Available Commands
|
99
|
+
login Login to Investfly
|
100
|
+
logout Logout from Investfly
|
101
|
+
strategy.list List Python Strategies
|
102
|
+
strategy.copysamples
|
103
|
+
Copy Samples from SDK
|
104
|
+
strategy.create Create a new trading strategy
|
105
|
+
strategy.download Download one of your strategy and save it to a file
|
106
|
+
strategy.update Update strategy Python Code
|
107
|
+
strategy.backtest.start
|
108
|
+
Start backtest for strategy
|
109
|
+
strategy.backtest.stop
|
110
|
+
Stop backtest for strategy
|
111
|
+
strategy.backtest.result
|
112
|
+
Get backtest result, waiting if backtest is still
|
113
|
+
running
|
114
|
+
exit Stop and Exit CLI
|
115
|
+
|
116
|
+
options:
|
117
|
+
-h, --help show this help message and exit
|
118
|
+
|
119
|
+
investfly-cli$
|
120
|
+
```
|
121
|
+
|
122
|
+
**Test Installation**
|
123
|
+
|
124
|
+
You can test the installation by using the CLI to login and logout of Investfly.
|
125
|
+
```commandline
|
126
|
+
investfly-cli$ login -u <YOUR_USERNAME> -p <YOUR_PASSWORD>
|
127
|
+
Session(username='xxxxxx', clientId='xxxxx-kaj1p3lv', clientToken='b29c9acc-330a-4821-9187-282d827e3e91')
|
128
|
+
|
129
|
+
investfly-cli$ logout
|
130
|
+
```
|
131
|
+
|
132
|
+
|
133
|
+
### Trading Strategy Development
|
134
|
+
|
135
|
+
Investfly-SDK comes with a starter strategy template and many sample strategies to help you get started quickly.
|
136
|
+
|
137
|
+
|
138
|
+
**Copy Samples**
|
139
|
+
|
140
|
+
```commandline
|
141
|
+
investfly-cli$ copysamples
|
142
|
+
Samples copied to ./samples directory
|
143
|
+
```
|
144
|
+
|
145
|
+
**Create New Strategy**
|
146
|
+
|
147
|
+
You can use one of the samples to create a new strategy. Normally, you would make a copy of the sample strategy, edit the copy using your favorite IDE to create a new strategy.
|
148
|
+
But for now, we'll use the unmodified sample
|
149
|
+
```commandline
|
150
|
+
investfly-cli$ login -u <YOUR_USERNAME> -p <YOUR_PASSWORD>
|
151
|
+
Session(username='xxxxx', clientId='xxxxxx-krfs61aa', clientToken='766fad47-3e1e-4f43-a77a-72a95a395fec')
|
152
|
+
|
153
|
+
investfly-cli$ strategy.create -n MySmaCrossOverStrategy -f ./samples/strategies/SmaCrossOverStrategy.py
|
154
|
+
Created strategy 83
|
155
|
+
|
156
|
+
investfly-cli$ strategy.list
|
157
|
+
{'strategyId': 83, 'strategyName': 'MySmaCrossOverStrategy'}
|
158
|
+
|
159
|
+
```
|
160
|
+
|
161
|
+
**Edit and Update Code**
|
162
|
+
|
163
|
+
Edit and update ./samples/strategies/SmaCrossOverStrategy.py as you like. For testing, change the `StandardSymbolsList.SP_100` to `StandardSymbolsList.SP_500` inside `getSecurityUniverseSelector` function.
|
164
|
+
|
165
|
+
```commandline
|
166
|
+
investfly-cli$ strategy.update --id 83 -f ./samples/strategies/SmaCrossOverStrategy.py
|
167
|
+
Code Updated
|
168
|
+
```
|
169
|
+
|
170
|
+
After the code is updated, next step is to backtest the strategy and deploy it live.
|
171
|
+
You can do them by logging into Investfly with a web browser, navigating to the strategy page and invoking corresponding actions.
|
172
|
+
|
173
|
+
|
174
|
+
### IDE Editor
|
175
|
+
|
176
|
+
The primary reason for publishing this SDK is so that you can use your favorite IDE Editor to write and update Python Code.
|
177
|
+
We recommend using PyCharm community edition:
|
178
|
+
https://www.jetbrains.com/pycharm/download
|
179
|
+
|
180
|
+
Using IDE editor will assist with auto-completion and type hints. Additionally, use type checking tools like mypy to check your code before deploying.
|
181
|
+
|
182
|
+
When using the IDE, open `investfly` directory created above as a project with your IDE.
|
183
|
+
Make sure that Python Interpreter is configured to the virtual environment `investfly/venv/bin/python` created above.
|
184
|
+
|
185
|
+
|
186
|
+
# API Docs
|
187
|
+
|
188
|
+
API Docs are published at https://www.investfly.com/guides/docs/index.html
|
189
|
+
|
190
|
+
# Getting Help
|
191
|
+
Please email [admin@investfly.com](admin@investfly.com) for any support or bug report
|
192
|
+
|
193
|
+
|
194
|
+
|
@@ -0,0 +1,39 @@
|
|
1
|
+
investfly/__init__.py,sha256=Ku0IZu4VYvNGui70Xu-bG1fB8XtVNQxBey6f5nLIKVU,71
|
2
|
+
investfly/api/IndicatorApiClient.py,sha256=G2bEWaCvcmotp4jx-IoiqHblZZWAdwaUjDNP5ZoaagM,931
|
3
|
+
investfly/api/InvestflyApiClient.py,sha256=I_hi1Uw8EGa3jr06cNkrGbhjIT90BPr_YN5EFilykwQ,2111
|
4
|
+
investfly/api/MarketDataApiClient.py,sha256=bOlMzzZzN5A35oo0Iml2xCekV0jOig8Q_L66xi6n0n0,611
|
5
|
+
investfly/api/PortfolioApiClient.py,sha256=llNISIHWSx3wvf83usGhwPhVr-3RYGAndBNpZV9w3W0,1858
|
6
|
+
investfly/api/RestApiClient.py,sha256=XjvJCqAqUMPa7tXkhxGwaOj1xgHkfLcA8Q0027Z6xm8,3236
|
7
|
+
investfly/api/StrategyApiClient.py,sha256=6HmCv7Q_yynVinWIrLfyhCATnqMaJfsqEdiNizqaWiY,2087
|
8
|
+
investfly/api/__init__.py,sha256=JeeOmrsPbVk4B26DT3hbvBoxAvkMEhJ-PeKeloNGF08,600
|
9
|
+
investfly/cli/InvestflyCli.py,sha256=GB_5QxiifXDRwy2MxV8Wq_WykVgcZbpeQ_UfhJFMWhs,10561
|
10
|
+
investfly/cli/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
11
|
+
investfly/models/CommonModels.py,sha256=kbyWsez1voii2K2wyflYCW7i9lYQh49nbrts4bTvvG4,2348
|
12
|
+
investfly/models/Indicator.py,sha256=R98Lkxjw5pnpMgucL-GxgQHoF-mP8qsylC_FtVMQ1wc,10664
|
13
|
+
investfly/models/MarketData.py,sha256=NbyOh472uIXyHaTW9eYCBbiTu2szSq47iCz8i3qI1v0,6081
|
14
|
+
investfly/models/MarketDataIds.py,sha256=CTNCb7G8NgLb84LYCqqxwlhO8e6RV-AUGwJH9GDv53A,3248
|
15
|
+
investfly/models/ModelUtils.py,sha256=pnrVIDM26LqK0Wuw7gTs0c97lCLIV_fm0EUtlEfT7j4,964
|
16
|
+
investfly/models/PortfolioModels.py,sha256=wEHzaxEMEmliNR1OXS0WNzzao7ZA5qhKIPzAjWQuUOM,8658
|
17
|
+
investfly/models/SecurityFilterModels.py,sha256=4baTBBI-XOKh8uTpvqVvk3unD-xHoyooO3dd5lKWbXA,5806
|
18
|
+
investfly/models/SecurityUniverseSelector.py,sha256=N2cYhgRz3PTh6T98liiiTbJNg27SBpaUaIQGgDHFbF4,8645
|
19
|
+
investfly/models/StrategyModels.py,sha256=n9MVOJFPtc_Wkiq5TyhdQnaiTUeXGMYqLmBE9IEiW10,5553
|
20
|
+
investfly/models/TradingStrategy.py,sha256=uUgQpZRgioVADIKerdC5VD0LEy9LvDqEEGvtRTgWASM,6381
|
21
|
+
investfly/models/__init__.py,sha256=6uMfJwcYaH1r-T-bbh6gMud0VpnoSQTkPNDVMDE3JXo,1383
|
22
|
+
investfly/samples/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
23
|
+
investfly/samples/indicators/IndicatorTemplate.py,sha256=X0AlStLnL1SBSnTwrtW_sthm00tmuN5V7N-GrtiarmM,4454
|
24
|
+
investfly/samples/indicators/NewsSentiment.py,sha256=fcpAqOcNWmqYsP-xwJquCX_6G7Ntr3A1-m31eJHAUOE,65095
|
25
|
+
investfly/samples/indicators/RsiOfSma.py,sha256=kiLvMhrsbc_lV0EEpERGW2im19u5XmyJk88aTDGSBis,1719
|
26
|
+
investfly/samples/indicators/SmaEmaAverage.py,sha256=9pp3TtEKJADD_bfufwrWlwMswlTLoN7Nj6BC_jJ1sRs,1749
|
27
|
+
investfly/samples/indicators/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
28
|
+
investfly/samples/strategies/SmaCrossOverStrategy.py,sha256=szjmnqQN8O7CRIS1vc-fRONKg4Dy1d59dZhiSEpEJAI,1699
|
29
|
+
investfly/samples/strategies/SmaCrossOverTemplate.py,sha256=HSyVh89_d-k1aAzqs_WFt8EDxs809OjWq6V3VJVUNQw,8200
|
30
|
+
investfly/samples/strategies/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
31
|
+
investfly/utils/CommonUtils.py,sha256=lCXAdI8-6PgbutcXJqUmSfuuLXp82FcnlxNVjCJpqLU,2631
|
32
|
+
investfly/utils/PercentBasedPortfolioAllocator.py,sha256=oKaSjq5L_3NfRo2iayepCZtZnCevsx4XpsxFfZMTnV8,1684
|
33
|
+
investfly/utils/__init__.py,sha256=2BqXoOQElv-GIU6wvmf2aaAABAcNny2TETcj7kf9rzM,129
|
34
|
+
investfly_sdk-1.2.dist-info/LICENSE.txt,sha256=Jmd2U7G7Z1oNdnRERRzFXN6C--bEo_K56j4v9EpJSTg,1090
|
35
|
+
investfly_sdk-1.2.dist-info/METADATA,sha256=5SO14Syv4-fKY4ggso8X7RwuJd_vM4zu5Ji5ANtAdH4,7507
|
36
|
+
investfly_sdk-1.2.dist-info/WHEEL,sha256=y4mX-SOX4fYIkonsAGA5N0Oy-8_gI4FXw5HNI1xqvWg,91
|
37
|
+
investfly_sdk-1.2.dist-info/entry_points.txt,sha256=GDRF4baJQXTh90DvdJJx1DeRezWfPt26E567lTs3g6U,66
|
38
|
+
investfly_sdk-1.2.dist-info/top_level.txt,sha256=dlEJ2OGWA3prqMvXELeydS5RTdpSzh7hz1LwR3NMc7A,10
|
39
|
+
investfly_sdk-1.2.dist-info/RECORD,,
|
investfly/cli/CliApiClient.py
DELETED
@@ -1,46 +0,0 @@
|
|
1
|
-
import requests
|
2
|
-
from investfly.api.RestApiClient import RestApiClient
|
3
|
-
|
4
|
-
class CliApiClient:
|
5
|
-
|
6
|
-
def __init__(self, baseUrl: str) -> None:
|
7
|
-
self.restApi = RestApiClient(baseUrl)
|
8
|
-
|
9
|
-
def login(self, username: str, password: str):
|
10
|
-
try:
|
11
|
-
user = self.restApi.login(username, password)
|
12
|
-
print("Successfully logged in as: "+user.username)
|
13
|
-
except Exception as e:
|
14
|
-
print(e)
|
15
|
-
|
16
|
-
def logout(self):
|
17
|
-
self.restApi.logout()
|
18
|
-
|
19
|
-
def getStatus(self):
|
20
|
-
try:
|
21
|
-
userInfo = self.restApi.doGet('/user/session')
|
22
|
-
print("Currently logged in as "+userInfo['username'])
|
23
|
-
except Exception as e:
|
24
|
-
print(e)
|
25
|
-
|
26
|
-
def getStrategies(self):
|
27
|
-
try:
|
28
|
-
strategies = self.restApi.doGet('/strategy/list')
|
29
|
-
for strategy in strategies:
|
30
|
-
print(str(strategy['strategyId'])+'\t'+strategy['strategyName']+'\n'+strategy['strategyDesc']+'\n')
|
31
|
-
except Exception as e:
|
32
|
-
print(e)
|
33
|
-
|
34
|
-
def saveStrategy(self, strategyId: int):
|
35
|
-
try:
|
36
|
-
strategy = self.restApi.doGet('/strategy/'+str(strategyId))
|
37
|
-
return strategy['pythonCode']
|
38
|
-
except Exception as e:
|
39
|
-
return e
|
40
|
-
|
41
|
-
def updateStrategy(self, id: int, code: str):
|
42
|
-
try:
|
43
|
-
self.restApi.doPostCode('/strategy/'+id+'/update/code', code)
|
44
|
-
print('Strategy successfully updated')
|
45
|
-
except Exception as e:
|
46
|
-
print(e)
|