├── .coveragerc ├── .gitignore ├── .travis.yml ├── LICENSE ├── README.md ├── autocolors.py ├── cliStocksTracker.py ├── config.ini ├── multiconfigparser.py ├── portfolio.py ├── renderer.py ├── requirements.txt ├── sample-portfolio.ini ├── tests ├── test_portfolio.py └── test_utils.py └── utils.py /.coveragerc: -------------------------------------------------------------------------------- 1 | [run] 2 | omit = 3 | # We don't need test coverage of our tests 4 | ./tests/* 5 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | __pycache__ 2 | portfolio.ini 3 | config.ini 4 | *.fund 5 | *.vscode 6 | .pytest_cache 7 | .coverage 8 | coverage.xml 9 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | python: 3 | - "3.9" 4 | before_install: 5 | - pip install -U pip 6 | - pip install -U pytest-cov 7 | install: 8 | - pip install -r requirements.txt 9 | script: 10 | - pytest --cov=./ 11 | after_success: 12 | - bash <(curl -s https://codecov.io/bash) -t 4d88a700-0288-415e-ba58-839ffb7a06fc 13 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # cliStocksTracker 2 | [![GitHub](https://img.shields.io/github/license/ConradSelig/cliStocksTracker?style=for-the-badge)](https://github.com/ConradSelig/cliStocksTracker/blob/main/LICENSE) 3 | [![GitHub contributors](https://img.shields.io/github/contributors/ConradSelig/cliStocksTracker?style=for-the-badge)](https://github.com/ConradSelig/cliStocksTracker/graphs/contributors) 4 | [![GitHub last commit](https://img.shields.io/github/last-commit/ConradSelig/cliStocksTracker?style=for-the-badge)](https://github.com/ConradSelig/cliStocksTracker/commits/main) 5 | [![codecov](https://codecov.io/gh/ConradSelig/cliStocksTracker/branch/main/graph/badge.svg?token=RKF57QQZLX)](https://codecov.io/gh/ConradSelig/cliStocksTracker) 6 | 7 | A command line stock market / portfolio tracker originally inspired by [Ericm's Stonks](https://github.com/ericm/stonks) program, featuring unicode for incredibly high detailed 8 | graphs even in a terminal. 9 | 10 | ![image](https://user-images.githubusercontent.com/31974507/107873060-ac3af380-6e6c-11eb-8673-10fed1a16f0a.png) 11 | 12 | ## Installation 13 | 14 | This project is still in Beta, so there is no executable packaged with the project. 15 | 16 | Requirements: 17 | * Python >= 3.6.9 18 | * plotille >= 3.7.2 19 | * numpy >= 1.19.5 20 | * yfinance >= 0.1.55 21 | * pytz >= 2021.1 22 | * colorama >= 0.4.4 23 | * webcolors==1.11.1 24 | * matplotlib>=3.3.4 25 | 26 | ### Manual 27 | ``` 28 | $ git clone https://github.com/ConradSelig/cliStocksTracker 29 | $ cd cliStocksTracker 30 | $ python3 -m pip install -r requirements.txt 31 | ``` 32 | 33 | ## Usage 34 | ``` 35 | usage: cliStocksTracker.py [-h] [--width WIDTH] [--height HEIGHT] 36 | [--independent-graphs] [--timezone TIMEZONE] 37 | [-r ROUNDING_MODE] [-ti TIME_INTERVAL] 38 | [-tp TIME_PERIOD] [--config CONFIG] 39 | [--portfolio-config PORTFOLIO_CONFIG] [-g] 40 | 41 | Options for cliStockTracker.py 42 | 43 | optional arguments: 44 | -h, --help show this help message and exit 45 | --width WIDTH integer for the width of the chart (default is 80) 46 | --height HEIGHT integer for the height of the chart (default is 20) 47 | --independent-graphs show a chart for each stock 48 | --timezone TIMEZONE your timezone (ex: America/New_York) 49 | -r ROUNDING_MODE, --rounding-mode ROUNDING_MODE 50 | how should numbers be rounded (math | down) 51 | -ti TIME_INTERVAL, --time-interval TIME_INTERVAL 52 | specify time interval for graphs (ex: 1m, 15m, 1h) 53 | -tp TIME_PERIOD, --time-period TIME_PERIOD 54 | specify time period for graphs (ex: 15m, 1h, 1d) 55 | --config CONFIG path to a config.ini file 56 | --portfolio-config PORTFOLIO_CONFIG 57 | path to a portfolio.ini file with your list of stonks 58 | -g, --generate-config 59 | generates example config files 60 | ``` 61 | 62 | Do note that any given command line argument will override settings from the config file. 63 | ## Configuration 64 | 65 | cliStocksTracker relies on two config files, "config.ini" and "portfolio.ini". 66 | 67 | ### config.ini 68 | 69 | ``` 70 | [Frame] 71 | width=[ graph width ] 72 | height=[ graph height ] 73 | 74 | [General] 75 | independent_graphs=[ True | False ] 76 | timezone=[ pytz timezone stamp (ex. "America/New_York", "Asia/Shanghai", etc) ] 77 | rounding_mode=[math | down] 78 | ``` 79 | If independent_graphs is True, all the given stocks will be graphed on the same plot, otherwise all of the given stocks will be printed on independent plots. 80 | There is currently no grouping of stocks, either manual or automatic (planned). 81 | 82 | A default config.ini is packaged with the project. 83 | 84 | **All keys in config.ini file are required.** 85 | 86 | ### portfolio.ini 87 | 88 | ``` 89 | [ stock symbol ] 90 | graph=[ True | False ] 91 | buy=[ count ]@[ price ] 92 | buy=10.786@14.56 # 10.786 stocks were bought at $14.56 93 | buy=2.3@14.68 # an additional 2.3 stocks were bought at @14.68 94 | sell=[ count ]@[ price ] 95 | sell=5.3@16.43 # 5.3 stocks were sold at $16.43 96 | color=[str] 97 | 98 | [ stock symbol ] 99 | graph=[ True | False ] 100 | buy=[ count ]@[ price ] 101 | sell=[ count ]@[ price ] 102 | color=[str] 103 | ... 104 | ``` 105 | 106 | An unlimited number of 'buy' and 'sell' keys are allowed for each symbol. **Yes, duplicate keys do work. So just add another line into your portfolio every time you buy or sell a stock**, 107 | cliStocksTracker will take care of the weighted average to give you as accurate data as possible. 108 | 109 | *Planned feature to have cliStocksTracker automatically condense these keys down to a single line at runtime, as well as allowing buying and 110 | selling as command line arguments*. 111 | 112 | Each stock symbol has four additional config settings: 113 | 1. "graph": Determines if a graph is plotted of this symbol. 114 | 2. "buy": A buy order, formatted as "count at price". Duplicates of this key are allowed. 115 | 3. "sell": A sell order, formatted as "count at price". Duplicates of this key are allowed. 116 | 4. "color": The custom color to display the stock on the graphs. This is not a mandatory configuration setting, and if left empty automatic color selection will take place. 117 | 118 | The color can be chosen from the following list of colors: 119 | 120 | > 'aliceblue', 'antiquewhite', 'aqua', 'aquamarine', 'azure', 'beige', 'bisque', 'black', 'blanchedalmond', 'blue', 'blueviolet', 'brown', 'burlywood', 'cadetblue', 'chartreuse', 121 | 'chocolate', 'coral', 'cornflowerblue', 'cornsilk', 'crimson', 'cyan', 'darkblue', 'darkcyan', 'darkgoldenrod', 'darkgray', 'darkgrey', 'darkgreen', 'darkkhaki', 'darkmagenta', 122 | 'darkolivegreen', 'darkorange', 'darkorchid', 'darkred', 'darksalmon', 'darkseagreen', 'darkslateblue', 'darkslategray', 'darkslategrey', 'darkturquoise', 'darkviolet', 123 | 'deeppink', 'deepskyblue', 'dimgray', 'dimgrey', 'dodgerblue', 'firebrick', 'floralwhite', 'forestgreen', 'fuchsia', 'gainsboro', 'ghostwhite', 'gold', 'goldenrod', 'gray', 124 | 'grey', 'green', 'greenyellow', 'honeydew', 'hotpink', 'indianred', 'indigo', 'ivory', 'khaki', 'lavender', 'lavenderblush', 'lawngreen', 'lemonchiffon', 'lightblue', 'lightcoral', 125 | 'lightcyan', 'lightgoldenrodyellow', 'lightgray', 'lightgrey', 'lightgreen', 'lightpink', 'lightsalmon', 'lightseagreen', 'lightskyblue', 'lightslategray', 'lightslategrey', 126 | 'lightsteelblue', 'lightyellow', 'lime', 'limegreen', 'linen', 'magenta', 'maroon', 'mediumaquamarine', 'mediumblue', 'mediumorchid', 'mediumpurple', 'mediumseagreen', 127 | 'mediumslateblue', 'mediumspringgreen', 'mediumturquoise', 'mediumvioletred', 'midnightblue', 'mintcream', 'mistyrose', 'moccasin', 'navajowhite', 'navy', 'oldlace', 128 | 'olive', 'olivedrab', 'orange', 'orangered', 'orchid', 'palegoldenrod', 'palegreen', 'paleturquoise', 'palevioletred', 'papayawhip', 'peachpuff', 'peru', 'pink', 'plum', 129 | 'powderblue', 'purple', 'red', 'rosybrown', 'royalblue', 'saddlebrown', 'salmon', 'sandybrown', 'seagreen', 'seashell', 'sienna', 'silver', 'skyblue', 'slateblue', 'slategray', 130 | 'slategrey', 'snow', 'springgreen', 'steelblue', 'tan', 'teal', 'thistle', 'tomato', 'turquoise', 'violet', 'wheat', 'white', 'whitesmoke', 'yellow', 'yellowgreen' 131 | 132 | All keys in the portfolio config file are optional, so this: 133 | ``` 134 | [GME] 135 | [AMC] 136 | [HPE] 137 | [AAPL] 138 | ``` 139 | is actually a valid portfolio.ini! (even if it shows you basically nothing...) 140 | 141 | ## Similar projects 142 | 143 | - [DidierRLopes/GameStonkTerminal](https://github.com/DidierRLopes/GamestonkTerminal) - Python 144 | - [aranair/rtscli](https://github.com/aranair/rtscli) - Python 145 | --- 146 | - [mop-tracker/mop](https://github.com/mop-tracker/mop) - Go 147 | - [achannarasappa/ticker](https://github.com/achannarasappa/ticker) - Go 148 | --- 149 | - [tarkah/tickrs](https://github.com/tarkah/tickrs) - Rust 150 | -------------------------------------------------------------------------------- /autocolors.py: -------------------------------------------------------------------------------- 1 | color_list = [ 2 | "#FF0000", 3 | "#00FF00", 4 | "#0000FF", 5 | "#FFFF00", 6 | "#FF00FF", 7 | "#00FFFF", 8 | "#000000", 9 | "#800000", 10 | "#008000", 11 | "#000080", 12 | "#808000", 13 | "#800080", 14 | "#008080", 15 | "#808080", 16 | "#C00000", 17 | "#00C000", 18 | "#0000C0", 19 | "#C0C000", 20 | "#C000C0", 21 | "#00C0C0", 22 | "#C0C0C0", 23 | "#400000", 24 | "#004000", 25 | "#000040", 26 | "#404000", 27 | "#400040", 28 | "#004040", 29 | "#404040", 30 | "#200000", 31 | "#002000", 32 | "#000020", 33 | "#202000", 34 | "#200020", 35 | "#002020", 36 | "#202020", 37 | "#600000", 38 | "#006000", 39 | "#000060", 40 | "#606000", 41 | "#600060", 42 | "#006060", 43 | "#606060", 44 | "#A00000", 45 | "#00A000", 46 | "#0000A0", 47 | "#A0A000", 48 | "#A000A0", 49 | "#00A0A0", 50 | "#A0A0A0", 51 | "#E00000", 52 | "#00E000", 53 | "#0000E0", 54 | "#E0E000", 55 | "#E000E0", 56 | "#00E0E0", 57 | "#E0E0E0", 58 | ] 59 | -------------------------------------------------------------------------------- /cliStocksTracker.py: -------------------------------------------------------------------------------- 1 | import pytz 2 | import utils 3 | import plotille 4 | import warnings 5 | import argparse 6 | import webcolors 7 | import autocolors 8 | import contextlib 9 | import multiconfigparser 10 | 11 | import numpy as np 12 | import yfinance as market 13 | import portfolio as port 14 | 15 | from datetime import datetime, timedelta 16 | from renderer import Renderer 17 | 18 | 19 | def merge_config(config, args): 20 | if "General" in config: 21 | if "independent_graphs" in config["General"]: 22 | args.independent_graphs = config["General"]["independent_graphs"] == "True" 23 | if "timezone" in config["General"]: 24 | args.timezone = config["General"]["timezone"] 25 | if "rounding_mode" in config["General"]: 26 | args.rounding_mode = config["General"]["rounding_mode"] 27 | 28 | if "Frame" in config: 29 | if "width" in config["Frame"]: 30 | args.width = int(config["Frame"]["width"]) 31 | if "height" in config["Frame"]: 32 | args.heigth = int(config["Frame"]["height"]) 33 | 34 | return 35 | 36 | 37 | def main(): 38 | config = multiconfigparser.ConfigParserMultiOpt() 39 | stocks_config = multiconfigparser.ConfigParserMultiOpt() 40 | args = parse_args() 41 | 42 | portfolio = port.Portfolio() 43 | 44 | # read config files 45 | config.read(args.config) 46 | stocks_config.read(args.portfolio_config) 47 | 48 | # verify that config file is correct 49 | # merge options from cli and config 50 | verify_stock_keys(stocks_config) 51 | merge_config(config, args) 52 | 53 | portfolio.populate(stocks_config, args) 54 | portfolio.gen_graphs( 55 | args.independent_graphs, args.width, args.height, args.timezone 56 | ) 57 | 58 | # print to the screen 59 | render_engine = Renderer(args.rounding_mode, portfolio) 60 | render_engine.render() 61 | 62 | return 63 | 64 | 65 | def parse_args(): 66 | parser = argparse.ArgumentParser(description="Options for cliStockTracker.py") 67 | parser.add_argument( 68 | "--width", 69 | type=int, 70 | help="integer for the width of the chart (default is 80)", 71 | default=80, 72 | ) 73 | parser.add_argument( 74 | "--height", 75 | type=int, 76 | help="integer for the height of the chart (default is 20)", 77 | default=20, 78 | ) 79 | parser.add_argument( 80 | "--independent-graphs", 81 | action="store_true", 82 | help="show a chart for each stock (default false)", 83 | default=False, 84 | ) 85 | parser.add_argument( 86 | "--timezone", 87 | type=str, 88 | help="your timezone (exmple and default: America/New_York)", 89 | default="America/New_York", 90 | ) 91 | parser.add_argument( 92 | "-r", 93 | "--rounding-mode", 94 | type=str, 95 | help="how should numbers be rounded (math | down) (default math)", 96 | default="math", 97 | ) 98 | parser.add_argument( 99 | "-ti", 100 | "--time-interval", 101 | type=str, 102 | help="specify time interval for graphs (ex: 1m, 15m, 1h) (default 1m)", 103 | default="1m", 104 | ) 105 | parser.add_argument( 106 | "-tp", 107 | "--time-period", 108 | type=str, 109 | help="specify time period for graphs (ex: 15m, 1h, 1d) (default 1d)", 110 | default="1d", 111 | ) 112 | parser.add_argument( 113 | "--config", type=str, help="path to a config.ini file", default="config.ini" 114 | ) 115 | parser.add_argument( 116 | "--portfolio-config", 117 | type=str, 118 | help="path to a portfolio.ini file with your list of stonks", 119 | default="portfolio.ini", 120 | ) 121 | args = parser.parse_args() 122 | return args 123 | 124 | 125 | def verify_stock_keys(stocks_config): 126 | # check that at least one stock is in portfolio.ini 127 | if list(stocks_config.keys()) == ["DEFAULT"]: 128 | print( 129 | "portfolio.ini has no stocks added or does not exist. There is nothing to show." 130 | ) 131 | exit() # nothing else to do! Just force exit. 132 | 133 | 134 | if __name__ == "__main__": 135 | main() 136 | -------------------------------------------------------------------------------- /config.ini: -------------------------------------------------------------------------------- 1 | [Frame] 2 | width=80 3 | height=20 4 | 5 | [General] 6 | independent_graphs=False 7 | timezone=America/New_York 8 | rounding_mode=math -------------------------------------------------------------------------------- /multiconfigparser.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import configparser 3 | 4 | 5 | class ConfigParserMultiOpt(configparser.RawConfigParser): 6 | """ConfigParser allowing duplicate keys. Values are stored in a list""" 7 | 8 | def __init__(self): 9 | configparser.RawConfigParser.__init__( 10 | self, empty_lines_in_values=False, strict=False 11 | ) 12 | 13 | def _read(self, fp, fpname): 14 | """Parse a sectioned configuration file. 15 | 16 | Each section in a configuration file contains a header, indicated by 17 | a name in square brackets (`[]'), plus key/value options, indicated by 18 | `name' and `value' delimited with a specific substring (`=' or `:' by 19 | default). 20 | 21 | Values can span multiple lines, as long as they are indented deeper 22 | than the first line of the value. Depending on the parser's mode, blank 23 | lines may be treated as parts of multiline values or ignored. 24 | 25 | Configuration files may include comments, prefixed by specific 26 | characters (`#' and `;' by default). Comments may appear on their own 27 | in an otherwise empty line or may be entered in lines holding values or 28 | section names. 29 | """ 30 | elements_added = set() 31 | cursect = None # None, or a dictionary 32 | sectname = None 33 | optname = None 34 | lineno = 0 35 | indent_level = 0 36 | e = None # None, or an exception 37 | for lineno, line in enumerate(fp, start=1): 38 | comment_start = None 39 | # strip inline comments 40 | for prefix in self._inline_comment_prefixes: 41 | index = line.find(prefix) 42 | if index == 0 or (index > 0 and line[index - 1].isspace()): 43 | comment_start = index 44 | break 45 | # strip full line comments 46 | for prefix in self._comment_prefixes: 47 | if line.strip().startswith(prefix): 48 | comment_start = 0 49 | break 50 | value = line[:comment_start].strip() 51 | if not value: 52 | if self._empty_lines_in_values: 53 | # add empty line to the value, but only if there was no 54 | # comment on the line 55 | if ( 56 | comment_start is None 57 | and cursect is not None 58 | and optname 59 | and cursect[optname] is not None 60 | ): 61 | cursect[optname].append("") # newlines added at join 62 | else: 63 | # empty line marks end of value 64 | indent_level = sys.maxsize 65 | continue 66 | # continuation line? 67 | first_nonspace = self.NONSPACECRE.search(line) 68 | cur_indent_level = first_nonspace.start() if first_nonspace else 0 69 | if cursect is not None and optname and cur_indent_level > indent_level: 70 | cursect[optname].append(value) 71 | # a section header or option header? 72 | else: 73 | indent_level = cur_indent_level 74 | # is it a section header? 75 | mo = self.SECTCRE.match(value) 76 | if mo: 77 | sectname = mo.group("header") 78 | if sectname in self._sections: 79 | if self._strict and sectname in elements_added: 80 | raise DuplicateSectionError(sectname, fpname, lineno) 81 | cursect = self._sections[sectname] 82 | elements_added.add(sectname) 83 | elif sectname == self.default_section: 84 | cursect = self._defaults 85 | else: 86 | cursect = self._dict() 87 | self._sections[sectname] = cursect 88 | self._proxies[sectname] = configparser.SectionProxy( 89 | self, sectname 90 | ) 91 | elements_added.add(sectname) 92 | # So sections can't start with a continuation line 93 | optname = None 94 | # no section header in the file? 95 | elif cursect is None: 96 | raise MissingSectionHeaderError(fpname, lineno, line) 97 | # an option line? 98 | else: 99 | mo = self._optcre.match(value) 100 | if mo: 101 | optname, vi, optval = mo.group("option", "vi", "value") 102 | if not optname: 103 | e = self._handle_error(e, fpname, lineno, line) 104 | optname = self.optionxform(optname.rstrip()) 105 | if self._strict and (sectname, optname) in elements_added: 106 | raise configparser.DuplicateOptionError( 107 | sectname, optname, fpname, lineno 108 | ) 109 | elements_added.add((sectname, optname)) 110 | # This check is fine because the OPTCRE cannot 111 | # match if it would set optval to None 112 | if optval is not None: 113 | optval = optval.strip() 114 | # Check if this optname already exists 115 | if (optname in cursect) and (cursect[optname] is not None): 116 | # If it does, convert it to a tuple if it isn't already one 117 | if not isinstance(cursect[optname], tuple): 118 | cursect[optname] = tuple(cursect[optname]) 119 | cursect[optname] = cursect[optname] + tuple([optval]) 120 | else: 121 | cursect[optname] = [optval] 122 | else: 123 | # valueless option handling 124 | cursect[optname] = None 125 | else: 126 | # a non-fatal parsing error occurred. set up the 127 | # exception but keep going. the exception will be 128 | # raised at the end of the file and will contain a 129 | # list of all bogus lines 130 | e = self._handle_error(e, fpname, lineno, line) 131 | # if any parsing errors occurred, raise an exception 132 | if e: 133 | raise e 134 | self._join_multiline_values() 135 | -------------------------------------------------------------------------------- /portfolio.py: -------------------------------------------------------------------------------- 1 | import pytz 2 | import utils 3 | import plotille 4 | import warnings 5 | import webcolors 6 | import autocolors 7 | 8 | import numpy as np 9 | import yfinance as market 10 | 11 | from dataclasses import dataclass 12 | from datetime import datetime, timedelta 13 | 14 | 15 | @dataclass 16 | class Stock: 17 | symbol: str 18 | data: list 19 | 20 | def __post_init__(self): 21 | self.curr_value = self.data[-1] 22 | self.open_value = self.data[0] 23 | self.high = max(self.data) 24 | self.low = min(self.data) 25 | self.average = sum(self.data) / len(self.data) 26 | self.change_amount = self.curr_value - self.open_value 27 | self.change_percentage = (self.change_amount / self.curr_value) * 100 28 | return 29 | 30 | 31 | @dataclass 32 | class PortfolioEntry: 33 | stock: Stock 34 | count: float 35 | average_cost: float 36 | graph: bool = False 37 | color: str = None 38 | 39 | def __post_init__(self): 40 | self.holding_market_value = self.stock.curr_value * self.count 41 | self.holding_open_value = self.stock.open_value * self.count 42 | self.cost_basis = self.count * self.average_cost 43 | self.gains = self.holding_market_value - self.cost_basis 44 | if self.count == 0: 45 | self.gains_per_share = 0 46 | else: 47 | self.gains_per_share = self.gains / self.count 48 | return 49 | 50 | 51 | class Portfolio(metaclass=utils.Singleton): 52 | def __init__(self, *args, **kwargs): 53 | self.stocks = {} 54 | self.open_market_value = 0 # portfolio worth at market open 55 | self.cost_value = ( 56 | 0 # amount invested into the portfolio (sum of cost of shares) 57 | ) 58 | self.market_value = 0 # current market value of shares 59 | return 60 | 61 | def add_entry( 62 | self, 63 | stock: Stock, 64 | count: float, 65 | average_buyin_cost: float, 66 | color: str, 67 | graph: bool, 68 | ): 69 | entry = PortfolioEntry(stock, count, average_buyin_cost, graph, color) 70 | self.stocks[stock.symbol] = entry 71 | 72 | self.open_market_value += entry.holding_open_value 73 | self.market_value += entry.holding_market_value 74 | self.cost_value += entry.cost_basis 75 | return 76 | 77 | def get_stocks(self): 78 | return self.stocks 79 | 80 | def get_stock(self, symbol): 81 | return self.stocks[symbol] 82 | 83 | def average_buyin(self, buys: list, sells: list): 84 | buy_c, buy_p, sell_c, sell_p, count, bought_at = 0, 0, 0, 0, 0, 0 85 | buys = [_.split("@") for _ in ([buys] if type(buys) is not tuple else buys)] 86 | sells = [_.split("@") for _ in ([sells] if type(sells) is not tuple else sells)] 87 | 88 | for buy in buys: 89 | next_c = float(buy[0]) 90 | if next_c <= 0: 91 | print( 92 | 'A negative "buy" key was detected. Use the sell key instead to guarantee accurate calculations.' 93 | ) 94 | exit() 95 | buy_c += next_c 96 | buy_p += float(buy[1]) * next_c 97 | 98 | for sell in sells: 99 | next_c = float(sell[0]) 100 | if next_c <= 0: 101 | print( 102 | 'A negative "sell" key was detected. Use the buy key instead to guarantee accurate calculations.' 103 | ) 104 | exit() 105 | sell_c += next_c 106 | sell_p += float(sell[1]) * next_c 107 | 108 | count = buy_c - sell_c 109 | if count == 0: 110 | return 0, 0 111 | 112 | bought_at = (buy_p - sell_p) / count 113 | 114 | return count, bought_at 115 | 116 | # download all ticker data in a single request 117 | # harder to parse but this provides a signficant performance boost 118 | def download_market_data(self, args, stocks): 119 | # get graph time interval and period 120 | time_period = args.time_period if args.time_period else "1d" 121 | time_interval = args.time_interval if args.time_interval else "1m" 122 | 123 | try: 124 | return market.download( 125 | tickers=stocks, 126 | period=time_period, 127 | interval=time_interval, 128 | progress=False, 129 | ) 130 | except Exception as e: 131 | print( 132 | "cliStocksTracker must be connected to the internet to function. Please ensure that you are connected to the internet and try again." 133 | ) 134 | print("Error message:", e) 135 | 136 | def populate(self, stocks_config, args): 137 | sections = stocks_config.sections() 138 | 139 | # download all stock data 140 | market_data = self.download_market_data(args, sections) 141 | 142 | # iterate through each ticker data 143 | data_key = "Open" 144 | for ticker in sections: 145 | # convert the numpy array into a list of prices while removing NaN values 146 | # if there is only one section, the data frame is not split into tickers 147 | if len(sections) > 1: 148 | data = market_data[data_key][ticker].values[ 149 | ~np.isnan(market_data[data_key][ticker].values) 150 | ] 151 | else: 152 | data = market_data[data_key].values[ 153 | ~np.isnan(market_data[data_key].values) 154 | ] 155 | new_stock = Stock(ticker, data) 156 | 157 | # calculate average buy in 158 | buyin = ( 159 | stocks_config[ticker]["buy"] 160 | if "buy" in list(stocks_config[ticker].keys()) 161 | else () 162 | ) 163 | sellout = ( 164 | stocks_config[ticker]["sell"] 165 | if "sell" in list(stocks_config[ticker].keys()) 166 | else () 167 | ) 168 | count, bought_at = self.average_buyin(buyin, sellout) 169 | 170 | # Check the stock color for graphing 171 | color = ( 172 | str(stocks_config[ticker]["color"]) 173 | if "color" in list(stocks_config[ticker].keys()) 174 | else None 175 | ) 176 | 177 | # Check that the stock color that was entered is legal 178 | colorWarningFlag = True 179 | if color == None: 180 | colorWarningFlag = False 181 | elif type(color) == str: 182 | if (color.startswith("#")) or ( 183 | color in webcolors.CSS3_NAMES_TO_HEX.keys() 184 | ): 185 | colorWarningFlag = False 186 | 187 | if colorWarningFlag: 188 | warnings.warn( 189 | "The color selected for " 190 | + ticker 191 | + " is not in not in the approved list. Automatic color selection will be used." 192 | ) 193 | color = None 194 | 195 | should_graph = ( 196 | "graph" in list(stocks_config[ticker].keys()) 197 | and stocks_config[ticker]["graph"] == "True" 198 | ) 199 | 200 | # finally, add the stock to the portfolio 201 | self.add_entry(new_stock, count, bought_at, color, should_graph) 202 | 203 | def gen_graphs(self, independent_graphs, graph_width, graph_height, cfg_timezone): 204 | graphs = [] 205 | if not independent_graphs: 206 | graphing_list = [] 207 | color_list = [] 208 | for sm in self.get_stocks().values(): 209 | if sm.graph: 210 | graphing_list.append(sm.stock) 211 | color_list.append(sm.color) 212 | if len(graphing_list) > 0: 213 | graphs.append( 214 | Graph( 215 | graphing_list, 216 | graph_width, 217 | graph_height, 218 | color_list, 219 | timezone=cfg_timezone, 220 | ) 221 | ) 222 | else: 223 | for sm in self.get_stocks().values(): 224 | if sm.graph: 225 | graphs.append( 226 | Graph( 227 | [sm.stock], 228 | graph_width, 229 | graph_height, 230 | [sm.color], 231 | timezone=cfg_timezone, 232 | ) 233 | ) 234 | 235 | for graph in graphs: 236 | graph.gen_graph(autocolors.color_list) 237 | self.graphs = graphs 238 | return 239 | 240 | 241 | class Graph: 242 | def __init__( 243 | self, stocks: list, width: int, height: int, colors: list, *args, **kwargs 244 | ): 245 | self.stocks = stocks 246 | self.graph = "" 247 | self.colors = colors 248 | self.plot = plotille.Figure() 249 | 250 | self.plot.width = width 251 | self.plot.height = height 252 | self.plot.color_mode = "rgb" 253 | self.plot.X_label = "Time" 254 | self.plot.Y_label = "Value" 255 | 256 | if "timezone" in kwargs.keys(): 257 | self.timezone = pytz.timezone(kwargs["timezone"]) 258 | else: 259 | self.timezone = pytz.utc 260 | 261 | if "starttime" in kwargs.keys(): 262 | self.start = ( 263 | kwargs["startend"].replace(tzinfo=pytz.utc).astimezone(self.timezone) 264 | ) 265 | else: 266 | self.start = ( 267 | datetime.now() 268 | .replace(hour=14, minute=30, second=0) 269 | .replace(tzinfo=pytz.utc) 270 | .astimezone(self.timezone) 271 | ) 272 | 273 | if "endtime" in kwargs.keys(): 274 | self.end = ( 275 | kwargs["endtime"].replace(tzinfo=pytz.utc).astimezone(self.timezone) 276 | ) 277 | else: 278 | self.end = ( 279 | datetime.now() 280 | .replace(hour=21, minute=0, second=0) 281 | .replace(tzinfo=pytz.utc) 282 | .astimezone(self.timezone) 283 | ) 284 | 285 | self.plot.set_x_limits(min_=self.start, max_=self.end) 286 | 287 | return 288 | 289 | def __call__(self): 290 | return self.graph 291 | 292 | def draw(self): 293 | print(self.graph) 294 | return 295 | 296 | def gen_graph(self, auto_colors): 297 | self.y_min, self.y_max = self.find_y_range() 298 | self.plot.set_y_limits(min_=self.y_min, max_=self.y_max) 299 | 300 | for i, stock in enumerate(self.stocks): 301 | if self.colors[i] == None: 302 | color = webcolors.hex_to_rgb(auto_colors[i % 67]) 303 | elif self.colors[i].startswith("#"): 304 | color = webcolors.hex_to_rgb(self.colors[i]) 305 | else: 306 | color = webcolors.hex_to_rgb( 307 | webcolors.CSS3_NAMES_TO_HEX[self.colors[i]] 308 | ) 309 | 310 | self.plot.plot( 311 | [self.start + timedelta(minutes=i) for i in range(len(stock.data))], 312 | stock.data, 313 | lc=color, 314 | label=stock.symbol, 315 | ) 316 | 317 | self.graph = self.plot.show(legend=True) 318 | return 319 | 320 | def find_y_range(self): 321 | y_min = 10000000000000 # Arbitrarily large number (bigger than any single stock should ever be worth) 322 | y_max = 0 323 | 324 | for stock in self.stocks: 325 | if y_min > min(stock.data): 326 | y_min = min(stock.data) 327 | if y_max < max(stock.data): 328 | y_max = max(stock.data) 329 | 330 | return y_min, y_max 331 | -------------------------------------------------------------------------------- /renderer.py: -------------------------------------------------------------------------------- 1 | import io 2 | import utils 3 | import portfolio 4 | 5 | from colorama import Fore, Style, Back 6 | from dataclasses import dataclass 7 | from datetime import datetime, timedelta 8 | from typing import List, Callable 9 | 10 | 11 | @dataclass 12 | class CellData: 13 | value: str 14 | color: str = Fore.RESET 15 | 16 | 17 | @dataclass 18 | class ColumnFormatter: 19 | header: str 20 | width: int 21 | 22 | # function that takes a thing and produces a printable string for it 23 | generator: Callable[[object], CellData] = lambda v: CellData(str(v)) 24 | 25 | def generate_string(self, input) -> str: 26 | cell_data = self.generator(input) 27 | return cell_data.value 28 | 29 | 30 | def format_number(value) -> str: 31 | return str(abs(utils.round_value(value, "math", 2))) 32 | 33 | 34 | def format_gl(value: float, is_currency: bool = True) -> str: 35 | change_symbol = "+" if value >= 0 else "-" 36 | if is_currency: 37 | change_symbol += "$" 38 | 39 | return change_symbol + format_number(value) 40 | 41 | 42 | _stock_column_formatters = { 43 | "Ticker": ColumnFormatter("Ticker", 9, lambda stock: CellData(stock.symbol)), 44 | "Current Price": ColumnFormatter( 45 | "Last", 12, lambda stock: CellData(format_number(stock.curr_value)) 46 | ), 47 | "Daily Change Amount": ColumnFormatter( 48 | "Chg", 49 | 12, 50 | lambda stock: CellData( 51 | format_gl(stock.change_amount), 52 | Fore.GREEN if stock.change_amount >= 0 else Fore.RED, 53 | ), 54 | ), 55 | "Daily Change Percentage": ColumnFormatter( 56 | "Chg%", 57 | 10, 58 | lambda stock: CellData( 59 | format_gl(stock.change_percentage, False) + "%", 60 | Fore.GREEN if stock.change_percentage >= 0 else Fore.RED, 61 | ), 62 | ), 63 | "Low": ColumnFormatter("Low", 12, lambda stock: CellData(format_number(stock.low))), 64 | "High": ColumnFormatter( 65 | "High", 12, lambda stock: CellData(format_number(stock.high)) 66 | ), 67 | "Daily Average Price": ColumnFormatter( 68 | "Avg", 12, lambda stock: CellData(format_number(stock.average)) 69 | ), 70 | } 71 | 72 | _portfolio_column_formatters = { 73 | "Stocks Owned": ColumnFormatter( 74 | "Owned", 9, lambda entry: CellData(format_number(entry.count)) 75 | ), 76 | "Gains per Share": ColumnFormatter( 77 | "G/L/S", 78 | 12, 79 | lambda entry: CellData( 80 | format_gl(entry.gains_per_share), 81 | Fore.GREEN if entry.gains_per_share >= 0 else Fore.RED, 82 | ), 83 | ), 84 | "Current Market Value": ColumnFormatter( 85 | "Mkt V", 12, lambda entry: CellData(format_number(entry.holding_market_value)) 86 | ), 87 | "Average Buy Price": ColumnFormatter( 88 | "Buy", 12, lambda entry: CellData(format_number(entry.average_cost)) 89 | ), 90 | "Total Share Gains": ColumnFormatter( 91 | "G/L/T", 92 | 12, 93 | lambda entry: CellData( 94 | format_gl(entry.gains), Fore.GREEN if entry.gains >= 0 else Fore.RED 95 | ), 96 | ), 97 | "Total Share Cost": ColumnFormatter( 98 | "Cost", 12, lambda entry: CellData(format_number(entry.cost_basis)) 99 | ), 100 | } 101 | 102 | 103 | class Renderer(metaclass=utils.Singleton): 104 | def __init__(self, rounding: str, portfolio: portfolio.Portfolio, *args, **kwargs): 105 | self.mode = rounding 106 | self.portfolio = portfolio 107 | return 108 | 109 | def render(self): 110 | print() 111 | for graph in self.portfolio.graphs: 112 | graph.draw() 113 | 114 | self.print_new_table() 115 | print() 116 | return 117 | 118 | def print_gains(self, format_str, gain, timespan): 119 | positive_gain = gain >= 0 120 | gain_symbol = "+" if positive_gain else "-" 121 | gain_verboge = "Gained" if positive_gain else "Lost" 122 | 123 | print("{:25}".format("Value " + gain_verboge + " " + timespan + ": "), end="") 124 | print(Fore.GREEN if positive_gain else Fore.RED, end="") 125 | 126 | # This prevents a runtime warning by making sure we are never dividing by zero 127 | if self.portfolio.cost_value == 0: 128 | gain_val = 0 129 | else: 130 | gain_val = gain / self.portfolio.cost_value * 100 131 | print( 132 | format_str.format( 133 | gain_symbol + "$" + str(abs(utils.round_value(gain, self.mode, 2))) 134 | ) 135 | + format_str.format( 136 | gain_symbol + str(abs(utils.round_value(gain_val, self.mode, 2))) + "%" 137 | ) 138 | ) 139 | print(Style.RESET_ALL, end="") 140 | return 141 | 142 | def print_overall_summary(self): 143 | print( 144 | "\n" 145 | + "{:25}".format("Current Time: ") 146 | + "{:13}".format(datetime.now().strftime("%A %b %d, %Y - %I:%M:%S %p")) 147 | ) 148 | print( 149 | "{:25}".format("Total Cost: ") 150 | + "{:13}".format("$" + format_number(self.portfolio.cost_value)) 151 | ) 152 | print( 153 | "{:25}".format("Total Value: ") 154 | + "{:13}".format("$" + format_number(self.portfolio.market_value)) 155 | ) 156 | 157 | # print daily value 158 | value_gained_day = ( 159 | self.portfolio.market_value - self.portfolio.open_market_value 160 | ) 161 | self.print_gains("{:13}", value_gained_day, "Today") 162 | 163 | # print overall value 164 | value_gained_all = self.portfolio.market_value - self.portfolio.cost_value 165 | self.print_gains("{:13}", value_gained_all, "Overall") 166 | return 167 | 168 | def print_new_table( 169 | self, 170 | stock_cols=list(_stock_column_formatters.keys()), 171 | portfolio_cols=list(_portfolio_column_formatters.keys()), 172 | ): 173 | # print heading 174 | print("\nPortfolio Summary:\n") 175 | 176 | # print the heading 177 | heading = "\t" 178 | divider = "\t" 179 | for col in stock_cols + portfolio_cols: 180 | column = _stock_column_formatters.get( 181 | col 182 | ) or _portfolio_column_formatters.get(col) 183 | heading += ("{:" + str(column.width) + "}").format(column.header) 184 | divider += "-" * column.width 185 | print(heading + "\n" + divider) 186 | 187 | # now print every portfolio entry 188 | for i, entry in enumerate(self.portfolio.stocks.values()): 189 | stock = entry.stock 190 | line = "\t" 191 | 192 | highlight_color = Back.LIGHTBLACK_EX if i % 2 == 0 else Back.RESET 193 | line += highlight_color 194 | 195 | for i, col in enumerate(stock_cols + portfolio_cols): 196 | col_formatter = _stock_column_formatters.get(col) 197 | 198 | is_stock = col_formatter != None 199 | if not is_stock: 200 | col_formatter = _portfolio_column_formatters.get(col) 201 | 202 | cell_data = col_formatter.generator(stock if is_stock else entry) 203 | line += cell_data.color + ( 204 | "{:" + str(col_formatter.width) + "}" 205 | ).format(cell_data.value) 206 | 207 | # print the entry 208 | line += Style.RESET_ALL 209 | print(line) 210 | 211 | # TODO: print totals line 212 | 213 | self.print_overall_summary() 214 | return 215 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | pytz 2 | yfinance 3 | pytest 4 | colorama 5 | dataclasses 6 | numpy 7 | plotille 8 | webcolors 9 | -------------------------------------------------------------------------------- /sample-portfolio.ini: -------------------------------------------------------------------------------- 1 | [AAPL] 2 | graph=True 3 | buy=10@100 4 | buy=5@120 5 | sell=3@122 6 | sell=8@125 7 | color=#FFFF00 8 | 9 | [SPKE] 10 | graph=False 11 | buy=1@10.28 12 | buy=1@10.30 13 | sell=1@10.32 14 | color=lime 15 | -------------------------------------------------------------------------------- /tests/test_portfolio.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | import pytest 4 | from pandas import DataFrame 5 | 6 | sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) 7 | import portfolio 8 | import autocolors 9 | 10 | class BlankArgs: 11 | time_period = None 12 | time_interval = None 13 | 14 | 15 | class BlankStocksConfig: 16 | tickers = {} 17 | 18 | def __getitem__(self, key): 19 | return self.tickers[key] 20 | 21 | def sections(self): 22 | return list(self.tickers.keys()) 23 | 24 | 25 | class TestStockDataclass: 26 | 27 | my_stock = portfolio.Stock("TEST", [2, 1, 3, 5, 4]) 28 | 29 | def test_symbol(self): 30 | assert self.my_stock.symbol == "TEST" 31 | 32 | def test_curr_value(self): 33 | assert self.my_stock.curr_value == 4 34 | 35 | def test_open_value(self): 36 | assert self.my_stock.open_value == 2 37 | 38 | def test_high(self): 39 | assert self.my_stock.high == 5 40 | 41 | def test_low(self): 42 | assert self.my_stock.low == 1 43 | 44 | def test_average(self): 45 | assert self.my_stock.average == 3 46 | 47 | def test_change_amount(self): 48 | return self.my_stock.change_amount == 2 49 | 50 | def test_change_percentage(self): 51 | return self.my_stock.change_percentage == 100 52 | 53 | 54 | class TestPortfolioEntryDataclass: 55 | 56 | my_stock = portfolio.Stock("TEST", [2, 1, 3, 5, 4]) 57 | my_portfolio_entry = portfolio.PortfolioEntry(my_stock, 4, 2.5, False, "blue") 58 | my_portfolio_entry_none_owned = portfolio.PortfolioEntry( 59 | my_stock, 0, 2.5, False, "blue" 60 | ) 61 | 62 | def test_holding_market_value(self): 63 | assert self.my_portfolio_entry.holding_market_value == 16 64 | 65 | def test_holding_open_value(self): 66 | assert self.my_portfolio_entry.holding_open_value == 8 67 | 68 | def test_cost_basis(self): 69 | assert self.my_portfolio_entry.cost_basis == 10 70 | 71 | def test_gains(self): 72 | assert self.my_portfolio_entry.gains == 6 73 | 74 | def test_gains_per_share_none_owned(self): 75 | assert self.my_portfolio_entry_none_owned.gains_per_share == 0 76 | 77 | def test_gains_per_share(self): 78 | assert self.my_portfolio_entry.gains_per_share == 1.5 79 | 80 | 81 | class TestPortfolio: 82 | 83 | my_portfolio = portfolio.Portfolio() 84 | my_stock_1 = portfolio.Stock("TEST_1", [2, 1, 3, 5, 4]) 85 | my_stock_2 = portfolio.Stock("TEST_2", [2, 1, 3, 5, 4]) 86 | 87 | def test_add_entry(self): 88 | self.my_portfolio.add_entry(self.my_stock_1, 4, 2, "blue", False) 89 | self.my_portfolio.add_entry(self.my_stock_2, 6, 3, "red", False) 90 | errors = [] 91 | 92 | if not len(self.my_portfolio.stocks) == 2: 93 | errors.append( 94 | f"A stock was not added to the portfolio. {len(self.my_portfolio.stocks)} != 2" 95 | ) 96 | if not self.my_portfolio.open_market_value == 20: 97 | errors.append( 98 | f"The open market value was not correctly calculated. {self.my_portfolio.open_market_value} != 20" 99 | ) 100 | if not self.my_portfolio.market_value == 40: 101 | errors.append( 102 | f"The current market value was not correctly calculated. {self.my_portfolio.market_value} != 40" 103 | ) 104 | if not self.my_portfolio.cost_value == 26: 105 | errors.append( 106 | f"The cost value was not correctly calculated. {self.my_portfolio.cost_value} != 30" 107 | ) 108 | 109 | assert not errors, "errors occured:\n{}".format("\n".join(errors)) 110 | 111 | def test_get_stocks(self): 112 | assert len(self.my_portfolio.stocks) == 2 113 | 114 | def test_get_stock(self): 115 | errors = [] 116 | 117 | if not self.my_portfolio.get_stock("TEST_1").color == "blue": 118 | errors.append("TEST_1 stock returned the wrong color.") 119 | if not self.my_portfolio.get_stock("TEST_2").color == "red": 120 | errors.append("TEST_2 stock returned the wrong color.") 121 | 122 | assert not errors, "errors occured:\n{}".format("\n".join(errors)) 123 | 124 | def test_average_buyin(self): 125 | set_a = ("1@1", "1@2", "1@3") 126 | set_b = ("1@1", "1@2", "2@3") 127 | set_c = ("100@1", "1@2", "1@3") 128 | 129 | errors = [] 130 | 131 | if not self.my_portfolio.average_buyin(set_a, ()) == (3, 2): 132 | errors.append( 133 | f"Buyin average failed (Case 1). {self.my_portfolio.average_buyin(set_a, ())} != (3, 2)" 134 | ) 135 | if not self.my_portfolio.average_buyin(set_b, ()) == (4, 2.25): 136 | errors.append( 137 | f"Buyin average failed (Case 2). {self.my_portfolio.average_buyin(set_b, ())} != (4, 2.25)" 138 | ) 139 | if not self.my_portfolio.average_buyin(set_c, ()) == (102, 1.0294117647058822): 140 | errors.append( 141 | f"Buyin average failed (Case 3). {self.my_portfolio.average_buyin(set_c, ())} != (102, 1.0294117647058822)" 142 | ) 143 | if not self.my_portfolio.average_buyin(set_b, set_b) == (0, 0): 144 | errors.append( 145 | f"Buyin average failed (Case 4). {self.my_portfolio.average_buyin(set_b, set_b)} != (0, 0)" 146 | ) 147 | if not self.my_portfolio.average_buyin(set_b, set_a) == (1, 3): 148 | errors.append( 149 | f"Buyin average failed (Case 5). {self.my_portfolio.average_buyin(set_b, set_a)} != (1, 3)" 150 | ) 151 | if not self.my_portfolio.average_buyin(set_c, set_a) == (99, 1): 152 | errors.append( 153 | f"Buyin average failed (Case 6). {self.my_portfolio.average_buyin(set_c, set_a)} != (102, 1.0294117647058822)" 154 | ) 155 | 156 | assert not errors, "errors occured:\n{}".format("\n".join(errors)) 157 | 158 | def test_download_market_data(self): 159 | assert ( 160 | type(self.my_portfolio.download_market_data(BlankArgs(), ["AAPL"])) 161 | == DataFrame 162 | ) 163 | 164 | def test_populate(self): 165 | errors = [] 166 | test_stocks_config = BlankStocksConfig() 167 | args = BlankArgs() 168 | 169 | # remove all stocks that might have slipped into the portfolio 170 | self.my_portfolio.stocks = {} 171 | # single stock populate 172 | test_stocks_config.tickers = {"AAPL": {"graph": "True"}} 173 | self.my_portfolio.populate(test_stocks_config, args) 174 | if not len(self.my_portfolio.stocks) == 1 and "AAPL" not in self.my_portfolio.stocks.keys(): 175 | errors.append( 176 | f"Single stock population failed. {len(self.my_portfolio.stocks)} != 1, \"AAPL\" not in {self.my_portfolio.stocks.keys()}" 177 | ) 178 | 179 | # remove all stocks that might have slipped into the portfolio 180 | self.my_portfolio.stocks = {} 181 | # multiple stock populate 182 | test_stocks_config.tickers = {"AAPL": {"graph": "True"}, "TSLA": {"graph": "True"}} 183 | self.my_portfolio.populate(test_stocks_config, args) 184 | if not len(self.my_portfolio.stocks) == 2 and "AAPL" not in self.my_portfolio.stocks.keys() and "TSLA" not in self.my_portfolio.stocks.keys(): 185 | errors.append( 186 | f"Multiple stock population failed. {len(self.my_portfolio.stocks)} != 2, \"AAPL\" or \"TSLA\" not in {self.my_portfolio.stocks.keys()}" 187 | ) 188 | 189 | assert not errors, "errors occured:\n{}".format("\n".join(errors)) 190 | 191 | def test_gen_graphs(self): 192 | errors = [] 193 | test_stocks_config = BlankStocksConfig() 194 | test_args = BlankArgs() 195 | 196 | # independent_graphs 197 | self.my_portfolio.stocks = {} 198 | test_stocks_config.tickers = {"AAPL": {"graph": "True"}, "TSLA": {"graph": "True"}} 199 | self.my_portfolio.populate(test_stocks_config, test_args) 200 | self.my_portfolio.gen_graphs(True, 30, 30, "America/New_York") 201 | if not len(self.my_portfolio.graphs) == 2: 202 | errors.append( 203 | f"Independent graphs gen_graphs() failed. {len(self.my_portfolio.graphs)} != 2" 204 | ) 205 | 206 | # single_graph 207 | self.my_portfolio.graphs = [] 208 | self.my_portfolio.gen_graphs(False, 30, 30, "America/New_York") 209 | if not len(self.my_portfolio.graphs) == 1: 210 | errors.append( 211 | f"Combined graphs gen_graphs() failed. {len(self.my_portfolio.graphs)} != 1" 212 | ) 213 | assert not errors, "errors occured:\n{}".format("\n".join(errors)) 214 | 215 | -------------------------------------------------------------------------------- /tests/test_utils.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | import pytest 4 | 5 | sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) 6 | from utils import round_value, Singleton 7 | 8 | 9 | class mysingleton(metaclass=Singleton): 10 | def __init__(cls): 11 | cls.count = 0 12 | 13 | def add_one(self): 14 | self.count += 1 15 | 16 | 17 | class TestSingleton: 18 | def test_create_new(self, ensure_singleton_exists=False): 19 | self.new_singleton = mysingleton() 20 | if not ensure_singleton_exists: 21 | assert self.new_singleton.count == 0 22 | 23 | def test_create_again(self): 24 | self.test_create_new(ensure_singleton_exists=True) 25 | self.new_singleton.add_one() 26 | self.new_singleton = mysingleton() 27 | assert self.new_singleton.count == 1 28 | 29 | 30 | class TestRoundValue: 31 | def test_math(self): 32 | assert round_value(1.456543, "math", 2) == 1.46 33 | 34 | def test_down(self): 35 | assert round_value(1.456543, "down", 2) == 1.45 36 | 37 | def test_zero(self): 38 | assert round_value(0, "math", 2) == 0 39 | 40 | def test_nan(self): 41 | assert round_value(float("NaN"), "math", 2) == 0 42 | 43 | def test_invalid_decimals(self): 44 | with pytest.raises(TypeError): 45 | round_value(1.456543, "math", "Hello World") 46 | 47 | def test_negative_decimals(self): 48 | assert round_value(1.456543, "math", -3) == 0 49 | 50 | def test_zero_decimals_math(self): 51 | assert round_value(1.456543, "math", 0) == 1 52 | 53 | def test_zero_decimals_down(self): 54 | assert round_value(1.456543, "down", 0) == 1 55 | -------------------------------------------------------------------------------- /utils.py: -------------------------------------------------------------------------------- 1 | from math import trunc, isnan 2 | 3 | 4 | class Singleton(type): 5 | _instances = {} 6 | 7 | def __call__(cls, *args, **kwargs): 8 | if cls not in cls._instances: 9 | cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) 10 | return cls._instances[cls] 11 | 12 | 13 | # Rounds value down to the desired number of decimals digits (controlled decimal_places) using math or truncate mode 14 | def round_value(value, mode, decimal_places): 15 | # test for any case where 0 needs to be returned 16 | if value == 0 or isnan(value) or decimal_places < 0: 17 | return 0 18 | # test and make sure the decimal_places is an integer 19 | if type(decimal_places) != int: 20 | raise TypeError( 21 | "'" + str(type(decimal_places)) + "' cannot be interpreted as an integer" 22 | ) 23 | # if math rounding, just use pythons builtin 24 | if mode == "math": 25 | return round(value, decimal_places) 26 | elif mode == "down": 27 | # if the decimal places are zero, we can just truncate 28 | if decimal_places == 0: 29 | return trunc(value) 30 | 31 | factor = 10.0 ** decimal_places 32 | return trunc(value * factor) / factor 33 | --------------------------------------------------------------------------------