trendvisdata 1.0.4__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.
trendvisdata/trend.py ADDED
@@ -0,0 +1,316 @@
1
+ """
2
+ Calculate Trend Strength across various markets / asset classes and graph
3
+ results
4
+
5
+ """
6
+ import copy
7
+ from trendvisdata.chart_data import Data
8
+ from trendvisdata.sector_mappings import sectmap
9
+ from trendvisdata.trend_params import trend_params_dict
10
+ from trendvisdata.trend_data import Fields, TrendRank
11
+ from trendvisdata.market_data import NorgateExtract, YahooExtract, MktUtils
12
+
13
+
14
+ class TrendStrength():
15
+ """
16
+ Create Trend Strength data and display results
17
+
18
+ Parameters
19
+ ----------
20
+ chart_dimensions : Tuple
21
+ Tuple of height, width for market chart.
22
+ chart_mkts : Int
23
+ Number of markets for market chart.
24
+ days : Int
25
+ The number of days price history.
26
+ end_date : Str
27
+ End Date represented as a string in the
28
+ format 'YYYY-MM-DD'.
29
+ indicator_type : Str
30
+ The indicator to plot. Choose from 'adx', 'ma_cross',
31
+ 'price_cross', 'rsi', 'breakout'.
32
+ lookback : Int
33
+ Number of days history if dates are not specified
34
+ mkts : Int
35
+ Number of markets for barchart or linegraph.
36
+ norm : Bool
37
+ Whether the prices have been normalised.
38
+ pie_tenor : Int / Tuple
39
+ The time period of the indicator. For the Moving Average
40
+ crossover this is a tuple from the following pairs: (5, 200),
41
+ (10, 30), (10, 50), (20, 50), (30, 100), (50, 200). For the
42
+ other indicators this is an integer from the list: 10, 20, 30,
43
+ 50, 100, 200.
44
+ sector_level : Int
45
+ The level of granularity of the assets.
46
+ For Commodities the choices are:
47
+ 1:'Asset Class',
48
+ 2:'Broad Sector',
49
+ 3:'Mid Sector',
50
+ 4:'Narrow Sector',
51
+ 5:'Underlying'.
52
+ For Equities the choices are:
53
+ 1:'Sector',
54
+ 2:'Industry Group',
55
+ 3:'Industry',
56
+ 4:'Sub-Industry',
57
+ 5:'Security'
58
+ source : Str
59
+ The source of the market data. 'norgate' or 'yahoo'. The default is
60
+ 'norgate'.
61
+ start_date : Str
62
+ Start Date represented as a string in the
63
+ format 'YYYY-MM-DD'.
64
+ tickers : List
65
+ List of tickers, represented as strings.
66
+ ticker_limit : Int
67
+ Flag to select only the first n markets. The default
68
+ is None.
69
+ trend : Str
70
+ Flag to select most or least trending markets.
71
+ Select from: 'up' - strongly trending upwards,
72
+ 'down - strongly trending downwards,
73
+ 'neutral' - weak trend,
74
+ 'strong' - up and down trends,
75
+ 'all' - up down and weak trends
76
+ The default is 'strong' which displays both up-trending
77
+ and down-trending markets.
78
+
79
+ Returns
80
+ -------
81
+ None.
82
+
83
+ """
84
+ def __init__(self, **kwargs) -> None:
85
+
86
+ # Import dictionary of default parameters
87
+ self.default_dict = copy.deepcopy(trend_params_dict)
88
+
89
+ # Import dictionary of sector mappings
90
+ mappings = copy.deepcopy(sectmap)
91
+
92
+ # Store initial inputs
93
+ inputs = {}
94
+ for key, value in kwargs.items():
95
+ inputs[key] = value
96
+
97
+ # Initialise system parameters
98
+ params = self._init_params(inputs)
99
+
100
+ # Import the data from Norgate Data
101
+ if params['source'] == 'norgate':
102
+ params, tables, mappings = self.prep_norgate(
103
+ params=params, mappings=mappings)
104
+
105
+ # Or from Yahoo Finance
106
+ elif params['source'] == 'yahoo':
107
+ params, tables, mappings = self.prep_yahoo(
108
+ params=params, mappings=mappings)
109
+
110
+ # Calculate the technical indicator fields and Trend Strength table
111
+ tables = self.trend_calc(
112
+ params=params, tables=tables, mappings=mappings)
113
+
114
+ # Generate list of top trending securities
115
+ top_trends, tables = self.top_trend_tickers(
116
+ params=params, tables=tables)
117
+
118
+ # Generate data dictionary for graphing via API
119
+ data_dict = Data.get_all_data(params=params, tables=tables)
120
+
121
+ self.top_trends = top_trends
122
+ self.tables = tables
123
+ self.params = params
124
+ self.mappings = mappings
125
+ self.data_dict = data_dict
126
+
127
+
128
+ @staticmethod
129
+ def _init_params(inputs: dict) -> dict:
130
+ """
131
+ Initialise parameter dictionary
132
+ Parameters
133
+ ----------
134
+ inputs : Dict
135
+ Dictionary of parameters supplied to the function.
136
+
137
+ Returns
138
+ -------
139
+ params : Dict
140
+ Dictionary of parameters.
141
+ """
142
+ # Copy the default parameters
143
+ params = copy.deepcopy(trend_params_dict['df_params'])
144
+
145
+ # For all the supplied arguments
146
+ for key, value in inputs.items():
147
+
148
+ # Replace the default parameter with that provided
149
+ params[key] = value
150
+
151
+ return params
152
+
153
+
154
+ @staticmethod
155
+ def prep_norgate(
156
+ params: dict,
157
+ mappings: dict) -> tuple[dict, dict, dict]:
158
+ """
159
+ Create dataframes of prices, extracting data from Norgate Data.
160
+
161
+ Parameters
162
+ ----------
163
+ params : Dict
164
+ Dictionary of key parameters.
165
+ mappings : Dict
166
+ Dictionary of sector mappings.
167
+
168
+ Returns
169
+ -------
170
+ params : Dict
171
+ Dictionary of key parameters.
172
+ tables : Dict
173
+ Dictionary of key tables.
174
+ mappings : Dict
175
+ Dictionary of sector mappings.
176
+
177
+ """
178
+
179
+ # Set the asset type to 'CTA'
180
+ params['asset_type'] = 'CTA'
181
+
182
+ # If a list of tickers are not supplied, run the function to collect
183
+ # available tickers
184
+ if params['tickers'] is None:
185
+ params = NorgateExtract.get_norgate_tickers(params=params)
186
+
187
+ # Set the start and end dates
188
+ params = MktUtils.date_set(params)
189
+
190
+ # Dictionary to store data tables
191
+ tables = {}
192
+
193
+ # Create dictionaries of DataFrames of prices and ticker names
194
+ params, tables, mappings = NorgateExtract.import_norgate(
195
+ params=params, tables=tables, mappings=mappings)
196
+
197
+ # Remove tickers with short history
198
+ tables = MktUtils.ticker_clean(params=params, tables=tables)
199
+
200
+ return params, tables, mappings
201
+
202
+
203
+ @staticmethod
204
+ def prep_yahoo(
205
+ params: dict,
206
+ mappings: dict) -> tuple[dict, dict, dict]:
207
+ """
208
+ Create dataframes of prices, extracting data from Yahoo Finance.
209
+
210
+ Parameters
211
+ ----------
212
+ params : Dict
213
+ Dictionary of key parameters.
214
+ mappings : Dict
215
+ Dictionary of sector mappings.
216
+
217
+ Returns
218
+ -------
219
+ params : Dict
220
+ Dictionary of key parameters.
221
+ tables : Dict
222
+ Dictionary of key tables.
223
+ mappings : Dict
224
+ Dictionary of sector mappings.
225
+
226
+ """
227
+
228
+ # Create list of tickers, dictionary of ticker names from
229
+ # Wikipedia
230
+ params, mappings = YahooExtract.ticker_extract(
231
+ params=params, mappings=mappings)
232
+
233
+ # Set short_name_dict = name_dict
234
+ params['ticker_short_name_dict'] = params['ticker_name_dict']
235
+
236
+ # Set the asset type to 'Equity'
237
+ params['asset_type'] = 'Equity'
238
+
239
+ # Set the start and end dates
240
+ params = MktUtils.date_set(params)
241
+
242
+ # Dictionary to store data tables
243
+ tables = {}
244
+
245
+ # Create dictionaries of DataFrames of prices and ticker names
246
+ params, tables = YahooExtract.import_yahoo(params, tables)
247
+
248
+ # Remove tickers with short history
249
+ tables = MktUtils.ticker_clean(params=params, tables=tables)
250
+
251
+ return params, tables, mappings
252
+
253
+
254
+ @staticmethod
255
+ def trend_calc(
256
+ params: dict,
257
+ tables: dict,
258
+ mappings: dict) -> dict:
259
+ """
260
+ Calculate the technical indicator fields and Trend Strength table
261
+
262
+ Parameters
263
+ ----------
264
+ params : Dict
265
+ Dictionary of key parameters.
266
+ tables : Dict
267
+ Dictionary of key tables.
268
+ mappings : Dict
269
+ Dictionary of sector mappings.
270
+
271
+ Returns
272
+ -------
273
+ tables : Dict
274
+ Dictionary of key tables.
275
+
276
+ """
277
+ # Calculate the technical indicator fields
278
+ tables['ticker_dict'] = Fields.generate_fields(
279
+ params, tables['raw_ticker_dict'])
280
+
281
+ # Calculate the Trend Strength table
282
+ tables['barometer'] = Fields.generate_trend_strength(
283
+ params=params, ticker_dict=tables['ticker_dict'],
284
+ sector_mappings_df=mappings['sector_mappings_df'])
285
+
286
+ return tables
287
+
288
+
289
+ @staticmethod
290
+ def top_trend_tickers(
291
+ params: dict,
292
+ tables: dict) -> tuple[dict, dict]:
293
+ """
294
+ Prepare list of top trending securities.
295
+
296
+ Parameters
297
+ ----------
298
+ params : Dict
299
+ Dictionary of key parameters.
300
+ tables : Dict
301
+ Dictionary of key tables.
302
+
303
+ Returns
304
+ -------
305
+ ticker_list : List
306
+ List of top trending securities.
307
+ tables : Dict
308
+ Dictionary of key tables.
309
+
310
+ """
311
+ # Generate list of top trending securities
312
+ top_trends, tables = TrendRank.top_trend_calc(
313
+ tables, params)
314
+
315
+ return top_trends, tables
316
+