summaryrefslogtreecommitdiff
path: root/python-infertrade.spec
blob: 6e5af6f07199032ab49eece03edb4d295706bda4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
%global _empty_manifest_terminate_build 0
Name:		python-infertrade
Version:	0.0.62
Release:	1
Summary:	Pandas and SciKit Learn compatible open source interface for algorithmic trading functions.
License:	Apache License 2.0
URL:		https://github.com/ta-oliver/infertrade
Source0:	https://mirrors.aliyun.com/pypi/web/packages/b4/ab/3184f43c7140368b74586ed45f22491f6c0e782a2b22de7d00d4751a04bf/infertrade-0.0.62.tar.gz
BuildArch:	noarch

Requires:	python3-pandas
Requires:	python3-numpy
Requires:	python3-ta
Requires:	python3-scikit-learn
Requires:	python3-matplotlib
Requires:	python3-typing-extensions
Requires:	python3-Markdown
Requires:	python3-requests
Requires:	python3-pytest
Requires:	python3-sphinx
Requires:	python3-pdftex
Requires:	python3-myst-parser
Requires:	python3-pytest-cov
Requires:	python3-black
Requires:	python3-GitPython

%description

<p align="center"><img src="https://www.infertrade.com/static/media/InferTradeLogo.5c2cc437.svg" alt="InferTrade"/>
</p>

# InferTrade

[`infertrade`](https://github.com/ta-oliver/infertrade) is an open source trading and investment strategy library designed for accessibility and compatibility.

The [`infertrade`](https://github.com/ta-oliver/infertrade) package seeks to achieve three objectives:

- Simplicity: a simple [`pandas`](https://github.com/pandas-dev/pandas) to [`pandas`](https://github.com/pandas-dev/pandas) interface that those experienced in trading but new to Python can easily use.

- Gateway to data science: classes that allow rules created for the infertrade simple interface to be used with [`scikit-learn`](https://github.com/scikit-learn/scikit-learn) functionality for prediction and calibration. (fit, transform, predict, pipelines, gridsearch) and [`scikit-learn`](https://github.com/scikit-learn/scikit-learn) compatible libraries, like [`feature-engine`](https://github.com/solegalli/feature_engine).

- The best open source trading strategies: wrapping functionality to allow strategies from any open source Python libraries with compatible licences, such as [`ta`](https://github.com/bukosabino/ta) to be used with the `infertrade` interface.

The project is licenced under the [Apache 2.0](https://choosealicense.com/licenses/apache-2.0/) licence.  

## Connection to InferTrade.com

Many thanks for looking into the [`infertrade`](https://github.com/ta-oliver/infertrade) package!

I created [InferTrade.com](https://infertrade.com/) to provide cutting edge statistical analysis in an accessible free interface. The intention was to help individuals and small firms have access to the same quality of analysis as large institutions for systematic trading and to allow more time to be spent on creating good signals rather than backtesting and strategy verification. If someone has done the hard work of gaining insights into markets I wanted them to be able to compete in a landscape of increasingly automated statistically-driven market participants. A huge amount of effort has been made by the trading and AI/ML communities to create open source packages with [powerful diagnostic functionality](https://github.com/mljar/mljar-supervised), which means you do not need to build a large and complex in-house analytics library to be able to support your investment decisions with solid statistical machine learning. However there remain educational and technical barriers to using this community-created wealth if you are not an experience programmer or do not have mathematical training. I want [InferTrade.com](www.infertrade.com) to allow everyone trading in markets to have access without barriers - cost, training or time - to be competitive, with an easy to use interface that both provides direct analysis and education insights to support your trading. 

The initial impetus for the creation of this open source package, [`infertrade`](https://github.com/ta-oliver/infertrade) was to ensure any of our users finding an attractive strategy on InferTrade.com could easily implement the rule in Python and have full access to the code to fully understand every aspect of how it works. By adding wrapper for existing libraries we hope to support further independent backtesting by users with their own preferred choice of trading libraries. We at InferStat heavily use open source in delivering InferTrade.com's functionality and we also wanted to give something back to the trading and data science community. The Apache 2.0 licence is a permissive licence, so that you can use or build upon [`infertrade`](https://github.com/ta-oliver/infertrade) for your personal, community or commercial projects.

The [`infertrade`](https://github.com/ta-oliver/infertrade) package and InferTrade.com will be adding functionality each week, and we are continually seeking to improve the experience and support the package and website provides for traders, portfolio managers and other users. Gaining feedback on new features is extremely helpful for us to improve our UX and design, as are any ideas for enhancements that would help you to trade better. If you would like to assist me in turning InferTrade into the leading open source trading platform we can offer participation in our Beta Testing programme ([sign up link](https://docs.google.com/forms/d/e/1FAIpQLSeNznsSNx-UUZ_nc9wchgsTy1z9T75YO5cZOB03YP-vQ-F2NQ/viewform?usp=sf_link)). You can also fork this repository and make direct improvements to the package.

Best,
Tom Oliver

InferStat Founder and CEO

- https://github.com/ta-oliver
- https://www.linkedin.com/in/thomas-a-oliver/



## Contact Us

This was [InferStat's](https://inferstat.com/) first open source project and we welcome your thoughts for improvements to code structure, documentation or any changes that would support your use of the library. 

If you would like assistance with using the [`infertrade`](https://github.com/ta-oliver) you can email us at support@infertrade.com or [book a video call](www.calendly.com/infertrade)

If you would like to contribute to the package, e.g. to add support for an additional package or library, please see our [contributing](CONTRIBUTING.md) information.

If you want guidance on infertrade API then please see our [API Guidance](API_GUIDANCE.md) information.


## Quickstart

Please note the project requires Python 3.7 or higher due to dependent libraries used.

See [Windows](https://github.com/ta-oliver/infertrade/blob/main/docs/Install%20Windows.md) or [Linux](https://github.com/ta-oliver/infertrade/blob/main/docs/Install%20Ubuntu%20Linux.md) guides for installation details.


### My First InferTrade Rule

```
import pandas as pd
import matplotlib.pyplot as plt

def my_first_infertrade_rule(df: pd.DataFrame) -> pd.DataFrame:
    df["allocation"] = 0.0
    df["allocation"][df.pct_change() > 0.02] = 0.5     
    return df
    
my_dataframe = pd.read_csv("example_market_data.csv")    
my_dataframe_with_allocations = my_first_infertrade_rule(my_dataframe)
my_dataframe_with_allocations.plot(["close"], ["allocation"])
plt.show()
```

![image](https://user-images.githubusercontent.com/29981664/110859161-ed2ef800-82b2-11eb-8bcb-cfdc3596b880.png)


### Basic usage with community functions

"Community" functions are those declared in this repository, not retrieved from an external package. They are all exposed at `infertrade.algos.community`.

```python
from infertrade.algos.community import normalised_close, scikit_signal_factory
from infertrade.data.simulate_data import simulated_market_data_4_years_gen
signal_transformer = scikit_signal_factory(normalised_close)
signal_transformer.fit_transform(simulated_market_data_4_years_gen())
```

### Usage with TA

```python
from infertrade.algos.community import scikit_signal_factory
from infertrade.data.simulate_data import simulated_market_data_4_years_gen
from infertrade.algos import ta_adaptor
from ta.trend import AroonIndicator
adapted_aroon = ta_adaptor(AroonIndicator, "aroon_down", window=1)
signal_transformer = scikit_signal_factory(adapted_aroon)
signal_transformer.fit_transform(simulated_market_data_4_years_gen())
```

### Calculate positions with simple position function

```python
from infertrade.algos.community.allocations import constant_allocation_size
from infertrade.utilities.operations import scikit_allocation_factory
from infertrade.data.simulate_data import simulated_market_data_4_years_gen

position_transformer = scikit_allocation_factory(constant_allocation_size)
position_transformer.fit_transform(simulated_market_data_4_years_gen())
```

### Example of position calculation via kelly just based on signal generation

```python
from infertrade.algos.community import scikit_signal_factory
from infertrade.data.simulate_data import simulated_market_data_4_years_gen
from infertrade.utilities.operations import PositionsFromPricePrediction, PricePredictionFromSignalRegression
from sklearn.pipeline import make_pipeline
from infertrade.algos import ta_adaptor
from ta.trend import AroonIndicator

adapted_aroon = ta_adaptor(AroonIndicator, "aroon_down", window=1)

pipeline = make_pipeline(scikit_signal_factory(adapted_aroon),
                         PricePredictionFromSignalRegression(),
                         PositionsFromPricePrediction()
                         )

pipeline.fit_transform(simulated_market_data_4_years_gen())
```

### Creating simulated data for testing

For convenience, the `infertrade.data` module contains some basic functions for simulating market data.

```
import matplotlib.pyplot as plt
from infertrade.data.simulate_data import simulated_market_data_4_years_gen
simulated_market_data_4_years_gen().plot(y=["open", "close", "high", "low", "last"])
plt.show()
```

![image](https://user-images.githubusercontent.com/29981664/111359984-1e794080-8684-11eb-88df-5e2af83eadd5.png)

```
import matplotlib.pyplot as plt
from infertrade.data.simulate_data import simulated_correlated_equities_4_years_gen
simulated_correlated_equities_4_years_gen().plot(y=["price", "signal"])
plt.show()
```
![image](https://user-images.githubusercontent.com/29981664/111360130-4668a400-8684-11eb-933e-e8f10662b0bb.png)


### Exporting portfolio performance to a CSV file

The "infertrade.api" module contains an Api class with multiple useful functions including "export_to_csv" which is used to export
portfolio performance as a CSV file.

The function accepts up to two dataframes containing market data, a rule name and a relationship name and the output would be a CSV file containing
information about the provided rule and relationship perfomance with provided market data.

```python
from infertrade.api import Api

Api.export_to_csv(dataframe="MarketData", rule_name="weighted_moving_averages")
"""Resulting CSV file would contain portfolio performance of supplied MarketData 
after trading using weighted moving averages"""

Api.export_to_csv(dataframe="MarketData1", second_df="MarketData2", rule_name="weighted_moving_averages", relationship="change_relationship")
"""Resulting CSV file would contain portfolio performance of supplied MarketData1 and MarketData2 
after trading using weighted moving averages and calculating the change relationship"""
```

![image](https://user-images.githubusercontent.com/74156271/131223361-6a3ba607-57ea-4826-b03f-5bb337f7f497.png)



### Calculate multiple combinations of relationships between supplied data and export to CSV

Besides the "infertrade.api.export_to_csv" method out api module contains
"infertrade.api.export_cross_prediction"

The function accepts a list of dataframes containing market data and
sequentially calculates the performance of trading strategy using pairwise combination

```python
from infertrade.api import Api

Api.export_cross_prediction(listOfDataframes)
                                            
""" The result of this would be CSV files of every possible combination of supplied data
with relationship calculations of every relationship ranked using the "percent_gain" column """

Api.export_cross_prediction(listOfDataframes,
                            column_to_sort="percent_gain",
                            export_as_csv=False)

""" If export_as_csv is set to false the return will only be ranked indexes of dataframes
along with total sum of supplied column used to sort """

Api.export_cross_prediction(listOfDataframes,
                            number_of_results=3,)

""" number_of_results is used to only save/return top X ranked combinations """


### Using the InferTrade API

The "api_automation" module contains the "execute_it_api_request" function,
by supplying the function with a request name from the API_GUIDANCE.md file
and your API key it is able to execute any call mentioned in the guidance.

```python
from infertrade.utilities.api_automation import execute_it_api_request

execute_it_api_request( request_name="Get trading rule metadata", 
                        api_key="YourApiKey")
```

Calls that contain data inside of lists ("[]") need you to provide the specified 
data.In this example, the API request ("Get available time series simulation models")
contains two lists and those are : "research_1" and "price"
To supply this data we simply pass the lists inside a dictionary as 
"additional_data"

```python
from infertrade.utilities.api_automation import execute_it_api_request

additional_data = {"price":[0,1,2,3,4,5,6,7,8,9],"research_1":[0,1,2,3,4,5,6,7,8,9]}
execute_it_api_request( request_name="Get available time series simulation models", 
                        api_key="YourApiKey",
                        additional_data = additional_data)
```

The passed data does not have to replace data inside a list, you can replace any
key listed in the JSON body of the request by using the same feature as before.

If you wish to use your own body or header you can do that by passing them to 
the function:

```python
from infertrade.utilities.api_automation import execute_it_api_request

execute_it_api_request( request_name="Get available time series simulation models", 
                        api_key="YourApiKey",
                        request_body = "YourRequestBody",
                        header = "YourHeader")
```

The default headers are set to:
```python
headers = {
    'Content-Type': 'application/json',
    'x-api-key': 'YourApiKey'
}
```

You can also pass a specific Content Type to the function:

```python
from infertrade.utilities.api_automation import execute_it_api_request

execute_it_api_request( request_name="Get trading rule metadata", 
                        api_key="YourApiKey",
                        Content_Type="YourContentType")
```

The default request are executed using the "request" module but if you prefer
using the "http.client" you can use the "selected_module" argument inside
the function call

```python
from infertrade.utilities.api_automation import execute_it_api_request

execute_it_api_request( request_name="Get trading rule metadata", 
                        api_key="YourApiKey",
                        selected_module="http.client")
```

You can also use the "parse_to_csv" function to read data from a csv file either
located on your computer or the InferTrade package:

```python
from infertrade.utilities.api_automation import execute_it_api_request, parse_csv_file

data = parse_csv_file(file_name="File_Name")
additional = {"trailing_stop_loss_maximum_daily_loss": "value",
            "price": data["Column_Name"],
            "research_1": data["Column_Name"]}
response = execute_it_api_request(
            request_name="Get available time series simulation models",
            api_key="YourApiKey",
            additional_data=additional,
            )
print(response.txt)
```

If you are only providing the file name, the function presumes that it is located in
"/infertrade/".

The same functions can be used alongside postman to generate request bodies,
if you set "execute_request" to false in the function parameters it will return
the request body with additional data:

```python
from infertrade.utilities.api_automation import execute_it_api_request, parse_csv_file

data = parse_csv_file(file_location="File_Location")
additional = {"trailing_stop_loss_maximum_daily_loss": "value",
            "price": data["Column_Name"],
            "research_1": data["Column_Name"]}
response = execute_it_api_request(
            request_name="Get available time series simulation models",
            api_key="YourApiKey",
            additional_data=additional,
            execute_request=False
            )
print(response)
```

The result of this will be the request body with "price", "research_1" and 
"trailing_stop_loss_maximum_daily_loss" set to provided data.





%package -n python3-infertrade
Summary:	Pandas and SciKit Learn compatible open source interface for algorithmic trading functions.
Provides:	python-infertrade
BuildRequires:	python3-devel
BuildRequires:	python3-setuptools
BuildRequires:	python3-pip
%description -n python3-infertrade

<p align="center"><img src="https://www.infertrade.com/static/media/InferTradeLogo.5c2cc437.svg" alt="InferTrade"/>
</p>

# InferTrade

[`infertrade`](https://github.com/ta-oliver/infertrade) is an open source trading and investment strategy library designed for accessibility and compatibility.

The [`infertrade`](https://github.com/ta-oliver/infertrade) package seeks to achieve three objectives:

- Simplicity: a simple [`pandas`](https://github.com/pandas-dev/pandas) to [`pandas`](https://github.com/pandas-dev/pandas) interface that those experienced in trading but new to Python can easily use.

- Gateway to data science: classes that allow rules created for the infertrade simple interface to be used with [`scikit-learn`](https://github.com/scikit-learn/scikit-learn) functionality for prediction and calibration. (fit, transform, predict, pipelines, gridsearch) and [`scikit-learn`](https://github.com/scikit-learn/scikit-learn) compatible libraries, like [`feature-engine`](https://github.com/solegalli/feature_engine).

- The best open source trading strategies: wrapping functionality to allow strategies from any open source Python libraries with compatible licences, such as [`ta`](https://github.com/bukosabino/ta) to be used with the `infertrade` interface.

The project is licenced under the [Apache 2.0](https://choosealicense.com/licenses/apache-2.0/) licence.  

## Connection to InferTrade.com

Many thanks for looking into the [`infertrade`](https://github.com/ta-oliver/infertrade) package!

I created [InferTrade.com](https://infertrade.com/) to provide cutting edge statistical analysis in an accessible free interface. The intention was to help individuals and small firms have access to the same quality of analysis as large institutions for systematic trading and to allow more time to be spent on creating good signals rather than backtesting and strategy verification. If someone has done the hard work of gaining insights into markets I wanted them to be able to compete in a landscape of increasingly automated statistically-driven market participants. A huge amount of effort has been made by the trading and AI/ML communities to create open source packages with [powerful diagnostic functionality](https://github.com/mljar/mljar-supervised), which means you do not need to build a large and complex in-house analytics library to be able to support your investment decisions with solid statistical machine learning. However there remain educational and technical barriers to using this community-created wealth if you are not an experience programmer or do not have mathematical training. I want [InferTrade.com](www.infertrade.com) to allow everyone trading in markets to have access without barriers - cost, training or time - to be competitive, with an easy to use interface that both provides direct analysis and education insights to support your trading. 

The initial impetus for the creation of this open source package, [`infertrade`](https://github.com/ta-oliver/infertrade) was to ensure any of our users finding an attractive strategy on InferTrade.com could easily implement the rule in Python and have full access to the code to fully understand every aspect of how it works. By adding wrapper for existing libraries we hope to support further independent backtesting by users with their own preferred choice of trading libraries. We at InferStat heavily use open source in delivering InferTrade.com's functionality and we also wanted to give something back to the trading and data science community. The Apache 2.0 licence is a permissive licence, so that you can use or build upon [`infertrade`](https://github.com/ta-oliver/infertrade) for your personal, community or commercial projects.

The [`infertrade`](https://github.com/ta-oliver/infertrade) package and InferTrade.com will be adding functionality each week, and we are continually seeking to improve the experience and support the package and website provides for traders, portfolio managers and other users. Gaining feedback on new features is extremely helpful for us to improve our UX and design, as are any ideas for enhancements that would help you to trade better. If you would like to assist me in turning InferTrade into the leading open source trading platform we can offer participation in our Beta Testing programme ([sign up link](https://docs.google.com/forms/d/e/1FAIpQLSeNznsSNx-UUZ_nc9wchgsTy1z9T75YO5cZOB03YP-vQ-F2NQ/viewform?usp=sf_link)). You can also fork this repository and make direct improvements to the package.

Best,
Tom Oliver

InferStat Founder and CEO

- https://github.com/ta-oliver
- https://www.linkedin.com/in/thomas-a-oliver/



## Contact Us

This was [InferStat's](https://inferstat.com/) first open source project and we welcome your thoughts for improvements to code structure, documentation or any changes that would support your use of the library. 

If you would like assistance with using the [`infertrade`](https://github.com/ta-oliver) you can email us at support@infertrade.com or [book a video call](www.calendly.com/infertrade)

If you would like to contribute to the package, e.g. to add support for an additional package or library, please see our [contributing](CONTRIBUTING.md) information.

If you want guidance on infertrade API then please see our [API Guidance](API_GUIDANCE.md) information.


## Quickstart

Please note the project requires Python 3.7 or higher due to dependent libraries used.

See [Windows](https://github.com/ta-oliver/infertrade/blob/main/docs/Install%20Windows.md) or [Linux](https://github.com/ta-oliver/infertrade/blob/main/docs/Install%20Ubuntu%20Linux.md) guides for installation details.


### My First InferTrade Rule

```
import pandas as pd
import matplotlib.pyplot as plt

def my_first_infertrade_rule(df: pd.DataFrame) -> pd.DataFrame:
    df["allocation"] = 0.0
    df["allocation"][df.pct_change() > 0.02] = 0.5     
    return df
    
my_dataframe = pd.read_csv("example_market_data.csv")    
my_dataframe_with_allocations = my_first_infertrade_rule(my_dataframe)
my_dataframe_with_allocations.plot(["close"], ["allocation"])
plt.show()
```

![image](https://user-images.githubusercontent.com/29981664/110859161-ed2ef800-82b2-11eb-8bcb-cfdc3596b880.png)


### Basic usage with community functions

"Community" functions are those declared in this repository, not retrieved from an external package. They are all exposed at `infertrade.algos.community`.

```python
from infertrade.algos.community import normalised_close, scikit_signal_factory
from infertrade.data.simulate_data import simulated_market_data_4_years_gen
signal_transformer = scikit_signal_factory(normalised_close)
signal_transformer.fit_transform(simulated_market_data_4_years_gen())
```

### Usage with TA

```python
from infertrade.algos.community import scikit_signal_factory
from infertrade.data.simulate_data import simulated_market_data_4_years_gen
from infertrade.algos import ta_adaptor
from ta.trend import AroonIndicator
adapted_aroon = ta_adaptor(AroonIndicator, "aroon_down", window=1)
signal_transformer = scikit_signal_factory(adapted_aroon)
signal_transformer.fit_transform(simulated_market_data_4_years_gen())
```

### Calculate positions with simple position function

```python
from infertrade.algos.community.allocations import constant_allocation_size
from infertrade.utilities.operations import scikit_allocation_factory
from infertrade.data.simulate_data import simulated_market_data_4_years_gen

position_transformer = scikit_allocation_factory(constant_allocation_size)
position_transformer.fit_transform(simulated_market_data_4_years_gen())
```

### Example of position calculation via kelly just based on signal generation

```python
from infertrade.algos.community import scikit_signal_factory
from infertrade.data.simulate_data import simulated_market_data_4_years_gen
from infertrade.utilities.operations import PositionsFromPricePrediction, PricePredictionFromSignalRegression
from sklearn.pipeline import make_pipeline
from infertrade.algos import ta_adaptor
from ta.trend import AroonIndicator

adapted_aroon = ta_adaptor(AroonIndicator, "aroon_down", window=1)

pipeline = make_pipeline(scikit_signal_factory(adapted_aroon),
                         PricePredictionFromSignalRegression(),
                         PositionsFromPricePrediction()
                         )

pipeline.fit_transform(simulated_market_data_4_years_gen())
```

### Creating simulated data for testing

For convenience, the `infertrade.data` module contains some basic functions for simulating market data.

```
import matplotlib.pyplot as plt
from infertrade.data.simulate_data import simulated_market_data_4_years_gen
simulated_market_data_4_years_gen().plot(y=["open", "close", "high", "low", "last"])
plt.show()
```

![image](https://user-images.githubusercontent.com/29981664/111359984-1e794080-8684-11eb-88df-5e2af83eadd5.png)

```
import matplotlib.pyplot as plt
from infertrade.data.simulate_data import simulated_correlated_equities_4_years_gen
simulated_correlated_equities_4_years_gen().plot(y=["price", "signal"])
plt.show()
```
![image](https://user-images.githubusercontent.com/29981664/111360130-4668a400-8684-11eb-933e-e8f10662b0bb.png)


### Exporting portfolio performance to a CSV file

The "infertrade.api" module contains an Api class with multiple useful functions including "export_to_csv" which is used to export
portfolio performance as a CSV file.

The function accepts up to two dataframes containing market data, a rule name and a relationship name and the output would be a CSV file containing
information about the provided rule and relationship perfomance with provided market data.

```python
from infertrade.api import Api

Api.export_to_csv(dataframe="MarketData", rule_name="weighted_moving_averages")
"""Resulting CSV file would contain portfolio performance of supplied MarketData 
after trading using weighted moving averages"""

Api.export_to_csv(dataframe="MarketData1", second_df="MarketData2", rule_name="weighted_moving_averages", relationship="change_relationship")
"""Resulting CSV file would contain portfolio performance of supplied MarketData1 and MarketData2 
after trading using weighted moving averages and calculating the change relationship"""
```

![image](https://user-images.githubusercontent.com/74156271/131223361-6a3ba607-57ea-4826-b03f-5bb337f7f497.png)



### Calculate multiple combinations of relationships between supplied data and export to CSV

Besides the "infertrade.api.export_to_csv" method out api module contains
"infertrade.api.export_cross_prediction"

The function accepts a list of dataframes containing market data and
sequentially calculates the performance of trading strategy using pairwise combination

```python
from infertrade.api import Api

Api.export_cross_prediction(listOfDataframes)
                                            
""" The result of this would be CSV files of every possible combination of supplied data
with relationship calculations of every relationship ranked using the "percent_gain" column """

Api.export_cross_prediction(listOfDataframes,
                            column_to_sort="percent_gain",
                            export_as_csv=False)

""" If export_as_csv is set to false the return will only be ranked indexes of dataframes
along with total sum of supplied column used to sort """

Api.export_cross_prediction(listOfDataframes,
                            number_of_results=3,)

""" number_of_results is used to only save/return top X ranked combinations """


### Using the InferTrade API

The "api_automation" module contains the "execute_it_api_request" function,
by supplying the function with a request name from the API_GUIDANCE.md file
and your API key it is able to execute any call mentioned in the guidance.

```python
from infertrade.utilities.api_automation import execute_it_api_request

execute_it_api_request( request_name="Get trading rule metadata", 
                        api_key="YourApiKey")
```

Calls that contain data inside of lists ("[]") need you to provide the specified 
data.In this example, the API request ("Get available time series simulation models")
contains two lists and those are : "research_1" and "price"
To supply this data we simply pass the lists inside a dictionary as 
"additional_data"

```python
from infertrade.utilities.api_automation import execute_it_api_request

additional_data = {"price":[0,1,2,3,4,5,6,7,8,9],"research_1":[0,1,2,3,4,5,6,7,8,9]}
execute_it_api_request( request_name="Get available time series simulation models", 
                        api_key="YourApiKey",
                        additional_data = additional_data)
```

The passed data does not have to replace data inside a list, you can replace any
key listed in the JSON body of the request by using the same feature as before.

If you wish to use your own body or header you can do that by passing them to 
the function:

```python
from infertrade.utilities.api_automation import execute_it_api_request

execute_it_api_request( request_name="Get available time series simulation models", 
                        api_key="YourApiKey",
                        request_body = "YourRequestBody",
                        header = "YourHeader")
```

The default headers are set to:
```python
headers = {
    'Content-Type': 'application/json',
    'x-api-key': 'YourApiKey'
}
```

You can also pass a specific Content Type to the function:

```python
from infertrade.utilities.api_automation import execute_it_api_request

execute_it_api_request( request_name="Get trading rule metadata", 
                        api_key="YourApiKey",
                        Content_Type="YourContentType")
```

The default request are executed using the "request" module but if you prefer
using the "http.client" you can use the "selected_module" argument inside
the function call

```python
from infertrade.utilities.api_automation import execute_it_api_request

execute_it_api_request( request_name="Get trading rule metadata", 
                        api_key="YourApiKey",
                        selected_module="http.client")
```

You can also use the "parse_to_csv" function to read data from a csv file either
located on your computer or the InferTrade package:

```python
from infertrade.utilities.api_automation import execute_it_api_request, parse_csv_file

data = parse_csv_file(file_name="File_Name")
additional = {"trailing_stop_loss_maximum_daily_loss": "value",
            "price": data["Column_Name"],
            "research_1": data["Column_Name"]}
response = execute_it_api_request(
            request_name="Get available time series simulation models",
            api_key="YourApiKey",
            additional_data=additional,
            )
print(response.txt)
```

If you are only providing the file name, the function presumes that it is located in
"/infertrade/".

The same functions can be used alongside postman to generate request bodies,
if you set "execute_request" to false in the function parameters it will return
the request body with additional data:

```python
from infertrade.utilities.api_automation import execute_it_api_request, parse_csv_file

data = parse_csv_file(file_location="File_Location")
additional = {"trailing_stop_loss_maximum_daily_loss": "value",
            "price": data["Column_Name"],
            "research_1": data["Column_Name"]}
response = execute_it_api_request(
            request_name="Get available time series simulation models",
            api_key="YourApiKey",
            additional_data=additional,
            execute_request=False
            )
print(response)
```

The result of this will be the request body with "price", "research_1" and 
"trailing_stop_loss_maximum_daily_loss" set to provided data.





%package help
Summary:	Development documents and examples for infertrade
Provides:	python3-infertrade-doc
%description help

<p align="center"><img src="https://www.infertrade.com/static/media/InferTradeLogo.5c2cc437.svg" alt="InferTrade"/>
</p>

# InferTrade

[`infertrade`](https://github.com/ta-oliver/infertrade) is an open source trading and investment strategy library designed for accessibility and compatibility.

The [`infertrade`](https://github.com/ta-oliver/infertrade) package seeks to achieve three objectives:

- Simplicity: a simple [`pandas`](https://github.com/pandas-dev/pandas) to [`pandas`](https://github.com/pandas-dev/pandas) interface that those experienced in trading but new to Python can easily use.

- Gateway to data science: classes that allow rules created for the infertrade simple interface to be used with [`scikit-learn`](https://github.com/scikit-learn/scikit-learn) functionality for prediction and calibration. (fit, transform, predict, pipelines, gridsearch) and [`scikit-learn`](https://github.com/scikit-learn/scikit-learn) compatible libraries, like [`feature-engine`](https://github.com/solegalli/feature_engine).

- The best open source trading strategies: wrapping functionality to allow strategies from any open source Python libraries with compatible licences, such as [`ta`](https://github.com/bukosabino/ta) to be used with the `infertrade` interface.

The project is licenced under the [Apache 2.0](https://choosealicense.com/licenses/apache-2.0/) licence.  

## Connection to InferTrade.com

Many thanks for looking into the [`infertrade`](https://github.com/ta-oliver/infertrade) package!

I created [InferTrade.com](https://infertrade.com/) to provide cutting edge statistical analysis in an accessible free interface. The intention was to help individuals and small firms have access to the same quality of analysis as large institutions for systematic trading and to allow more time to be spent on creating good signals rather than backtesting and strategy verification. If someone has done the hard work of gaining insights into markets I wanted them to be able to compete in a landscape of increasingly automated statistically-driven market participants. A huge amount of effort has been made by the trading and AI/ML communities to create open source packages with [powerful diagnostic functionality](https://github.com/mljar/mljar-supervised), which means you do not need to build a large and complex in-house analytics library to be able to support your investment decisions with solid statistical machine learning. However there remain educational and technical barriers to using this community-created wealth if you are not an experience programmer or do not have mathematical training. I want [InferTrade.com](www.infertrade.com) to allow everyone trading in markets to have access without barriers - cost, training or time - to be competitive, with an easy to use interface that both provides direct analysis and education insights to support your trading. 

The initial impetus for the creation of this open source package, [`infertrade`](https://github.com/ta-oliver/infertrade) was to ensure any of our users finding an attractive strategy on InferTrade.com could easily implement the rule in Python and have full access to the code to fully understand every aspect of how it works. By adding wrapper for existing libraries we hope to support further independent backtesting by users with their own preferred choice of trading libraries. We at InferStat heavily use open source in delivering InferTrade.com's functionality and we also wanted to give something back to the trading and data science community. The Apache 2.0 licence is a permissive licence, so that you can use or build upon [`infertrade`](https://github.com/ta-oliver/infertrade) for your personal, community or commercial projects.

The [`infertrade`](https://github.com/ta-oliver/infertrade) package and InferTrade.com will be adding functionality each week, and we are continually seeking to improve the experience and support the package and website provides for traders, portfolio managers and other users. Gaining feedback on new features is extremely helpful for us to improve our UX and design, as are any ideas for enhancements that would help you to trade better. If you would like to assist me in turning InferTrade into the leading open source trading platform we can offer participation in our Beta Testing programme ([sign up link](https://docs.google.com/forms/d/e/1FAIpQLSeNznsSNx-UUZ_nc9wchgsTy1z9T75YO5cZOB03YP-vQ-F2NQ/viewform?usp=sf_link)). You can also fork this repository and make direct improvements to the package.

Best,
Tom Oliver

InferStat Founder and CEO

- https://github.com/ta-oliver
- https://www.linkedin.com/in/thomas-a-oliver/



## Contact Us

This was [InferStat's](https://inferstat.com/) first open source project and we welcome your thoughts for improvements to code structure, documentation or any changes that would support your use of the library. 

If you would like assistance with using the [`infertrade`](https://github.com/ta-oliver) you can email us at support@infertrade.com or [book a video call](www.calendly.com/infertrade)

If you would like to contribute to the package, e.g. to add support for an additional package or library, please see our [contributing](CONTRIBUTING.md) information.

If you want guidance on infertrade API then please see our [API Guidance](API_GUIDANCE.md) information.


## Quickstart

Please note the project requires Python 3.7 or higher due to dependent libraries used.

See [Windows](https://github.com/ta-oliver/infertrade/blob/main/docs/Install%20Windows.md) or [Linux](https://github.com/ta-oliver/infertrade/blob/main/docs/Install%20Ubuntu%20Linux.md) guides for installation details.


### My First InferTrade Rule

```
import pandas as pd
import matplotlib.pyplot as plt

def my_first_infertrade_rule(df: pd.DataFrame) -> pd.DataFrame:
    df["allocation"] = 0.0
    df["allocation"][df.pct_change() > 0.02] = 0.5     
    return df
    
my_dataframe = pd.read_csv("example_market_data.csv")    
my_dataframe_with_allocations = my_first_infertrade_rule(my_dataframe)
my_dataframe_with_allocations.plot(["close"], ["allocation"])
plt.show()
```

![image](https://user-images.githubusercontent.com/29981664/110859161-ed2ef800-82b2-11eb-8bcb-cfdc3596b880.png)


### Basic usage with community functions

"Community" functions are those declared in this repository, not retrieved from an external package. They are all exposed at `infertrade.algos.community`.

```python
from infertrade.algos.community import normalised_close, scikit_signal_factory
from infertrade.data.simulate_data import simulated_market_data_4_years_gen
signal_transformer = scikit_signal_factory(normalised_close)
signal_transformer.fit_transform(simulated_market_data_4_years_gen())
```

### Usage with TA

```python
from infertrade.algos.community import scikit_signal_factory
from infertrade.data.simulate_data import simulated_market_data_4_years_gen
from infertrade.algos import ta_adaptor
from ta.trend import AroonIndicator
adapted_aroon = ta_adaptor(AroonIndicator, "aroon_down", window=1)
signal_transformer = scikit_signal_factory(adapted_aroon)
signal_transformer.fit_transform(simulated_market_data_4_years_gen())
```

### Calculate positions with simple position function

```python
from infertrade.algos.community.allocations import constant_allocation_size
from infertrade.utilities.operations import scikit_allocation_factory
from infertrade.data.simulate_data import simulated_market_data_4_years_gen

position_transformer = scikit_allocation_factory(constant_allocation_size)
position_transformer.fit_transform(simulated_market_data_4_years_gen())
```

### Example of position calculation via kelly just based on signal generation

```python
from infertrade.algos.community import scikit_signal_factory
from infertrade.data.simulate_data import simulated_market_data_4_years_gen
from infertrade.utilities.operations import PositionsFromPricePrediction, PricePredictionFromSignalRegression
from sklearn.pipeline import make_pipeline
from infertrade.algos import ta_adaptor
from ta.trend import AroonIndicator

adapted_aroon = ta_adaptor(AroonIndicator, "aroon_down", window=1)

pipeline = make_pipeline(scikit_signal_factory(adapted_aroon),
                         PricePredictionFromSignalRegression(),
                         PositionsFromPricePrediction()
                         )

pipeline.fit_transform(simulated_market_data_4_years_gen())
```

### Creating simulated data for testing

For convenience, the `infertrade.data` module contains some basic functions for simulating market data.

```
import matplotlib.pyplot as plt
from infertrade.data.simulate_data import simulated_market_data_4_years_gen
simulated_market_data_4_years_gen().plot(y=["open", "close", "high", "low", "last"])
plt.show()
```

![image](https://user-images.githubusercontent.com/29981664/111359984-1e794080-8684-11eb-88df-5e2af83eadd5.png)

```
import matplotlib.pyplot as plt
from infertrade.data.simulate_data import simulated_correlated_equities_4_years_gen
simulated_correlated_equities_4_years_gen().plot(y=["price", "signal"])
plt.show()
```
![image](https://user-images.githubusercontent.com/29981664/111360130-4668a400-8684-11eb-933e-e8f10662b0bb.png)


### Exporting portfolio performance to a CSV file

The "infertrade.api" module contains an Api class with multiple useful functions including "export_to_csv" which is used to export
portfolio performance as a CSV file.

The function accepts up to two dataframes containing market data, a rule name and a relationship name and the output would be a CSV file containing
information about the provided rule and relationship perfomance with provided market data.

```python
from infertrade.api import Api

Api.export_to_csv(dataframe="MarketData", rule_name="weighted_moving_averages")
"""Resulting CSV file would contain portfolio performance of supplied MarketData 
after trading using weighted moving averages"""

Api.export_to_csv(dataframe="MarketData1", second_df="MarketData2", rule_name="weighted_moving_averages", relationship="change_relationship")
"""Resulting CSV file would contain portfolio performance of supplied MarketData1 and MarketData2 
after trading using weighted moving averages and calculating the change relationship"""
```

![image](https://user-images.githubusercontent.com/74156271/131223361-6a3ba607-57ea-4826-b03f-5bb337f7f497.png)



### Calculate multiple combinations of relationships between supplied data and export to CSV

Besides the "infertrade.api.export_to_csv" method out api module contains
"infertrade.api.export_cross_prediction"

The function accepts a list of dataframes containing market data and
sequentially calculates the performance of trading strategy using pairwise combination

```python
from infertrade.api import Api

Api.export_cross_prediction(listOfDataframes)
                                            
""" The result of this would be CSV files of every possible combination of supplied data
with relationship calculations of every relationship ranked using the "percent_gain" column """

Api.export_cross_prediction(listOfDataframes,
                            column_to_sort="percent_gain",
                            export_as_csv=False)

""" If export_as_csv is set to false the return will only be ranked indexes of dataframes
along with total sum of supplied column used to sort """

Api.export_cross_prediction(listOfDataframes,
                            number_of_results=3,)

""" number_of_results is used to only save/return top X ranked combinations """


### Using the InferTrade API

The "api_automation" module contains the "execute_it_api_request" function,
by supplying the function with a request name from the API_GUIDANCE.md file
and your API key it is able to execute any call mentioned in the guidance.

```python
from infertrade.utilities.api_automation import execute_it_api_request

execute_it_api_request( request_name="Get trading rule metadata", 
                        api_key="YourApiKey")
```

Calls that contain data inside of lists ("[]") need you to provide the specified 
data.In this example, the API request ("Get available time series simulation models")
contains two lists and those are : "research_1" and "price"
To supply this data we simply pass the lists inside a dictionary as 
"additional_data"

```python
from infertrade.utilities.api_automation import execute_it_api_request

additional_data = {"price":[0,1,2,3,4,5,6,7,8,9],"research_1":[0,1,2,3,4,5,6,7,8,9]}
execute_it_api_request( request_name="Get available time series simulation models", 
                        api_key="YourApiKey",
                        additional_data = additional_data)
```

The passed data does not have to replace data inside a list, you can replace any
key listed in the JSON body of the request by using the same feature as before.

If you wish to use your own body or header you can do that by passing them to 
the function:

```python
from infertrade.utilities.api_automation import execute_it_api_request

execute_it_api_request( request_name="Get available time series simulation models", 
                        api_key="YourApiKey",
                        request_body = "YourRequestBody",
                        header = "YourHeader")
```

The default headers are set to:
```python
headers = {
    'Content-Type': 'application/json',
    'x-api-key': 'YourApiKey'
}
```

You can also pass a specific Content Type to the function:

```python
from infertrade.utilities.api_automation import execute_it_api_request

execute_it_api_request( request_name="Get trading rule metadata", 
                        api_key="YourApiKey",
                        Content_Type="YourContentType")
```

The default request are executed using the "request" module but if you prefer
using the "http.client" you can use the "selected_module" argument inside
the function call

```python
from infertrade.utilities.api_automation import execute_it_api_request

execute_it_api_request( request_name="Get trading rule metadata", 
                        api_key="YourApiKey",
                        selected_module="http.client")
```

You can also use the "parse_to_csv" function to read data from a csv file either
located on your computer or the InferTrade package:

```python
from infertrade.utilities.api_automation import execute_it_api_request, parse_csv_file

data = parse_csv_file(file_name="File_Name")
additional = {"trailing_stop_loss_maximum_daily_loss": "value",
            "price": data["Column_Name"],
            "research_1": data["Column_Name"]}
response = execute_it_api_request(
            request_name="Get available time series simulation models",
            api_key="YourApiKey",
            additional_data=additional,
            )
print(response.txt)
```

If you are only providing the file name, the function presumes that it is located in
"/infertrade/".

The same functions can be used alongside postman to generate request bodies,
if you set "execute_request" to false in the function parameters it will return
the request body with additional data:

```python
from infertrade.utilities.api_automation import execute_it_api_request, parse_csv_file

data = parse_csv_file(file_location="File_Location")
additional = {"trailing_stop_loss_maximum_daily_loss": "value",
            "price": data["Column_Name"],
            "research_1": data["Column_Name"]}
response = execute_it_api_request(
            request_name="Get available time series simulation models",
            api_key="YourApiKey",
            additional_data=additional,
            execute_request=False
            )
print(response)
```

The result of this will be the request body with "price", "research_1" and 
"trailing_stop_loss_maximum_daily_loss" set to provided data.





%prep
%autosetup -n infertrade-0.0.62

%build
%py3_build

%install
%py3_install
install -d -m755 %{buildroot}/%{_pkgdocdir}
if [ -d doc ]; then cp -arf doc %{buildroot}/%{_pkgdocdir}; fi
if [ -d docs ]; then cp -arf docs %{buildroot}/%{_pkgdocdir}; fi
if [ -d example ]; then cp -arf example %{buildroot}/%{_pkgdocdir}; fi
if [ -d examples ]; then cp -arf examples %{buildroot}/%{_pkgdocdir}; fi
pushd %{buildroot}
if [ -d usr/lib ]; then
	find usr/lib -type f -printf "\"/%h/%f\"\n" >> filelist.lst
fi
if [ -d usr/lib64 ]; then
	find usr/lib64 -type f -printf "\"/%h/%f\"\n" >> filelist.lst
fi
if [ -d usr/bin ]; then
	find usr/bin -type f -printf "\"/%h/%f\"\n" >> filelist.lst
fi
if [ -d usr/sbin ]; then
	find usr/sbin -type f -printf "\"/%h/%f\"\n" >> filelist.lst
fi
touch doclist.lst
if [ -d usr/share/man ]; then
	find usr/share/man -type f -printf "\"/%h/%f.gz\"\n" >> doclist.lst
fi
popd
mv %{buildroot}/filelist.lst .
mv %{buildroot}/doclist.lst .

%files -n python3-infertrade -f filelist.lst
%dir %{python3_sitelib}/*

%files help -f doclist.lst
%{_docdir}/*

%changelog
* Thu Jun 08 2023 Python_Bot <Python_Bot@openeuler.org> - 0.0.62-1
- Package Spec generated