├── rrlib ├── __init__.py ├── btreports │ └── golden │ │ ├── 21-05-27.png │ │ ├── 21-05-30.png │ │ ├── 21-05-31.png │ │ └── 21-06-03.png ├── utils │ └── robotRay.service ├── rrOptions.py ├── rrIFTTT.py ├── test.py ├── robotRay.sample.ini ├── rrLogger.py ├── rrTelegram.py ├── rrGoldenStrategy.py ├── rrDataFetcher.py ├── rrBacktrader.py ├── rrDFPublic.py ├── rrServer.py ├── rrPortfolio.py ├── rrDFIB.py ├── rrDailyScan.py ├── rrGoldenBt.py ├── rrController.py ├── rrPutSellStrategy.py └── rrDb.py ├── rrDb.db ├── requirements.txt ├── .gitignore ├── README.md └── LICENSE /rrlib/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | -------------------------------------------------------------------------------- /rrDb.db: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/camilo-rojas/robotRay/HEAD/rrDb.db -------------------------------------------------------------------------------- /rrlib/btreports/golden/21-05-27.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/camilo-rojas/robotRay/HEAD/rrlib/btreports/golden/21-05-27.png -------------------------------------------------------------------------------- /rrlib/btreports/golden/21-05-30.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/camilo-rojas/robotRay/HEAD/rrlib/btreports/golden/21-05-30.png -------------------------------------------------------------------------------- /rrlib/btreports/golden/21-05-31.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/camilo-rojas/robotRay/HEAD/rrlib/btreports/golden/21-05-31.png -------------------------------------------------------------------------------- /rrlib/btreports/golden/21-06-03.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/camilo-rojas/robotRay/HEAD/rrlib/btreports/golden/21-06-03.png -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | backtrader 2 | bs4 3 | pandas 4 | peewee 5 | configparser 6 | schedule 7 | requests 8 | finvizfinance 9 | tqdm 10 | python-telegram-bot 11 | keyring 12 | ib_insync 13 | yfinance 14 | matplotlib 15 | TA_Lib 16 | pysqlite3 17 | -------------------------------------------------------------------------------- /rrlib/utils/robotRay.service: -------------------------------------------------------------------------------- 1 | #CentOS service sample implementation 2 | 3 | [Unit] 4 | Description=robotRay 5 | After=syslog.target 6 | #Requires= 7 | 8 | [Service] 9 | Type=idle 10 | User=camilor 11 | Group=camilor 12 | WorkingDirectory=/home/camilor/robotRay/robotRay 13 | TimeoutStartSec=0 14 | #ExecStartPre= 15 | StandardOutput=syslog 16 | StandardError=syslog 17 | Environment="HOME_DIR=/home/camilor/robotRay/robotRay" 18 | Environment=PATH="$HOME_DIR:$PATH" 19 | ExecStart=${HOME_DIR}/venv/bin/python3.9 rrlib/rrServer.py 20 | 21 | [Install] 22 | WantedBy=multi-user.target 23 | 24 | # CentOS - service install config 25 | # place .service file in /etc/systemd/system, adapt home and path 26 | # sudo systemctl enable /etc/systemd/system/robotRay.service 27 | # sudo systemctl start /etc/systemd/system/robotRay.service 28 | # sudo systemctl status robotRay.service 29 | # journalctl -u robotRay.service 30 | -------------------------------------------------------------------------------- /rrlib/rrOptions.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on Sat Sep 15 14:46:12 2018 5 | robotRay server v1.0 6 | @author: camilorojas 7 | 8 | Optin Manager class for put formating and supporting tools 9 | """ 10 | import datetime 11 | import sys 12 | import os 13 | 14 | 15 | class OptionManager: 16 | 17 | def getPutFormater(stock, expiration, strike): 18 | sys.path.append(os.path.join(os.path.dirname(__file__), '..')) 19 | month = int(expiration) 20 | month = datetime.date.today()+datetime.timedelta(month*365/12) 21 | ym = month.strftime("%y-%m") 22 | from rrlib.rrDb import rrDbManager 23 | db = rrDbManager() 24 | ymd = db.completeExpirationDate(ym) 25 | if strike < 10: 26 | trailer = "P0000" 27 | elif strike < 100: 28 | trailer = "P000" 29 | elif strike < 1000: 30 | trailer = "P00" 31 | elif strike < 10000: 32 | trailer = "P0" 33 | else: 34 | trailer = "P" 35 | return str(stock+ymd+trailer+str(strike)+"000") 36 | 37 | def getDatebyMonth(month): 38 | sys.path.append(os.path.join(os.path.dirname(__file__), '..')) 39 | from rrlib.rrDb import rrDbManager 40 | db = rrDbManager() 41 | return db.getDatebyMonth(month) 42 | -------------------------------------------------------------------------------- /rrlib/rrIFTTT.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on 07 04 2021 5 | robotRay server v1.0 6 | @author: camilorojas 7 | 8 | IFTT message implementation for RobotRay for one way communication on operational status 9 | 10 | """ 11 | 12 | import datetime 13 | import sys 14 | import os 15 | import time 16 | import configparser 17 | import requests 18 | 19 | 20 | class Singleton(type): 21 | _instances = {} 22 | 23 | def __call__(cls, *args, **kwargs): 24 | if cls not in cls._instances: 25 | cls._instances[cls] = super( 26 | Singleton, cls).__call__(*args, **kwargs) 27 | # else: 28 | # cls._instances[cls].__init__(*args, **kwargs) 29 | return cls._instances[cls] 30 | 31 | 32 | class rrIFTTT(metaclass=Singleton): 33 | 34 | def __init__(self, *args, **kwargs): 35 | # starting common services 36 | sys.path.append(os.path.join(os.path.dirname(__file__), '..')) 37 | # starting logging 38 | from rrlib.rrLogger import logger 39 | self.log = logger() 40 | # starting ini parameters 41 | config = configparser.ConfigParser() 42 | config.read("rrlib/robotRay.ini") 43 | # Telegram API key & chat id for secure comms 44 | self.IFTTT = config['ifttt']['key'] 45 | self.url = config['ifttt']['url'] 46 | self.log.logger.debug(" rrIFTTT module starting. ") 47 | 48 | def send(self, report): 49 | if self.IFTTT != "": 50 | try: 51 | r = requests.post( 52 | self.url+self.IFTTT, data=report) 53 | if r.status_code == 200: 54 | self.log.logger.debug(" sent message") 55 | return r 56 | except Exception as e: 57 | self.log.logger.error(" IFTTT error:") 58 | self.log.logger.error(e) 59 | -------------------------------------------------------------------------------- /rrlib/test.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | import sys 4 | import os 5 | import pandas as pd 6 | from pprint import pprint 7 | from bs4 import BeautifulSoup as bs 8 | import urllib 9 | from urllib.error import URLError, HTTPError 10 | import yfinance as yf 11 | 12 | 13 | if True: 14 | sys.path.append(os.path.join(os.path.dirname(__file__), '..')) 15 | from rrlib.rrPortfolio import rrPortfolio 16 | from rrlib.rrDFIB import StockDFIB 17 | from rrlib.rrDFIB import OptionDFIB 18 | from rrlib.rrDFPublic import StockDFPublic 19 | from rrlib.rrDFPublic import OptionDFPublic 20 | from rrlib.rrDataFetcher import OptionDataFetcher as optFetcher 21 | from rrlib.rrDailyScan import rrDailyScan as ds 22 | from rrlib.rrBacktrader import rrBacktrader as bt 23 | 24 | nflx = yf.Ticker("NFLX") 25 | opt = nflx.option_chain('2021-11-19') 26 | pprint(opt.puts.strike) 27 | 28 | 29 | """ 30 | try: 31 | sauce = urllib.request.urlopen( 32 | "https://finance.yahoo.com/quote/NFLX211119P00390000", timeout=10).read() 33 | except HTTPError as e: 34 | if e.code == 404: 35 | soup = bs(e.fp.read()) 36 | print(soup.prettify()) 37 | print( 38 | " HTTP Error= "+str(e.code)) 39 | except URLError as e: 40 | print( 41 | " URL Error= "+str(e.code)) 42 | else: 43 | soup = bs(sauce, 'html.parser') 44 | pprint(soup.prettify()) 45 | 46 | 47 | pd.set_option('display.max_columns', None) 48 | ds().dailyScan() 49 | 50 | https://finance.yahoo.com/quote/NFLX211119P00390000 51 | 52 | stockIB = StockDFIB("AAPL") 53 | print(stockIB.getIntradayData()) 54 | print(stockIB.getData()) 55 | stockP = StockDFPublic("AAPL") 56 | print(stockP.getIntradayData()) 57 | print(stockP.getData()) 58 | 59 | option = OptionDFIB("CRM") 60 | print(option.getData(3, 160)) 61 | 62 | op = OptionDFPublic("CRM") 63 | print(op.getData(3, 160)) 64 | p = rrPortfolio() 65 | p.switchSource("ib") 66 | option = OptionDFIB("CRM") 67 | print(option.getData(3, 160)) 68 | print(stock.getIntradayData()) 69 | pd.set_option('display.max_columns', None) 70 | print(p.R) 71 | print(p.BP) 72 | print(p.funds) 73 | print(p.getAccount()) 74 | print(p.getBuyingPower()) 75 | print(p.getRealizedPNL()) 76 | print(p.getUnrealizedPNL()) 77 | print(p.getCash()) 78 | print(p.getAvailableFunds()) 79 | strikes = optFetcher("SHOP").getStrikes() 80 | print(strikes) 81 | """ 82 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | env.sh 2 | config.py 3 | rrlib/__pycache__/ 4 | rrlib/robotRay.ini 5 | *.db 6 | .DS_Store 7 | # Byte-compiled / optimized / DLL files 8 | __pycache__/ 9 | *.py[cod] 10 | *$py.class 11 | 12 | # C extensions 13 | *.so 14 | 15 | # Distribution / packaging 16 | .Python 17 | build/ 18 | develop-eggs/ 19 | dist/ 20 | downloads/ 21 | eggs/ 22 | .eggs/ 23 | lib/ 24 | lib64/ 25 | parts/ 26 | sdist/ 27 | var/ 28 | wheels/ 29 | pip-wheel-metadata/ 30 | share/python-wheels/ 31 | *.egg-info/ 32 | .installed.cfg 33 | *.egg 34 | MANIFEST 35 | 36 | # PyInstaller 37 | # Usually these files are written by a python script from a template 38 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 39 | *.manifest 40 | *.spec 41 | 42 | # Installer logs 43 | pip-log.txt 44 | pip-delete-this-directory.txt 45 | 46 | # Unit test / coverage reports 47 | htmlcov/ 48 | .tox/ 49 | .nox/ 50 | .coverage 51 | .coverage.* 52 | .cache 53 | nosetests.xml 54 | coverage.xml 55 | *.cover 56 | *.py,cover 57 | .hypothesis/ 58 | .pytest_cache/ 59 | 60 | # Translations 61 | *.mo 62 | *.pot 63 | 64 | # Django stuff: 65 | *.log 66 | local_settings.py 67 | db.sqlite3 68 | db.sqlite3-journal 69 | 70 | # Flask stuff: 71 | instance/ 72 | .webassets-cache 73 | 74 | # Scrapy stuff: 75 | .scrapy 76 | 77 | # Sphinx documentation 78 | docs/_build/ 79 | 80 | # PyBuilder 81 | target/ 82 | 83 | # Jupyter Notebook 84 | .ipynb_checkpoints 85 | 86 | # IPython 87 | profile_default/ 88 | ipython_config.py 89 | 90 | # pyenv 91 | .python-version 92 | 93 | # pipenv 94 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 95 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 96 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 97 | # install all needed dependencies. 98 | #Pipfile.lock 99 | 100 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 101 | __pypackages__/ 102 | 103 | # Celery stuff 104 | celerybeat-schedule 105 | celerybeat.pid 106 | 107 | # SageMath parsed files 108 | *.sage.py 109 | 110 | # Environments 111 | .env 112 | .venv 113 | env/ 114 | venv/ 115 | ENV/ 116 | env.bak/ 117 | venv.bak/ 118 | 119 | # Spyder project settings 120 | .spyderproject 121 | .spyproject 122 | 123 | # Rope project settings 124 | .ropeproject 125 | 126 | # mkdocs documentation 127 | /site 128 | 129 | # mypy 130 | .mypy_cache/ 131 | .dmypy.json 132 | dmypy.json 133 | 134 | # Pyre type checker 135 | .pyre/ 136 | -------------------------------------------------------------------------------- /rrlib/robotRay.sample.ini: -------------------------------------------------------------------------------- 1 | #RobotRay INI file with parameters for operational and comms 2 | 3 | [debug] 4 | #work outside regular trading hours 5 | oth=No 6 | #fast start for development, no initial stock data fetch and intraday 7 | faststart=No 8 | 9 | [scheduler] 10 | #interval in hours 11 | stockdatainterval= 4 12 | #interval in minutes 13 | stockintrainterval=20 14 | stockoptioninverval=30 15 | #hour for daily report 24 hour format separating with : 16 | dailyreport=19:50 17 | dailyscan=18:00 18 | # hour to run golden cross strategy 19 | goldenTime=09:00 20 | 21 | [stocks] 22 | #list of stock symbols to track with RobotRay and look for naked put strategies 23 | #separate by commas the stock symbols 24 | stocks=SQ,TTD,NFLX,TEAM,CRM,WDAY,PYPL,SPCE,COIN,CGC,MA,V,MSFT,PLTR,TWTR,DIS,RBLX 25 | 26 | [portfolio] 27 | # portfolio funds for disconnected operation, if source is ib, funds will be automatically retreived 28 | funds = 100000 29 | # R $ for risk unit 30 | R = 200 31 | # expected minimum monthly premium for holding the option 1% equivalent of 12% year ROI 32 | monthlyPremium=0.01 33 | # Available BP, future connect to IB 34 | BP=2000000 35 | 36 | [backtrader] 37 | #database to store backtrading info 38 | filename=rrBt.db 39 | #other timeframes 1d,5d,1mo,3mo,6mo,1y,2y,5y,10y,ytd,max 40 | timeframe=2y 41 | # Max investment in strategy in % terms of full portfolio funds 42 | maxinv = 3 43 | # Commissions by broker, 0.001 = 1% 44 | commission = 0.001 45 | # Margin requested by broker, ex IB for Stocks requires 25% (0.25) of total going long, 30% (0.3) short 46 | marginreq=0.27 47 | # Stop loss distance for stock stop loss 0.05= 5% drawdown in price 48 | stoploss=0.05 49 | 50 | [urlfetcher] 51 | #For manual fetching with BS4 this is the timeout in seconds 52 | Timeout = 20 53 | 54 | [datasource] 55 | #Source for data, can be public (fiviz and yahoo) or from IB (Interactive Brokers), so that datasources for stock and option data 56 | source=public 57 | #source=ib 58 | #Boolean to make data fetching parameters verbose and report status 59 | verbose = Yes 60 | 61 | [ib] 62 | #IP and Port for Interactive Broker desktop tool to connect for data info and trading 63 | ip=127.0.0.1 64 | port= 65 | 66 | [ifttt] 67 | #IFTT Webhook HTTP integration, to send emails or alerts to user based on BTC, STO or daily update 68 | key= 69 | # sample url: https://maker.ifttt.com/trigger/[yourrecepie]with/key/ 70 | url= 71 | 72 | [telegram] 73 | #Telegram HTTP api for two way communication with RobotRay 74 | api= 75 | startbot=No 76 | chatid= 77 | 78 | [DB] 79 | # filename for the database to store historical data 80 | filename=rrDB.db 81 | 82 | [sellputstrategy] 83 | #% to calculate strike based on recent performance and highs 0.25 means calculate strike at 25% below highs 84 | strikePctg = 0.25 85 | 86 | #Boolean to make thinking decision verbose and report status 87 | verbose = Yes 88 | 89 | # If price change daily is below -0.045 or -4.5% then go green, if its above 0.02 or 2% then go red, between yellow 90 | dayPriceChgGreen=-0.045 91 | dayPriceChgRed=0.02 92 | 93 | #sma200 below 0 is red, <0.1 yellow, > 0.1 green 94 | smaGreen=0.1 95 | smaRed=0 96 | 97 | #sales growth quarter to quarter > 30% green, below 10% red 98 | salesGrowthGreen=0.3 99 | salesGrowthRed=0.1 100 | 101 | #KPI for evaluation kpi green > 0.65, red below 0.5 102 | IntradayKPIGreen=0.65 103 | IntradayKPIRed=0.5 104 | 105 | #Number of days before mandatory BTCcomm 106 | BTCdays=45 107 | #Premium % before BTC -ej. 50% premium collected - 0.5 108 | PremiumTarget=0.5 109 | 110 | #Distance from expected price to option ask price to allow market flexibility 111 | ExpPrice2Ask=1.2 112 | -------------------------------------------------------------------------------- /rrlib/rrLogger.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on 07 05 2019 5 | robotRay server v1.0 6 | @author: camilorojas 7 | 8 | rrLogger class for logging throughout the RobotRay proyect 9 | 10 | """ 11 | 12 | import logging 13 | import sys 14 | import logging.handlers 15 | import os 16 | import tqdm 17 | import io 18 | from copy import copy 19 | from logging import Formatter 20 | 21 | MAPPING = { 22 | 'DEBUG': 37, # white 23 | 'INFO': 36, # cyan 24 | 'WARNING': 33, # yellow 25 | 'ERROR': 31, # red 26 | 'CRITICAL': 41, # white on red bg 27 | } 28 | 29 | PREFIX = '\033[' 30 | SUFFIX = '\033[0m' 31 | 32 | 33 | class Singleton(type): 34 | _instances = {} 35 | 36 | def __call__(cls, *args, **kwargs): 37 | if cls not in cls._instances: 38 | cls._instances[cls] = super( 39 | Singleton, cls).__call__(*args, **kwargs) 40 | # else: 41 | # cls._instances[cls].__init__(*args, **kwargs) 42 | return cls._instances[cls] 43 | 44 | 45 | class logger(metaclass=Singleton): 46 | def __init__(self): 47 | self.logger = logging.getLogger("rrLog") 48 | self.logger.setLevel(logging.INFO) 49 | fh = logging.FileHandler('rrLog.log') 50 | fh.setLevel(logging.INFO) 51 | ch = logging.StreamHandler(sys.stdout) 52 | ch.setLevel(logging.INFO) 53 | # Create a Formatter for formatting the log messages 54 | ft = logging.Formatter( 55 | '%(asctime)s - %(name)s - %(levelname)s - %(message)s', datefmt="%Y-%m-%d %H:%M:%S") 56 | # Add the Formatter to the Handler 57 | fh.setFormatter(ft) 58 | cf = ColoredFormatter( 59 | '%(asctime)s - %(name)s - %(levelname)s - %(message)s') 60 | ch.setFormatter(cf) 61 | if (self.logger.hasHandlers()): 62 | self.logger.handlers.clear() 63 | 64 | self.logger.addHandler(fh) 65 | self.logger.addHandler(ch) 66 | 67 | 68 | class TqdmToLogger(io.StringIO): 69 | """ 70 | Output stream for TQDM which will output to logger module instead of 71 | the StdOut. 72 | """ 73 | logger = None 74 | level = None 75 | buf = '' 76 | 77 | def __init__(self, logger, level=None): 78 | super(TqdmToLogger, self).__init__() 79 | self.logger = logger 80 | self.level = level or logging.INFO 81 | 82 | def write(self, buf): 83 | self.buf = buf.strip('\r\n\t ') 84 | 85 | def flush(self): 86 | self.logger.log(self.level, self.buf) 87 | 88 | 89 | class ColoredFormatter(Formatter): 90 | 91 | def __init__(self, patern): 92 | Formatter.__init__(self, patern, datefmt="%Y-%m-%d %H:%M:%S") 93 | 94 | def format(self, record): 95 | 96 | colored_record = copy(record) 97 | levelname = colored_record.levelname 98 | 99 | import platform 100 | if platform.system() == 'Windows': 101 | # Windows does not support ANSI escapes and we are using API calls to set the console color 102 | pass 103 | # logging.StreamHandler.emit = add_coloring_to_emit_windows(logging.StreamHandler.emit) 104 | else: 105 | # all non-Windows platforms are supporting ANSI escapes so we use them 106 | seq = MAPPING.get(levelname, 37) # default white 107 | colored_levelname = ('{0}{1}m{2}{3}').format( 108 | PREFIX, seq, levelname, SUFFIX) 109 | colored_record.levelname = colored_levelname 110 | # comment next line for only status coloring 111 | colored_record.msg = ('{0}{1}m{2}{3}').format( 112 | PREFIX, seq, colored_record.getMessage(), SUFFIX) 113 | 114 | return Formatter.format(self, colored_record) # -*- coding: utf-8 -*- 115 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # RobotRay 2 | 3 | Created by: Camilo Rojas - @camilo_rojas 4 | 5 | Buy Me A Coffee 6 | 7 | Python based robot trader on naked put strategy for selected accounts. 8 | 9 | The strategy selected for this bot is to sell puts for a selected number of stocks. The selection of the stock list is currently manual. 10 | 11 | ## Entry: 12 | The robot searches for opportunities in selling naked puts (sell to open), looking for days with a -4.5% daily price change, which normally increases volatility in the options for the stock. With the increase in vega we will evaluate the option chain for opportunities that offer a yield of 1% monthly or more. If we find an opportunity we will generate a prospect that will be managed. The amount of contracts and the R are all defined in a config file. 13 | 14 | ## Exit and Risk Management: 15 | RobotRay will manage the trade and monitor the following conditions: 1) Risk Loss management will close (BTC) if losses are 2x the amount of premium collected, 2) we are at 21 days to expiration, 3) we reach 50% target of total premium. 16 | 17 | The idea is to sell between 3 and 8 month Put options, and close (buy to close) to gain advantage of vega crush and short term volatility. Worst case scenario of being assigned the contract, bot will confirm buying power. 18 | 19 | This is a **high risk bot**. For academic purposes only, not for real world implementation. 20 | 21 | It connects info from Interactive Brokers for real market data and trading. Also leverages information from other public data sources to build an analytics model to select trades. 22 | 23 | All package requirements are included in the *requirements.txt* file in the project 24 | 25 | ## Future ideas: 26 | 1. Interactive Brokers automated trading 27 | 2. Report / Statistics of operation with full P&L reporting 28 | 3. Backtrading to review strategy for selected stocks 29 | 4. Automated stock selection and rejection based on portfolio and risk 30 | 5. Auto evaluate between open positions and new prospects to maximize % of success 31 | 32 | ## Architecture 33 | The project architecture is the following: 34 | 35 | ### Bootstrap: 36 | - rrServer - scheduling, threading 37 | 38 | ### View: 39 | - rrTelegram - communications through Telegram 40 | 41 | ### Controller: 42 | - rrController 43 | - rrDataFetcher - invoked by rrDB controls data fetching mechanism routing to public or IB 44 | 45 | ### Model: 46 | - rrDB - Handles DB manager for Stocks, Option Data and Intraday data 47 | - rrThinker - Handles DB manager for Prospects and its lifecycle 48 | - rrDFIB - Interactive Brokers data fetching 49 | - rrDFPublic - Finviz and Yahoo data fetching 50 | 51 | ### Utilities: 52 | - rrOptions - Support lib for Option formating and management 53 | - rrLogger - Logging 54 | 55 | ### Parametrization: 56 | - robotRay.ini - File with operational parameters and general configuration 57 | 58 | ## Getting Started 59 | In a Python shell invoke the *python3 rrlib/rrServer.py* command to start the bot trading program. 60 | Currently no command line parameters are supported, but operation can be configured from the ini file in the rrlib directory. 61 | 62 | ## Install on CentOS 8 63 | - Generate your userid for robotRay, need sudo (wheel) group for TA-lib and sqlite3 if it needs to be installed, useradd, passwd, usermod -aG wheel 64 | - Yum update python (3.8+), sqlite, ta-lib (https://mrjbq7.github.io/ta-lib/install.html), [tar, xz-devel, gcc, make for ta-lib install]. Or compile/install if not already 65 | - Create your robotRay directory and git fetch https://github.com/camilo-rojas/robotRay 66 | - Create your venv for python if required. python3 -m venv venv. Activate the environment source venv/bin/activate 67 | - Pip upgrade environment and install all requirements.txt 68 | - Adjust robotRay.ini based from robotRay.sample.ini with your parameters and stock 69 | * If you have problems installing pip install pysqlite3 with errors or problems be sure to install sudo yum install sqlite-devel 70 | -------------------------------------------------------------------------------- /rrlib/rrTelegram.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on 07 04 2021 5 | robotRay server v1.0 6 | @author: camilorojas 7 | 8 | Telegram chat implementation for RobotRay for two way communication on operational status 9 | 10 | """ 11 | 12 | import datetime 13 | import sys 14 | import os 15 | import time 16 | import configparser 17 | import telegram 18 | from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, Dispatcher 19 | 20 | 21 | class rrTelegram: 22 | def __init__(self, *args, **kwargs): 23 | # starting common services 24 | sys.path.append(os.path.join(os.path.dirname(__file__), '..')) 25 | # starting logging 26 | from rrlib.rrLogger import logger 27 | self.log = logger() 28 | # starting backend services 29 | from rrlib.rrDb import rrDbManager 30 | from rrlib.rrPutSellStrategy import rrPutSellStrategy as rps 31 | from rrlib.rrController import rrController 32 | self.db = rrDbManager() 33 | self.sellp = rps() 34 | self.cont = rrController() 35 | # starting ini parameters 36 | config = configparser.ConfigParser() 37 | config.read("rrlib/robotRay.ini") 38 | # Telegram API key & chat id for secure comms 39 | self.APIkey = config.get('telegram', 'api') 40 | self.chatid = config.get('telegram', 'chatid') 41 | self.startBot = config.get('telegram', 'startbot') 42 | self.log.logger.debug(" rrTelegram module starting. ") 43 | # starting bot 44 | # self.bot = telegram.bot(self.APIkey) 45 | self.upd = Updater(self.APIkey) 46 | self.dp = self.upd.dispatcher 47 | 48 | # function to handle the /start command 49 | def start(self, update, context): 50 | first_name = update.message.chat.first_name 51 | self.chat_id = update.message.chat_id 52 | if(str(self.chat_id) == str(self.chatid)): 53 | update.message.reply_text( 54 | f"Hi {first_name}, RobotRay ready for you.") 55 | else: 56 | update.message.reply_text("Hi you are not authorized") 57 | 58 | # function to handle the /help command 59 | def help(self, update, context): 60 | if(str(self.chat_id) == str(self.chatid)): 61 | update.message.reply_text('RobotRay help menu, following the options available:') 62 | else: 63 | update.message.reply_text("Hi you not authorized") 64 | 65 | # function to handle errors occured in the dispatcher 66 | def error(self, update, context): 67 | try: 68 | update.message.reply_text('RobotRay error occured.') 69 | except Exception: 70 | self.log.logger.error( 71 | " Robotray error ocurred, you have two instances running Telegram bot") 72 | 73 | # function to handle normal text 74 | def textCommand(self, update, context): 75 | text_received = update.message.text 76 | response = self.cont.botcommand(text_received) 77 | if len(response) > 0: 78 | for message in response[1:]: 79 | update.message.reply_text(f'{message}') 80 | if response[0] != "": 81 | if response[0].startswith("db."): 82 | func = getattr(self.db, response[0].split("db.", 1)[1]) 83 | if response[0].split("db.", 1)[1].startswith("print"): 84 | print(func()) 85 | else: 86 | func() 87 | elif response[0].startswith("sellp."): 88 | func = getattr(self.sellp, response[0].split("sellp.", 1)[1]) 89 | if response[0].split("sellp.", 1)[1].startswith("print"): 90 | print(func()) 91 | else: 92 | func() 93 | else: 94 | func = getattr(self, response[0]) 95 | func() 96 | 97 | def startbot(self): 98 | self.dp.add_handler(CommandHandler("start", self.start)) 99 | self.dp.add_handler(CommandHandler("help", self.help)) 100 | self.dp.add_handler(MessageHandler(Filters.text, self.textCommand)) 101 | self.dp.add_error_handler(self.error) 102 | # start the bot 103 | self.upd.start_polling() 104 | 105 | def sendMessage(self, message=""): 106 | if self.startBot != "No": 107 | self.upd.bot.send_message(self.chatid, text=message) 108 | 109 | def sendImage(self, url=""): 110 | if self.startBot != "No": 111 | self.upd.bot.send_photo(self.chatid, url) 112 | -------------------------------------------------------------------------------- /rrlib/rrGoldenStrategy.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on 07 04 2021 5 | robotRay server v1.0 6 | @author: camilorojas 7 | 8 | Golden Strategy 9 | 10 | Process for module 11 | 1. Evaluate SMA 200 and SMA 50 to find if there are any cross overs 12 | 2. In case of a golden cross over inform owner 13 | 3. In case or death cross over inform owner 14 | 15 | """ 16 | import sys 17 | import os 18 | from tqdm import tqdm 19 | import pandas as pd 20 | import datetime 21 | 22 | 23 | class rrGoldenStrategy: 24 | def __init__(self): 25 | # starting common services 26 | sys.path.append(os.path.join(os.path.dirname(__file__), '..')) 27 | # starting logging 28 | from rrlib.rrLogger import logger 29 | self.log = logger() 30 | # starting backend services 31 | from rrlib.rrDb import rrDbManager 32 | self.db = rrDbManager() 33 | # starting ini parameters 34 | import configparser 35 | config = configparser.ConfigParser() 36 | config.read("rrlib/robotRay.ini") 37 | self.log.logger.debug(" Golden Strategy module starting. ") 38 | 39 | def evaluateProspects(self): 40 | sys.path.append(os.path.join(os.path.dirname(__file__), '..')) 41 | from rrlib.rrDb import IntradayStockData 42 | from rrlib.rrDb import StockData 43 | try: 44 | for stock in IntradayStockData.select(): 45 | # for stock in tqdm(IntradayStockData.select(), desc="Getting SMAs of Stock Data:", unit="Stock", ascii=False, ncols=120, leave=False) 46 | st = pd.DataFrame(list(StockData.select(StockData.sma50, StockData.sma200, StockData.timestamp).where( 47 | StockData.stock == stock.stock).order_by(StockData.id.desc()).dicts())) 48 | sma50 = st.sma50 49 | sma200 = st.sma200 50 | times = st.timestamp 51 | # get stock data from 2 days earlier to find golden cross or death cross 52 | try: 53 | for i in [i for i, x in enumerate(times) if x < (datetime.datetime.now()-datetime.timedelta(days=2))]: 54 | position = i 55 | break 56 | # find trend 57 | sma200now = float(sma200[0].strip("%"))/100 58 | sma200old = float(sma200[position].strip("%"))/100 59 | sma50now = float(sma50[0].strip("%"))/100 60 | sma50old = float(sma50[position].strip("%"))/100 61 | 62 | if sma200now > sma50now: 63 | trend = "downtrend" 64 | elif sma200now < sma50now: 65 | trend = "uptrend" 66 | 67 | # look for golden or death and raise communication 68 | if sma200now > sma50now and sma200old < sma50old: 69 | m200 = ("SMA200 was "+str(sma200old)+", and now is "+str(sma200now)) 70 | m50 = ("SMA50 was "+str(sma50old)+", and now is "+str(sma50now)) 71 | self.log.logger.info( 72 | " Golden Strategy found a DEATH CROSS "+trend+" in:"+stock.stock) 73 | self.communicateProspects(stock.stock, "Death Cross") 74 | elif sma200now < sma50now and sma200old > sma50old: 75 | self.log.logger.info( 76 | " Golden Strategy found a GOLDEN CROSS "+trend + " in:"+stock.stock) 77 | self.communicateProspects(stock.stock, "Golden Cross "+m200+", "+m50) 78 | self.log.logger.debug("Stock:"+stock.stock+", is "+trend+", 50:"+str(sma50[0])+", "+str(sma50[position]) + ", 200:" + str( 79 | sma200[0])+", "+str(sma200[position])+"; time:"+str(times[0])+", "+str(times[position])) 80 | except Exception: 81 | self.log.logger.warning(" Golden Strategy for " + 82 | stock.stock+", not enough historic info") 83 | 84 | except Exception as e: 85 | self.log.logger.error(" Golden Strategy evaluation error:") 86 | self.log.logger.error(e) 87 | 88 | def communicateProspects(self, stock, gord): 89 | from rrlib.rrIFTTT import rrIFTTT 90 | from rrlib.rrTelegram import rrTelegram 91 | try: 92 | report = {} 93 | report["value1"] = "Golden Strategy: Prospect Found: Stock:"+stock 94 | report["value2"] = "Found a: "+gord 95 | report["value3"] = "Good luck! " 96 | self.log.logger.debug( 97 | " Communicator , invoking with these parameters "+str(report)) 98 | self.db.updateServerRun(prospectsFound="Yes") 99 | try: 100 | rrIFTTT().send(report) 101 | rrTelegram().sendMessage( 102 | str(report["value1"])+" | "+str(report["value2"])+" | "+str(report["value3"])) 103 | 104 | except Exception as e: 105 | self.log.logger.error( 106 | " Golden Strategy communicating error") 107 | self.log.logger.error(e) 108 | except Exception as e: 109 | self.log.logger.error( 110 | " Golden Strategy prospect communicator error") 111 | self.log.logger.error(e) 112 | -------------------------------------------------------------------------------- /rrlib/rrDataFetcher.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on 07 05 2019 5 | robotRay server v1.0 6 | @author: camilorojas 7 | 8 | Data Fetcher proxy for market data 9 | Data Fetcher supports public datasources from Finviz and Yahoo. And in 10 | v1 verson will support Interactive Brokers connectivity for data. 11 | 12 | DataFetcher calls two different py files with the specific fetching logic 13 | - rrDFPublic.py - will capture the public data sources 14 | - rrDFIB.py - will connect and gather info from Interactive Brokers 15 | 16 | """ 17 | 18 | import sys 19 | import os 20 | import pandas as pd 21 | 22 | 23 | class StockDataFetcher(): 24 | 25 | def __init__(self, symbol): 26 | # starting common services 27 | sys.path.append(os.path.join(os.path.dirname(__file__), '..')) 28 | # starting logging service 29 | from rrlib.rrLogger import logger 30 | self.symbol = symbol 31 | self.log = logger() 32 | self.log.logger.debug(" Init Stock Data Fetcher "+str(symbol)) 33 | # starting ini parameters 34 | import configparser 35 | config = configparser.ConfigParser() 36 | config.read("rrlib/robotRay.ini") 37 | # Get datasource from IB or Public 38 | self.source = config.get('datasource', 'source') 39 | # For manual fetching set time out 40 | self.timeout = int(config['urlfetcher']['Timeout']) 41 | 42 | def getData(self): 43 | sys.path.append(os.path.join(os.path.dirname(__file__), '..')) 44 | self.log.logger.debug(" About to retreive "+self.symbol) 45 | if (self.source == "public"): 46 | from rrlib.rrDFPublic import StockDFPublic as sdfp 47 | df = sdfp(self.symbol).getData() 48 | elif(self.source == "ib"): 49 | # implement class for ib retreival 50 | df = pd.DataFrame() 51 | else: 52 | self.log.logger.error(" DataFetcher source error:"+self.source) 53 | pd.set_option("display.max_rows", None, "display.max_columns", None) 54 | self.log.logger.debug(" Values loaded: \n"+str(df)) 55 | self.log.logger.debug( 56 | " DONE - Stock Data Fetcher "+str(self.symbol)) 57 | return df 58 | 59 | def getIntradayData(self): 60 | self.log.logger.debug(" About to retreive "+self.symbol) 61 | sys.path.append(os.path.join(os.path.dirname(__file__), '..')) 62 | if(self.source == "public"): 63 | from rrlib.rrDFPublic import StockDFPublic as sdfp 64 | df = sdfp(self.symbol).getIntradayData() 65 | self.log.logger.debug(" Values loaded: \n"+str(df)) 66 | elif(self.source == "ib"): 67 | self.log.logger.debug(" Loading intraday from IB") 68 | # implement class for ib retreival 69 | df = pd.DataFrame() 70 | else: 71 | self.log.logger.error(" DataFetcher source error:"+self.source) 72 | df = pd.DataFrame() 73 | self.log.logger.debug( 74 | " DONE - Stock Intraday Data Fetcher "+str(self.symbol)) 75 | return df 76 | 77 | 78 | class OptionDataFetcher(): 79 | 80 | def __init__(self, symbol): 81 | sys.path.append(os.path.join(os.path.dirname(__file__), '..')) 82 | from rrlib.rrLogger import logger 83 | self.symbol = symbol 84 | self.log = logger() 85 | self.log.logger.debug(" Init Option Data Fetcher for "+symbol) 86 | # timeout import 87 | import configparser 88 | config = configparser.ConfigParser() 89 | config.read("rrlib/robotRay.ini") 90 | self.timeout = int(config['urlfetcher']['Timeout']) 91 | self.source = config.get('datasource', 'source') 92 | 93 | # Strike int, month is int and the number of months after today 94 | def getData(self, month, strike): 95 | sys.path.append(os.path.join(os.path.dirname(__file__), '..')) 96 | if(self.source == "public"): 97 | from rrlib.rrDFPublic import OptionDFPublic as odfp 98 | df = odfp(self.symbol).getData(month, strike) 99 | self.log.logger.debug(" Values loaded: \n"+str(df)) 100 | elif(self.source == "ib"): 101 | self.log.logger.debug(" Loading option data from IB") 102 | # implement class for ib retreival 103 | df = pd.DataFrame() 104 | else: 105 | self.log.logger.error(" DataFetcher source error:"+self.source) 106 | df = pd.DataFrame() 107 | return df 108 | 109 | def getStrikes(self): 110 | sys.path.append(os.path.join(os.path.dirname(__file__), '..')) 111 | if(self.source == "public"): 112 | from rrlib.rrDFPublic import OptionDFPublic as odfp 113 | df = odfp(self.symbol).getStrikes() 114 | self.log.logger.debug(" Values loaded: \n"+str(df)) 115 | elif(self.source == "ib"): 116 | self.log.logger.debug(" Loading strikes from IB") 117 | # implement class for ib retreival 118 | df = pd.DataFrame() 119 | else: 120 | self.log.logger.error(" DataFetcher source error:"+self.source) 121 | df = pd.DataFrame() 122 | return df 123 | 124 | def getExpirations(self): 125 | sys.path.append(os.path.join(os.path.dirname(__file__), '..')) 126 | if(self.source == "public"): 127 | from rrlib.rrDFPublic import OptionDFPublic as odfp 128 | df = odfp(self.symbol).getExpirations() 129 | self.log.logger.debug(" Values loaded: \n"+str(df)) 130 | elif(self.source == "ib"): 131 | self.log.logger.debug(" Loading expirations from IB") 132 | # implement class for ib retreival 133 | df = pd.DataFrame() 134 | else: 135 | self.log.logger.error(" DataFetcher source error:"+self.source) 136 | df = pd.DataFrame() 137 | return df 138 | -------------------------------------------------------------------------------- /rrlib/rrBacktrader.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on 07 04 2021 5 | robotRay server v1.0 6 | @author: camilorojas 7 | 8 | Backtrader strategy classes 9 | 10 | Process for module 11 | 1. Gather data from yfinance the data for the stocks 12 | 3. Call the strategy backtrader 13 | 14 | Pending 15 | 2. Gather data from options (?) 16 | 17 | """ 18 | 19 | import yfinance as yf 20 | import pandas as pd 21 | import peewee as pw 22 | import datetime 23 | import sys 24 | import os 25 | from tqdm import tqdm 26 | 27 | sys.path.append(os.path.join(os.path.dirname(__file__), '..')) 28 | db = pw.SqliteDatabase('rrBt.db') 29 | 30 | 31 | class rrBacktrader: 32 | def __init__(self): 33 | # Starting common services 34 | from rrlib.rrLogger import logger, TqdmToLogger 35 | from rrlib.rrDb import rrDbManager 36 | # Get logging service 37 | self.db = rrDbManager() 38 | self.log = logger() 39 | self.tqdm_out = TqdmToLogger(self.log.logger) 40 | self.log.logger.debug(" Backtrader starting. ") 41 | # starting ini parameters 42 | import configparser 43 | config = configparser.ConfigParser() 44 | config.read("rrlib/robotRay.ini") 45 | # db filename to confirm it exists 46 | self.dbFilename = config.get('backtrader', 'filename') 47 | self.timeframe = config.get('backtrader', 'timeframe') 48 | self.initializeDb() 49 | # Get datsource from pubic or ib 50 | self.source = config.get('datasource', 'source') 51 | # Get verbose option boolean 52 | self.verbose = config.get('datasource', 'verbose') 53 | 54 | def initializeDb(self): 55 | historicData.create_table() 56 | 57 | def btSellPuts(self): 58 | pass 59 | 60 | def btGolden(self): 61 | from rrlib.rrGoldenBt import rrGoldenBt 62 | rrGoldenBt().run() 63 | 64 | def getHistoricData(self, stock): 65 | df = pd.DataFrame(historicData.select().where(historicData.stock == stock).dicts()) 66 | df.drop('timestamp', inplace=True, axis=1) 67 | df.drop('id', inplace=True, axis=1) 68 | df.drop('stock', inplace=True, axis=1) 69 | df['date'] = pd.to_datetime(df['date']) 70 | df.set_index('date', drop=True, inplace=True) 71 | return df 72 | 73 | def downloadStockData(self): 74 | stocks = self.db.getStocks() 75 | historicData.drop_table(True) 76 | historicData.create_table() 77 | SQLITE_MAX_VARIABLE_NUMBER = self.max_sql_variables() 78 | for index, stock in tqdm(stocks.iterrows(), desc=" Getting Historic Data", unit="Stock", ascii=False, ncols=120, leave=False): 79 | try: 80 | yfstock = yf.Ticker(stock['ticker']) 81 | df = yfstock.history(period=self.timeframe) 82 | df['stock'] = stock['ticker'] 83 | df['date'] = df.index 84 | df.rename(columns={'stock': 'stock', 'Open': 'open', 'High': 'high', 'Low': 'low', 'Close': 'close', 85 | 'Volume': 'volume', 'Dividends': 'dividends', 'Stock Splits': 'stocksplits', 'Date': 'date'}, inplace=True) 86 | page = int((len(df)*len(df.columns)*1.5)) 87 | size = int(page // SQLITE_MAX_VARIABLE_NUMBER) 88 | if size > 0: 89 | increment = int(len(df)//size) 90 | else: 91 | increment = -1 92 | if size > 0: 93 | for i in range(0, len(df), increment): 94 | # print("i:"+str(i)+", i+increment"+str(i+increment)) 95 | historicData.insert_many(df.to_dict(orient='records')[ 96 | i:i+increment]).execute() 97 | else: 98 | historicData.insert_many(df.to_dict(orient='records')).execute() 99 | 100 | except Exception as e: 101 | self.log.logger.warning("Problem downloading data") 102 | self.log.logger.warning(e) 103 | 104 | def max_sql_variables(self): 105 | low, high = 0, 100000 106 | try: 107 | try: 108 | import pysqlite3 as sqlite3 109 | except Exception as e: 110 | self.log.logger.warning("Unable to load pysqlite3 will try with sqlite3") 111 | self.log.logger.warning(e) 112 | import sqlite3 113 | db = sqlite3.connect(':memory:') 114 | cur = db.cursor() 115 | cur.execute('CREATE TABLE t (test)') 116 | 117 | while (high - 1) > low: 118 | guess = (high + low) // 2 119 | query = 'INSERT INTO t VALUES ' + ','.join(['(?)' for _ in 120 | range(guess)]) 121 | args = [str(i) for i in range(guess)] 122 | try: 123 | cur.execute(query, args) 124 | except sqlite3.OperationalError as e: 125 | if "too many SQL variables" in str(e): 126 | high = guess 127 | else: 128 | raise 129 | else: 130 | low = guess 131 | cur.close() 132 | db.close() 133 | return low 134 | except Exception as e: 135 | self.log.logger.warning( 136 | "Unable to load SQLite3 library binary, can't download backtrade to SQLite3") 137 | self.log.logger.warning(e) 138 | return 512 139 | 140 | 141 | class historicData(pw.Model): 142 | stock = pw.CharField(null=True) 143 | timestamp = pw.DateTimeField(null=True, default=datetime.datetime.now()) 144 | date = pw.DateField(null=True) 145 | open = pw.FloatField(null=True) 146 | high = pw.FloatField(null=True) 147 | low = pw.FloatField(null=True) 148 | close = pw.FloatField(null=True) 149 | volume = pw.FloatField(null=True) 150 | dividends = pw.FloatField(null=True) 151 | stocksplits = pw.FloatField(null=True) 152 | 153 | class Meta: 154 | database = db 155 | db_table = "historicData" 156 | -------------------------------------------------------------------------------- /rrlib/rrDFPublic.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on 05 04 2021 5 | robotRay server v1.0 6 | @author: camilorojas 7 | 8 | Data Fetcher Public will request the information from the following datasources 9 | Stock Data - finvizfinance library 10 | Intraday Stock Data - finvizfinance library 11 | Option Data - Yahoo Finance, scrapping with BS4 12 | 13 | """ 14 | 15 | import sys 16 | import os 17 | from bs4 import BeautifulSoup as bs 18 | import urllib 19 | from urllib.error import URLError, HTTPError 20 | import pandas as pd 21 | from finvizfinance.quote import finvizfinance 22 | import yfinance as yf 23 | 24 | 25 | class StockDFPublic(): 26 | 27 | def __init__(self, symbol): 28 | sys.path.append(os.path.join(os.path.dirname(__file__), '..')) 29 | from rrlib.rrLogger import logger 30 | self.symbol = symbol 31 | self.log = logger() 32 | self.log.logger.debug(" Init Stock Public Data Fetcher "+str(symbol)) 33 | # timeout import 34 | import configparser 35 | config = configparser.ConfigParser() 36 | config.read("rrlib/robotRay.ini") 37 | self.timeout = int(config['urlfetcher']['Timeout']) 38 | 39 | def getData(self): 40 | self.log.logger.debug(" About to retreive "+self.symbol) 41 | stock = finvizfinance(self.symbol) 42 | self.log.logger.debug(" For: "+self.symbol+" data:"+str(stock.TickerFundament())) 43 | df = pd.DataFrame(stock.TickerFundament().items(), columns=['key', 'value']) 44 | pd.set_option("display.max_rows", None, "display.max_columns", None) 45 | self.log.logger.debug(" Values loaded: \n"+str(df)) 46 | self.log.logger.debug( 47 | " DONE - Stock Public Data Fetcher "+str(self.symbol)) 48 | return df 49 | 50 | def getIntradayData(self): 51 | self.log.logger.debug(" About to retreive "+self.symbol) 52 | stock = finvizfinance(self.symbol) 53 | self.log.logger.debug(" For: "+self.symbol+" data:"+str(stock.TickerFundament())) 54 | df = pd.DataFrame() 55 | # df = pd.DataFrame(columns=['stock', 'price', '%Change', '%Volume']) 56 | df = df.append({'stock': self.symbol, 'price': stock.TickerFundament().get('Price'), 57 | '%Change': float(stock.TickerFundament().get('Change').strip('%'))/100, 58 | '%Volume': 59 | float(stock.TickerFundament().get('Rel Volume'))}, ignore_index=True) 60 | self.log.logger.debug(" Values loaded: \n"+str(df)) 61 | self.log.logger.debug( 62 | " DONE - Stock Intraday Public Data Fetcher "+str(self.symbol)) 63 | return df 64 | 65 | 66 | class OptionDFPublic(): 67 | 68 | def __init__(self, symbol): 69 | sys.path.append(os.path.join(os.path.dirname(__file__), '..')) 70 | from rrlib.rrLogger import logger 71 | self.symbol = symbol 72 | self.log = logger() 73 | self.log.logger.debug(" Init Option Public Data Fetcher for "+symbol) 74 | # timeout import 75 | import configparser 76 | config = configparser.ConfigParser() 77 | config.read("rrlib/robotRay.ini") 78 | self.timeout = int(config['urlfetcher']['Timeout']) 79 | 80 | def getExpirations(self): 81 | stock = yf.Ticker(self.symbol) 82 | return stock.options 83 | 84 | def getStrikes(self): 85 | stock = yf.Ticker(self.symbol) 86 | try: 87 | opt = stock.option_chain(stock.options[6]) 88 | except Exception: 89 | opt = stock.option_chain(stock.options[2]) 90 | return opt.puts.strike 91 | 92 | # Strike int, month is int and the number of months after today 93 | 94 | def getData(self, month, strike): 95 | # https://finance.yahoo.com/quote/WDAY200117P00160000 96 | # Get the put value for specified month 3-8 97 | from rrlib.rrOptions import OptionManager 98 | month = int(month) 99 | df = pd.DataFrame(columns=['key', 'value']) 100 | i = 0 101 | if (0 <= month <= 8): 102 | try: 103 | putURL = OptionManager.getPutFormater( 104 | self.symbol, month, strike) 105 | # print(putURL) 106 | url = "http://finance.yahoo.com/quote/"+putURL+"?p="+putURL 107 | self.log.logger.debug(" URL \n"+str(url)) 108 | req = urllib.request.Request(url) 109 | req.add_header( 110 | "User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36" 111 | ) 112 | sauce = urllib.request.urlopen(req, timeout=self.timeout).read() 113 | except HTTPError as e: 114 | if e.code == 404: 115 | soup = bs(e.fp.read()) 116 | print(soup.prettify()) 117 | self.log.logger.error( 118 | " HTTP Error= "+str(e.code)+" for stock "+self.symbol) 119 | return df 120 | except URLError as e: 121 | self.log.logger.error( 122 | " URL Error= "+str(e.code)+" for stock "+self.symbol) 123 | return df 124 | else: 125 | soup = bs(sauce, 'html.parser') 126 | data = soup.findAll( 127 | "td", {"class": "Ta(end) Fw(600) Lh(14px)"}) 128 | self.log.logger.debug(str(data)) 129 | for tableData in soup.findAll("td", {"class": "C($primaryColor) W(51%)"}): 130 | df = df.append( 131 | {'key': tableData.span.text}, ignore_index=True) 132 | try: 133 | if data[i].span.text != "N/A": 134 | df.at[i, 'value'] = data[i].span.text 135 | else: 136 | df.at[i, 'value'] = '0' 137 | except Exception: 138 | if data[i].text != "N/A": 139 | df.at[i, 'value'] = data[i].text 140 | else: 141 | df.at[i, 'value'] = '0' 142 | else: 143 | if data[i].text != "N/A": 144 | df.at[i, 'value'] = data[i].text 145 | else: 146 | df.at[i, 'value'] = '0' 147 | i = i+1 148 | if len(df) > 0: 149 | price = soup.find( 150 | "span", {"class": "Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)"}) 151 | self.log.logger.debug( 152 | " Done public pricing loaded: \n"+str(price.text)) 153 | df = df.append( 154 | {'key': 'price', 'value': price.text}, ignore_index=True) 155 | self.log.logger.debug(" Done Option loaded: \n"+str(df)) 156 | self.log.logger.debug( 157 | " Getting Public Option loaded: "+self.symbol+" for month "+str(month)) 158 | return df 159 | else: 160 | self.log.logger.error( 161 | " Month outside or range, allowed 3-8 months") 162 | return df 163 | -------------------------------------------------------------------------------- /rrlib/rrServer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on 07 05 2019 5 | robotRay server v1.0 6 | @author: camilorojas 7 | 8 | RobotRay main server to coordinate main thread execution and services 9 | 10 | """ 11 | 12 | import threading 13 | import signal 14 | import schedule 15 | import time 16 | import sys 17 | import os 18 | 19 | 20 | class server(): 21 | def __init__(self, *args, **kwargs): 22 | self.log = logger() 23 | self.intro() 24 | # Handle Ctrl - C 25 | 26 | def SigIntHand(SIG, FRM): 27 | self.log.logger.info( 28 | "To close wait for prompt and enter quit or exit. Ctrl-C does not exit") 29 | 30 | signal.signal(signal.SIGINT, SigIntHand) 31 | self.runCycle = 0 32 | self.threads = [] 33 | self.running = True 34 | self.log.logger.info("Initialization finished robotRay server") 35 | 36 | def intro(self): 37 | self.log.logger.info("") 38 | self.log.logger.info("-"*64) 39 | self.log.logger.info(" ____ __ __ ____ ") 40 | self.log.logger.info(" / __ \ ____ / /_ ____ / /_ / __ \ ____ _ __ __") 41 | self.log.logger.info(" / /_/ // __ \ / __ \ / __ \ / __// /_/ // __ `// / / /") 42 | self.log.logger.info(" / _, _// /_/ // /_/ // /_/ // /_ / _, _// /_/ // /_/ / ") 43 | self.log.logger.info("/_/ |_| \____//_.___/ \____/ \__//_/ |_| \__,_/ \__, / ") 44 | self.log.logger.info(" /____/ ") 45 | self.log.logger.info("robotRay v1.0 - by Camilo Rojas - Jun 8 2019") 46 | self.log.logger.info( 47 | "Copyright Camilo Rojas - camilo.rojas@gmail.com") 48 | self.log.logger.info("-"*64) 49 | self.log.logger.info("") 50 | 51 | def startup(self): 52 | self.log.logger.info("-- Startup robotRay server") 53 | # starting common services 54 | # find .ini db filename 55 | import configparser 56 | config = configparser.ConfigParser() 57 | config.read("rrlib/robotRay.ini") 58 | self.log.logger.info( 59 | "01. Building db elegible stocks ") 60 | self.db = rrDbManager() 61 | self.db.startServerRun() 62 | self.db.initializeStocks() 63 | self.log.logger.info( 64 | "01. DONE - Building db elegible stocks for strategies") 65 | self.log.logger.info("02. Setting dates for options") 66 | self.db.initializeExpirationDate() 67 | self.log.logger.info( 68 | "02. DONE - Setting dates for options") 69 | self.log.logger.info("03. Controller startup sequence") 70 | self.controller = rrController() 71 | self.log.logger.info("03. DONE - Controller startup sequence") 72 | self.log.logger.info("04. Scheduling daily scanners") 73 | self.stockdatainterval = int(config.get('scheduler', 'stockdatainterval')) 74 | self.stockintrainterval = int(config.get('scheduler', 'stockintrainterval')) 75 | self.stockoptioninverval = int(config.get('scheduler', 'stockoptioninverval')) 76 | self.dailyreport = config.get('scheduler', 'dailyreport') 77 | self.dailyscan = config.get('scheduler', 'dailyscan') 78 | self.goldenTime = config.get('scheduler', 'goldenTime') 79 | self.scheduler() 80 | self.log.logger.info("04. DONE - Scheduling daily scanners") 81 | self.startbot = config.get('telegram', 'startbot') 82 | if (self.startbot == "Yes"): 83 | self.log.logger.info("05. Starting Telegram bot") 84 | self.bot = rrTelegram() 85 | self.db.updateServerRun(telegramBotEnabled="Yes") 86 | self.log.logger.info("05. DONE - Starting Telegram bot") 87 | self.log.logger.info("06. Starting strategies") 88 | self.sellp = rrPutSellStrategy() 89 | self.log.logger.info("06. DONE - Starting strategies") 90 | self.faststart = config.get('debug', 'faststart') 91 | if(self.faststart == "No"): 92 | self.log.logger.info("10. Initial Stock Data and Intraday fetch") 93 | self.db.getStockData() 94 | self.db.getIntradayData() 95 | self.log.logger.info("10. DONE - Initial Stock Data and Intraday fetch") 96 | self.log.logger.info( 97 | "-- Finished Startup robotRay server. Starting schedule.") 98 | self.log.logger.info("") 99 | 100 | def scheduler(self): 101 | schedule.every(self.stockdatainterval).hours.do( 102 | self.run_threaded, self.controller.getStockData) 103 | schedule.every(self.stockintrainterval).minutes.do( 104 | self.run_threaded, self.controller.getIntradayData) 105 | schedule.every(self.stockoptioninverval).minutes.do( 106 | self.run_threaded, self.controller.getOptionData) 107 | schedule.every().day.at(self.dailyreport).do( 108 | self.run_threaded, self.controller.sendReport) 109 | schedule.every().day.at(self.dailyscan).do( 110 | self.run_threaded, self.controller.dailyScan) 111 | schedule.every().day.at(self.goldenTime).do( 112 | self.run_threaded, self.controller.goldenstrategy) 113 | 114 | def runServer(self): 115 | self.run_threaded(self.runScheduler) 116 | if (self.startbot == "Yes"): 117 | self.run_threaded(self.bot.startbot) 118 | while True: 119 | try: 120 | if not sys.stdin.isatty(): 121 | command = "" 122 | time.sleep(10) 123 | else: 124 | command = input("> ") 125 | response = self.controller.consolecommand(command) 126 | if len(response) > 0: 127 | for message in response[1:]: 128 | self.log.logger.info(message) 129 | if response[0] != "": 130 | if response[0].startswith("db."): 131 | func = getattr(self.db, response[0].split("db.", 1)[1]) 132 | if response[0].split("db.", 1)[1].startswith("print"): 133 | print(func()) 134 | else: 135 | func() 136 | elif response[0].startswith("sellp."): 137 | func = getattr(self.sellp, response[0].split("sellp.", 1)[1]) 138 | if response[0].split("sellp.", 1)[1].startswith("print"): 139 | print(func()) 140 | else: 141 | func() 142 | else: 143 | func = getattr(self, response[0]) 144 | func() 145 | except KeyboardInterrupt: 146 | self.running = False 147 | self.shutdown() 148 | break 149 | 150 | def runScheduler(self): 151 | while self.running: 152 | schedule.run_pending() 153 | time.sleep(1) 154 | 155 | def run_threaded(self, job_func): 156 | job_thread = threading.Thread(target=job_func) 157 | job_thread.daemon = True 158 | job_thread.start() 159 | self.threads.append(job_thread) 160 | 161 | def shutdown(self): 162 | self.log.logger.info("999. - Shutdown initiated") 163 | self.log.logger.info("999. - Shutdown completed") 164 | sys.exit() 165 | 166 | # Exit signal management from server handler 167 | 168 | 169 | def exit_gracefully(signum, frame): 170 | signal.signal(signal.SIGINT, original_sigint) 171 | try: 172 | if input("\n998. - Really quit? (y/n)>").lower().startswith('y'): 173 | sys.exit() 174 | 175 | except KeyboardInterrupt: 176 | print("\n998. - Ok, quitting robotRay server") 177 | sys.exit() 178 | 179 | 180 | # main server run procedure 181 | if __name__ == '__main__': 182 | while True: 183 | original_sigint = signal.getsignal(signal.SIGINT) 184 | signal.signal(signal.SIGINT, exit_gracefully) 185 | sys.path.append(os.path.join(os.path.dirname(__file__), '..')) 186 | from rrlib.rrLogger import logger 187 | from rrlib.rrDb import rrDbManager 188 | from rrlib.rrTelegram import rrTelegram 189 | from rrlib.rrPutSellStrategy import rrPutSellStrategy 190 | from rrlib.rrController import rrController 191 | try: 192 | mainserver = server() 193 | mainserver.startup() 194 | mainserver.runServer() 195 | except KeyboardInterrupt: 196 | exit_gracefully(signal.SIGINT, exit_gracefully) 197 | -------------------------------------------------------------------------------- /rrlib/rrPortfolio.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on 07 04 2021 5 | robotRay server v1.0 6 | @author: camilorojas 7 | 8 | Portfolio classes 9 | 10 | Process for module 11 | 1. if source is ib then get portfolio total from ib 12 | 2. if source is public then get portfolio total from .ini file 13 | 3. class lifecycle methods 14 | 15 | """ 16 | import pandas as pd 17 | 18 | 19 | class rrPortfolio: 20 | def __init__(self): 21 | # Starting common services 22 | from rrlib.rrLogger import logger, TqdmToLogger 23 | # Get logging service 24 | self.log = logger() 25 | self.tqdm_out = TqdmToLogger(self.log.logger) 26 | self.log.logger.debug(" Backtrader starting. ") 27 | # starting ini parameters 28 | import configparser 29 | import math 30 | config = configparser.ConfigParser() 31 | config.read("rrlib/robotRay.ini") 32 | # db filename to confirm it exists 33 | self.source = config.get('datasource', 'source') 34 | if self.source == "ib": 35 | self.funds = str(self.getAvailableFunds()) 36 | else: 37 | self.funds = config.get('portfolio', 'funds') 38 | if self.source == "ib": 39 | self.R = str(int(math.ceil(self.getAvailableFunds()*0.005 / 100.0)) * 100) 40 | else: 41 | self.R = config.get('portfolio', 'R') 42 | self.monthlyPremium = config.get('portfolio', 'monthlyPremium') 43 | if self.source == "ib": 44 | self.BP = float(self.getBuyingPower()) 45 | else: 46 | self.BP = config.get('portfolio', 'BP') 47 | # Get datsource from pubic or ib 48 | 49 | def switchSource(self, source): 50 | import configparser 51 | import math 52 | config = configparser.ConfigParser() 53 | if source == "ib": 54 | self.source = "ib" 55 | self.funds = str(self.getAvailableFunds()) 56 | self.BP = float(self.getBuyingPower()) 57 | self.R = str(int(math.ceil(self.getAvailableFunds()*0.005 / 100.0)) * 100) 58 | self.log.logger.info( 59 | " Portfolio switching from Public to Interactive Brokers") 60 | elif source == "public": 61 | self.source = "public" 62 | self.funds = config.get('portfolio', 'funds') 63 | self.R = config.get('portfolio', 'R') 64 | self.BP = config.get('portfolio', 'BP') 65 | self.log.logger.info( 66 | " Portfolio switching from Interactive Brokers to Public") 67 | else: 68 | self.source = "public" 69 | self.funds = config.get('portfolio', 'funds') 70 | self.R = config.get('portfolio', 'R') 71 | self.BP = config.get('portfolio', 'BP') 72 | self.log.warning( 73 | " Portfolio switching allows ib for Interactive Brokers or Public for finviz / yahoo, public by default") 74 | 75 | def getPositions(self): 76 | df = pd.DataFrame() 77 | if self.source == "ib": 78 | from rrlib.rrDFIB import IBConnection 79 | self.ib = IBConnection() 80 | self.log.logger.debug(" About to retreive Portfolio") 81 | if not self.ib.isConnected(): 82 | self.ib.connect() 83 | pos = self.ib.getPositions() 84 | df = pd.DataFrame(pos) 85 | df['symbol'] = "" 86 | pd.options.mode.chained_assignment = None # default='warn' 87 | for i in range(len(df)): 88 | df['symbol'][i] = pos[i][1].symbol 89 | df.drop('contract', inplace=True, axis=1) 90 | else: 91 | # get Db positions 92 | pass 93 | return df 94 | 95 | def getAccount(self): 96 | if self.source == "ib": 97 | from rrlib.rrDFIB import IBConnection 98 | self.ib = IBConnection() 99 | self.log.logger.debug(" About to retreive Portfolio") 100 | if not self.ib.isConnected(): 101 | self.ib.connect() 102 | # AvailableFunds, BuyingPower, TotalCashValue, NetLiquidation, ExcessLiquidity, 103 | # FullInitMarginReq 104 | # StockMarketValue, OptionMarketValue, UnrealizedPnL, RealizedPnL 105 | acct = pd.DataFrame(self.ib.ib.accountSummary()) 106 | df = pd.DataFrame({"key": ["AvailableFunds", "BuyingPower", "TotalCashValue", "NetLiquidation", "ExcessLiquidity", "FullInitMarginReq", "StockMarketValue", "OptionMarketValue", "UnrealizedPnL", "RealizedPnL"], 107 | "value": [acct[acct.tag == "AvailableFunds"].value.item(), acct[acct.tag == "BuyingPower"].value.item(), acct[acct.tag == "TotalCashValue"].value.item(), acct[acct.tag == "NetLiquidation"].value.item(), acct[acct.tag == "ExcessLiquidity"].value.item(), acct[acct.tag == "FullInitMarginReq"].value.item(), acct.loc[(acct['account'] == 'All') & ( 108 | acct["tag"] == "StockMarketValue"), 'value'].values[0], acct.loc[(acct['account'] == 'All') & ( 109 | acct["tag"] == "OptionMarketValue"), 'value'].values[0], acct.loc[(acct['account'] == 'All') & ( 110 | acct["tag"] == "UnrealizedPnL"), 'value'].values[0], acct.loc[(acct['account'] == 'All') & ( 111 | acct["tag"] == "RealizedPnL"), 'value'].values[0]]}) 112 | else: 113 | # get account info public 114 | pass 115 | return df 116 | 117 | def getBuyingPower(self): 118 | if self.source == "ib": 119 | # get 120 | df = self.getAccount() 121 | buyingPower = float(df[df['key'] == 'BuyingPower'].value) 122 | else: 123 | # get trades info public 124 | pass 125 | return buyingPower 126 | 127 | def getAvailableFunds(self): 128 | if self.source == "ib": 129 | df = self.getAccount() 130 | availableFunds = float(df[df['key'] == 'AvailableFunds'].value) 131 | else: 132 | # get trades info public 133 | pass 134 | return availableFunds 135 | 136 | def getCash(self): 137 | if self.source == "ib": 138 | df = self.getAccount() 139 | cash = float(df[df['key'] == 'TotalCashValue'].value) 140 | else: 141 | # get trades info public 142 | pass 143 | return cash 144 | 145 | def getUnrealizedPNL(self): 146 | if self.source == "ib": 147 | df = self.getAccount() 148 | unrpnl = float(df[df['key'] == 'UnrealizedPnL'].value) 149 | else: 150 | # get trades info public 151 | pass 152 | return unrpnl 153 | 154 | def getRealizedPNL(self): 155 | if self.source == "ib": 156 | df = self.getAccount() 157 | rpnl = float(df[df['key'] == 'RealizedPnL'].value) 158 | else: 159 | # get trades info public 160 | pass 161 | return rpnl 162 | 163 | def getTrades(self): 164 | if self.source == "ib": 165 | from rrlib.rrDFIB import IBConnection 166 | self.ib = IBConnection() 167 | self.log.logger.debug(" About to retreive trades") 168 | if not self.ib.isConnected(): 169 | self.ib.connect() 170 | trades = pd.DataFrame(self.ib.ib.trades()) 171 | df = trades 172 | else: 173 | # get trades info public 174 | pass 175 | return df 176 | 177 | def getOpenTrades(self): 178 | if self.source == "ib": 179 | from rrlib.rrDFIB import IBConnection 180 | self.ib = IBConnection() 181 | self.log.logger.debug(" About to retreive open trades") 182 | if not self.ib.isConnected(): 183 | self.ib.connect() 184 | trades = pd.DataFrame(self.ib.ib.openTrades()) 185 | df = trades 186 | else: 187 | # get trades info public 188 | pass 189 | return df 190 | 191 | def getOpenOrders(self): 192 | if self.source == "ib": 193 | from rrlib.rrDFIB import IBConnection 194 | self.ib = IBConnection() 195 | self.log.logger.debug(" About to retreive open orders") 196 | if not self.ib.isConnected(): 197 | self.ib.connect() 198 | trades = pd.DataFrame(self.ib.ib.openOrders()) 199 | df = trades 200 | else: 201 | # get trades info public 202 | pass 203 | return df 204 | 205 | def getOrders(self): 206 | if self.source == "ib": 207 | from rrlib.rrDFIB import IBConnection 208 | self.ib = IBConnection() 209 | self.log.logger.debug(" About to retreive open orders") 210 | if not self.ib.isConnected(): 211 | self.ib.connect() 212 | trades = pd.DataFrame(self.ib.ib.orders()) 213 | df = trades 214 | else: 215 | # get trades info public 216 | pass 217 | return df 218 | -------------------------------------------------------------------------------- /rrlib/rrDFIB.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on 05 04 2021 5 | robotRay server v1.0 6 | @author: camilorojas 7 | 8 | Data Fetcher Interactive Brokers will request the information from the following datasources 9 | Stock Data - IB library 10 | Intraday Stock Data - IB library 11 | Option Data - IB library 12 | 13 | Pending implementation 14 | 15 | getdata return pd[ 16 | 9 - performance week text with % at the end 17 | 15 - perfromance month text with % at the end 18 | 20 - shortFloat text % final 19 | 21 - performance quarter text with % at the end 20 | 26 - short ratio text 21 | 27 - performance half year text % final 22 | 31 - target price 23 | 32 - performance year text % final - TTM_over_TTM 24 | 36 - roe text 25 | 38 - perf ytd text % final 26 | 42 - roi text - TTMROIPCT 27 | 43 - w52 high % final text - NHIG precio mayor 28 | 44 - beta text 29 | 47 - sales 5 year growth text with % at the end - REVTRENDGR 5 años 30 | 49 - w52 low % final text - NLOW precio menor 31 | 53 - sales quarter after quarter text with % at the end - REVCHNGYR 1 año 32 | 61 - relative volume text 33 | 62 - previous close text 34 | 65 - earnings date text Apr 28 AMC 35 | 68 - price text - NPRICE 36 | 69 - recomendation analyst(1 sell 5 buy) 37 | 70 - sma 20 text % final 38 | 71 - sma 50 text % final 39 | 72 - sma 200 text % final 40 | 74 - performance day text % final 41 | ] 42 | 43 | getIntradayData retrun pd [ 44 | 'stock': 'symbol', 45 | 'price': 'Price', 46 | '%Change': 'Change price', 47 | '%Volume': 'rel volume' 48 | ] 49 | 50 | getoptiondata return pd [ 51 | 1 - open price 52 | 2 - bid 53 | 3 - ask 54 | 5 - expiration date 55 | 6 - day range 56 | 8 - volume 57 | 9 - open interest 58 | 10 - price 59 | ] 60 | 61 | """ 62 | 63 | import sys 64 | import os 65 | import pandas as pd 66 | from ib_insync import * 67 | 68 | 69 | class StockDFIB(): 70 | 71 | def __init__(self, symbol): 72 | sys.path.append(os.path.join(os.path.dirname(__file__), '..')) 73 | from rrlib.rrLogger import logger 74 | self.symbol = symbol 75 | self.log = logger() 76 | self.log.logger.debug(" Init Stock IB Data Fetcher "+str(symbol)) 77 | self.ib = IBConnection() 78 | 79 | def getData(self): 80 | from rrlib.rrDFPublic import StockDFPublic as sdfp 81 | self.log.logger.debug(" About to connect to IB for "+self.symbol) 82 | if not self.ib.isConnected(): 83 | self.ib.connect() 84 | self.log.logger.debug(" Connected to IB for "+self.symbol) 85 | stock = Stock(self.symbol, "SMART", "USD") 86 | self.ib.ib.qualifyContracts(stock) 87 | self.ib.ib.reqContractDetails(stock) 88 | bars = self.ib.ib.reqHistoricalData(stock, endDateTime='', durationStr='1 D', barSizeSetting='1 day', whatToShow='TRADES', 89 | useRTH=True, formatDate=1, keepUpToDate=False) 90 | df = util.df(bars) 91 | self.log.logger.debug(" Fetched data from IB for "+self.symbol) 92 | self.log.logger.debug(" Data: "+str(df)) 93 | df = pd.DataFrame(columns=['key', 'value']) 94 | df = sdfp(self.symbol).getData() 95 | pd.set_option("display.max_rows", None, "display.max_columns", None) 96 | self.log.logger.debug(" Values loaded: \n"+str(df)) 97 | self.log.logger.debug( 98 | " DONE - Interactive Brokers Data Fetcher "+str(self.symbol)) 99 | return df 100 | 101 | def getIntradayData(self): 102 | self.log.logger.debug(" About to retreive "+self.symbol) 103 | if not self.ib.isConnected(): 104 | self.ib.connect() 105 | self.log.logger.debug(" Connected to IB for "+self.symbol) 106 | stock = Stock(self.symbol, "SMART", "USD") 107 | self.ib.ib.reqContractDetails(stock) 108 | data = self.ib.ib.reqMktData(stock) 109 | bars = self.ib.ib.reqHistoricalData(stock, endDateTime='', durationStr='2 D', barSizeSetting='1 day', whatToShow='TRADES', 110 | useRTH=True, formatDate=1, keepUpToDate=False) 111 | dfBar = util.df(bars) 112 | self.ib.ib.sleep(1) 113 | pchg = round(((float(data.marketPrice()) - 114 | float(dfBar[:-1].close))/float(dfBar[:-1].close)*100), 2) 115 | volchg = round(data.volume/float(dfBar[:-1].volume), 2) 116 | df = pd.DataFrame() 117 | df = df.append({'stock': self.symbol, 'price': str(data.marketPrice()), 118 | '%Change': str(pchg), '%Volume': str(volchg)}, ignore_index=True) 119 | self.log.logger.debug(" Values loaded: \n"+str(df)) 120 | self.log.logger.debug( 121 | " DONE - Stock Intraday Public Data Fetcher "+str(self.symbol)) 122 | return df 123 | 124 | 125 | class OptionDFIB(): 126 | 127 | def __init__(self, symbol): 128 | sys.path.append(os.path.join(os.path.dirname(__file__), '..')) 129 | from rrlib.rrLogger import logger 130 | self.symbol = symbol 131 | self.log = logger() 132 | self.log.logger.debug(" Init Option IB Data Fetcher for "+symbol) 133 | # Define IB Connection 134 | self.ib = IBConnection() 135 | 136 | # Strike int, month is int and the number of months after today 137 | def getData(self, month, strike): 138 | # https://finance.yahoo.com/quote/WDAY200117P00160000 139 | # Get the put value for specified month 3-8 140 | """ 141 | getoptiondata return pd [ 142 | 1 - open price 143 | 2 - bid 144 | 3 - ask 145 | 5 - expiration date 146 | 6 - day range 147 | 8 - volume 148 | 9 - open interest 149 | 10 - price 150 | ] 151 | 152 | """ 153 | from rrlib.rrOptions import OptionManager 154 | if not self.ib.isConnected(): 155 | self.ib.connect() 156 | month = int(month) 157 | df = pd.DataFrame(columns=['key', 'value']) 158 | if (3 <= month <= 8): 159 | # get option data 160 | self.log.logger.debug(" Done Option loaded: \n"+str(df)) 161 | self.log.logger.debug( 162 | " Getting Public Option loaded: "+self.symbol+" for month "+str(month)) 163 | date = OptionManager.getDatebyMonth(month) 164 | option = Option(self.symbol, date.replace('-', ''), 165 | int(strike), 'P', 'SMART', multiplier=100) 166 | pd.set_option("display.max_rows", None, "display.max_columns", None) 167 | # self.ib.ib.qualifyContracts(option) 168 | data = self.ib.ib.reqMktData(option) 169 | self.ib.ib.sleep(1) 170 | df = df.append({'key': 'Previous Close', 'value': data.last}, ignore_index=True) 171 | df = df.append({'key': 'Open', 'value': data.last}, ignore_index=True) 172 | df = df.append({'key': 'Bid', 'value': data.bid}, ignore_index=True) 173 | df = df.append({'key': 'Ask', 'value': data.ask}, ignore_index=True) 174 | df = df.append({'key': 'Strike', 'value': strike}, ignore_index=True) 175 | df = df.append( 176 | {'key': 'Expire Date', 'value': date}, ignore_index=True) 177 | df = df.append( 178 | {'key': 'Day\'s Range', 'value': str(data.high)+" - "+str(data.low)}, ignore_index=True) 179 | df = df.append({'key': 'Contract Range', 'value': 0}, ignore_index=True) 180 | df = df.append({'key': 'Volume', 'value': data.volume}, ignore_index=True) 181 | df = df.append({'key': 'Open Interest', 'value': "NA"}, ignore_index=True) 182 | df = df.append({'key': 'price', 'value': data.last}, ignore_index=True) 183 | return df 184 | else: 185 | self.log.logger.error( 186 | " Month outside or range, allowed 3-8 months") 187 | return df 188 | 189 | 190 | class Singleton(type): 191 | _instances = {} 192 | 193 | def __call__(cls, *args, **kwargs): 194 | if cls not in cls._instances: 195 | cls._instances[cls] = super( 196 | Singleton, cls).__call__(*args, **kwargs) 197 | # else: 198 | # cls._instances[cls].__init__(*args, **kwargs) 199 | return cls._instances[cls] 200 | 201 | 202 | class IBConnection(metaclass=Singleton): 203 | def __init__(self): 204 | sys.path.append(os.path.join(os.path.dirname(__file__), '..')) 205 | from rrlib.rrLogger import logger 206 | self.log = logger() 207 | # ib parameter import 208 | import configparser 209 | config = configparser.ConfigParser() 210 | config.read("rrlib/robotRay.ini") 211 | self.ib_ip = config['ib']['ip'] 212 | self.ib_port = int(config['ib']['port']) 213 | self.ib = IB() 214 | 215 | def onError(self, reqId, errorCode, errorString, contract): 216 | msg = str(reqId)+" " + str(errorCode)+" " + errorString 217 | if contract: 218 | symbol = contract.localSymbol 219 | msg += " "+symbol 220 | if errorCode == 200 and errorString == 'No security definition has been found for the request': 221 | msg += " - Bad contract" 222 | elif errorCode == 1102: 223 | msg += " - Restarting after outage" 224 | self.connect() 225 | 226 | self.log.logger.info(" IB message:"+msg) 227 | 228 | def connect(self): 229 | import random 230 | self.ib.errorEvent += self.onError 231 | self.ib.connect(self.ib_ip, self.ib_port, 232 | clientId=str(int(random.random()*100))) 233 | 234 | def disconnect(self): 235 | self.ib.disconnect() 236 | 237 | def isConnected(self): 238 | return self.ib.isConnected() 239 | 240 | def getPositions(self): 241 | return [pos for pos in self.ib.positions()] 242 | -------------------------------------------------------------------------------- /rrlib/rrDailyScan.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on 07 04 2021 5 | robotRay server v1.0 6 | @author: camilorojas 7 | 8 | Daily Scan classes 9 | 10 | Process for module 11 | Daily download of the data sources, analyze with technical analysis all 12 | signals that are present in the last 5 days and prepare a report to inform the user 13 | 14 | """ 15 | 16 | import pandas as pd 17 | import numpy as np 18 | import os 19 | import sys 20 | import talib 21 | from rrlib.rrBacktrader import historicData, rrBacktrader 22 | 23 | 24 | class rrDailyScan: 25 | def __init__(self): 26 | # Starting common services 27 | from rrlib.rrLogger import logger, TqdmToLogger 28 | from rrlib.rrDb import rrDbManager 29 | # Get logging service 30 | self.db = rrDbManager() 31 | self.log = logger() 32 | self.tqdm_out = TqdmToLogger(self.log.logger) 33 | self.log.logger.debug(" Daily scanner starting. ") 34 | # starting ini parameters 35 | import configparser 36 | config = configparser.ConfigParser() 37 | config.read("rrlib/robotRay.ini") 38 | # set patterns for daily detection 39 | self.patterns = pd.DataFrame(np.array([ 40 | # ['CDL2CROWS', 'Two Crows', 'Low reversal w conf', '5.7 % ', '35.2 %'], 41 | ['CDL3BLACKCROWS', '* Three Black Crows *', 'High R2BE', '-0.144', '0.286'], 42 | ['CDL3INSIDE', 'Three Inside Up/Down', 'Medium Reversal', '0.062', '0.354'], 43 | ['CDL3LINESTRIKE', '* Three Line Strike *', 'High R2BU', '0.108', '0.369'], 44 | # ['CDL3OUTSIDE', 'Three Outside Up/Down', 'Medium Reversal', '0.051', '0.35'], 45 | ['CDL3STARSINSOUTH', 'Three Stars In The South', 'Rare Medium R2BU w conf', '0.20', '0.40'], 46 | ['CDL3WHITESOLDIERS', 47 | '* Three Advancing White Soldiers *', 'High R2BU', '-0.001', '0.333'], 48 | ['CDLABANDONEDBABY', '* Abandoned Baby *', 'High reversal', '-0.046)', '0.318'], 49 | ['CDLADVANCEBLOCK', 'Advance Block', '', '0.142', '0.381'], 50 | # ['CDLBELTHOLD' , 'Belt-hold', '','0.037', '0.346'], [ 51 | ['CDLBREAKAWAY', 'Breakaway', 52 | 'High Over(Sold/bought) 5 day use as conf', '0.109', '0.37'], 53 | ['CDLCLOSINGMARUBOZU', 'Closing Marubozu', 'Rare High confirmation', '-0.047', '0.318'], 54 | ['CDLCONCEALBABYSWALL', '* Concealing Baby Swallow *', 'Medium Rare R2BU', '0.50', '0.50'], 55 | ['CDLCOUNTERATTACK', 'Counterattack', 'Low Reversal w conf', '0', '0'], 56 | ['CDLDARKCLOUDCOVER', 'Dark Cloud Cover', '', '0.061', '0.354'], 57 | # ['CDLDOJI','Doji','','',''], 58 | ['CDLDOJISTAR', 'Doji Star', '', '0.238', '0.413'], 59 | # ['CDLDRAGONFLYDOJI', 'Dragonfly Doji', '', '0.054', '0.351'], 60 | ['CDLENGULFING', 'Engulfing Pattern', 'Low Reversal', '0.104', '0.368'], 61 | ['CDLEVENINGDOJISTAR', 'Evening Doji Star', 'High R2BE', '', ''], 62 | ['CDLEVENINGSTAR', '* Evening Star *', 'Rare High R2BE', '0.006', '0.335'], 63 | # ['CDLGAPSIDESIDEWHITE', 'Up/Down-gap side-by-side white lines', '', '0.013', '0.338'], 64 | ['CDLGRAVESTONEDOJI', 'Gravestone Doji', '', '0.196', '0.399'], 65 | ['CDLHAMMER', 'Hammer', 'Medium R2BU', '0.225', '0.408'], 66 | ['CDLHANGINGMAN', 'Hanging Man', 'Medium R2BE', '0.075', '0.358'], 67 | ['CDLHARAMI', 'Harami Pattern', '', '0.219', '0.406'], 68 | ['CDLHARAMICROSS', 'Harami Cross Pattern', '', '0.207', '0.402'], 69 | ['CDLHIGHWAVE', 'High-Wave Candle', '', '0.263', '0.421'], 70 | ['CDLHIKKAKE', 'Hikkake Pattern', '', '0.11', '0.371'], 71 | ['CDLHIKKAKEMOD', 'Modified Hikkake Pattern', '', '0.14', '0.381'], 72 | ['CDLHOMINGPIGEON', 'Homing Pigeon', '', '0.344', '0.448'], 73 | ['CDLIDENTICAL3CROWS', '* Identical Three Crows *', 'High R2BE', '-0.078', '0.307'], 74 | # ['CDLINNECK', 'In-Neck Pattern', 'Low Continuation', '0.047', '0.349'], 75 | ['CDLINVERTEDHAMMER', 'Inverted Hammer', 'Medium R2BU', '0.182', '0.394'], 76 | # ['CDLKICKING', 'Kicking', '', '-0.11', '0.294'], 77 | # ['CDLKICKINGBYLENGTH','Kicking', 'bull/bear determined by the longer marubozu', '-0.117', '0.294'], 78 | ['CDLLADDERBOTTOM', 'Ladder Bottom', '', '-0.147', '0.382'], 79 | # ['CDLLONGLEGGEDDOJI', 'Long Legged Doji', '', '', ''], 80 | # ['CDLMARUBOZU', 'Marubozu', '', '-0.085', '0.305'], 81 | ['CDLMATCHINGLOW', 'Matching Low', '', '0.261', '0.42'], 82 | # ['CDLMATHOLD', 'Mat Hold', '','-0.40', '0.20'], 83 | ['CDLMORNINGDOJISTAR', 'Morning Doji Star', '', '0', '0'], 84 | ['CDLMORNINGSTAR', 'Morning Star', '', '0.152', '0.384'], 85 | # ['CDLONNECK', 'On-Neck Pattern', '', '0.015', '0.338'], 86 | ['CDLPIERCING', 'Piercing Pattern', '', '0.185', '0.395'], 87 | ['CDLRICKSHAWMAN', 'Rickshaw Man', '', '0.304', '0.435'], 88 | ['CDLRISEFALL3METHODS', 'Rising/Falling Three Methods', '', '0.088', '0.363'], 89 | # ['CDLSEPARATINGLINES', 'Separating Lines', '', '-0.049', '0.317'], 90 | ['CDLSHOOTINGSTAR', 'Shooting Star', '', '0.135', '0.378'], 91 | # ['CDLSHORTLINE', 'Short Line Candle', '', '', ''], 92 | ['CDLSPINNINGTOP', 'Spinning Top', '', '0.271', '0.424'], 93 | # ['CDLSTALLEDPATTERN', 'Stalled Pattern', '', '', ''], 94 | ['CDLSTICKSANDWICH', 'Stick Sandwich', '', '0.273', '0.424'], 95 | # ['CDLTAKURI', 'Takuri (Dragonfly Doji with very long lower shadow)','', '0.038', '0.346'], 96 | ['CDLTASUKIGAP', 'Tasuki Gap', '', '0.17', '0.39'], 97 | # ['CDLTHRUSTING', 'Thrusting Pattern', '', '0.051', '0.35'], 98 | # ['CDLTRISTAR', 'Tristar Pattern', '', '0.032', '0.344'], 99 | ['CDLUNIQUE3RIVER', 'Unique 3 River', '', '0.206', '0.402'], 100 | ['CDLUPSIDEGAP2CROWS', 'Upside Gap Two Crows', '', '0.158', '0.386'], 101 | ['CDLXSIDEGAP3METHODS', 'Upside/Downside Gap Three Methods', '', '0.133', '0.378'] 102 | ]), columns=['cod', 'desc', 'impact', 'roi', 'successrate']) 103 | 104 | def dailyScan(self): 105 | sys.path.append(os.path.join(os.path.dirname(__file__), '..')) 106 | from rrlib.rrBacktrader import rrBacktrader as rrbt 107 | self.bt = rrbt() 108 | stocks = self.db.getStocks() 109 | # for index, stock in tqdm(stocks.iterrows(), desc=" Getting Historic Data", unit="Stock", ascii=False, ncols=120, leave=False): 110 | report = pd.DataFrame(columns=['stock', 'pattern', 'date', 'signal']) 111 | for index, stock in stocks.iterrows(): 112 | try: 113 | hd = self.bt.getHistoricData(stock['ticker']) 114 | for index, cod in self.patterns.iterrows(): 115 | func = getattr(talib, cod['cod']) 116 | result = func(hd['open'], hd['high'], hd['low'], hd['close']) 117 | last = result.tail(3) 118 | for index, entryCode in last.items(): 119 | if entryCode != 0: 120 | if entryCode == 200: 121 | entry = "Bullish with Confirmation" 122 | elif entryCode == 100: 123 | entry = "Bullish" 124 | elif entryCode == -100: 125 | entry = "Bearish" 126 | elif entryCode == -200: 127 | entry = "Bearish with Confirmation" 128 | report = report.append( 129 | {'stock': stock['ticker'], 'pattern': cod['desc'], 'date': index, 'signal': entry, 'impact': cod['impact'], 'roi': cod['roi'], 'successrate': cod['successrate']}, ignore_index=True) 130 | except Exception as e: 131 | self.log.logger.warning("Problem daily scanner") 132 | self.log.logger.warning(e) 133 | report = report.sort_values(['stock', 'date', 'roi'], ascending=(True, True, True)) 134 | return report 135 | 136 | def communicateScan(self): 137 | import datetime 138 | from rrlib.rrTelegram import rrTelegram 139 | from rrlib.rrIFTTT import rrIFTTT 140 | 141 | ds = rrDailyScan().dailyScan() 142 | for index, stock in self.db.getStocks().iterrows(): 143 | stk = str(stock['ticker']) 144 | self.log.logger.info(" Daily Scan for: " + stk) 145 | try: 146 | for index, event in ds[ds.stock == stk].iterrows(): 147 | self.log.logger.info(" event: " + event['date'].strftime("%d/%m")+", Pattern: "+str(event['pattern']) + 148 | ", signal: " + 149 | str(event['signal']) + ", ROI "+str(event['roi'])+", success rate " + str(event['successrate'])+". "+str(event['impact'])) 150 | if(datetime.datetime.now().isoweekday() == 1): 151 | daydelta = 4 152 | elif datetime.datetime.now().isoweekday() == 7: 153 | daydelta = 3 154 | else: 155 | daydelta = 2 156 | if float(event['roi']) > 0.1 and float(event['successrate']) > 0.2 and (datetime.datetime.now()-datetime.timedelta(days=3)) < event['date']: 157 | self.db.updateServerRun(prospectsFound="Yes") 158 | report = {} 159 | report["value1"] = "Daily Scanner: Prospect Found: Stock:"+stk+" event:" + \ 160 | event['date'].strftime("%d/%m")+" Pattern:" + str(event['pattern']) 161 | report["value2"] = "Signal:" + str(event['signal'])+" Entry:" + \ 162 | "" + ", Stop Loss:"+""+", Take Profit:"+"" 163 | report["value3"] = "ROI:" + str(event['roi'])+", Success Rate:" + str( 164 | event['successrate'])+", Impact:"+str(event['impact']) 165 | try: 166 | if(float(event['roi']) > 0.2) and (datetime.datetime.now()-datetime.timedelta(days=daydelta)) < event['date']: 167 | rrIFTTT().send(report) 168 | rrTelegram().sendMessage( 169 | str(report["value1"])+" | "+str(report["value2"])+" | "+str(report["value3"])) 170 | rrTelegram().sendImage("https://charts2.finviz.com/chart.ashx?t="+stk+"&ty=c&ta=1&p=d&s=l") 171 | except Exception as e: 172 | self.log.logger.error( 173 | " Daily scan communications error") 174 | self.log.logger.error(e) 175 | except Exception as e: 176 | self.log.logger.error(e) 177 | -------------------------------------------------------------------------------- /rrlib/rrGoldenBt.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on 07 04 2021 5 | robotRay server v1.0 6 | @author: camilorojas 7 | 8 | Backtrader for Golden cross and Death cross Strategy 9 | 10 | 11 | """ 12 | from __future__ import (absolute_import, division, print_function, 13 | unicode_literals) 14 | import backtrader as bt 15 | import math 16 | import datetime 17 | 18 | 19 | class FixedCommisionScheme(bt.CommInfoBase): 20 | ''' 21 | IB Simple commision scheme 2 usd per trade 22 | ''' 23 | params = ( 24 | ('commission', 2), 25 | ('stocklike', True), 26 | ('commtype', bt.CommInfoBase.COMM_FIXED), 27 | 28 | ) 29 | 30 | def _getcommission(self, size, price, pseudoexec): 31 | return self.p.commission 32 | 33 | 34 | class rrGoldenBt: 35 | def __init__(self): 36 | # Starting common services 37 | from rrlib.rrLogger import logger, TqdmToLogger 38 | from rrlib.rrBacktrader import rrBacktrader 39 | from rrlib.rrPortfolio import rrPortfolio 40 | from rrlib.rrDb import rrDbManager as db 41 | # Get logging service 42 | self.log = logger() 43 | self.tqdm_out = TqdmToLogger(self.log.logger) 44 | self.log.logger.debug(" Backtrader starting. ") 45 | # startup backtrading db 46 | self.btdb = rrBacktrader() 47 | self.portfolio = rrPortfolio() 48 | self.db = db() 49 | # starting ini parameters 50 | import configparser 51 | config = configparser.ConfigParser() 52 | config.read("rrlib/robotRay.ini") 53 | # max investment in % terms of porfolio 54 | # deprecating margin relates to R not maxinv 55 | self.maxinv = config.get('backtrader', 'maxinv') 56 | self.commission = float(config.get('backtrader', 'commission')) 57 | self.marginRequirement = float(config.get('backtrader', 'marginreq')) 58 | self.stoplossdistance = float(config.get('backtrader', 'stoploss')) 59 | # for now use IB like commisions 60 | self.COMMINFO_DEFAULT = dict( 61 | stocklike=False, # Futures-like 62 | commtype=bt.CommissionInfo.COMM_FIXED, # fixed price per asset 63 | commission=2.0, # Standard IB Price for futures 64 | # mult=1000.0, # multiplier default 1 65 | margin=float(self.portfolio.R)/(1-(1-self.stoplossdistance)) * \ 66 | self.marginRequirement # IB avg 27% del costo de la trx en acciones 67 | ) 68 | # Generate Cerebro 69 | self.cerebro = bt.Cerebro() 70 | self.cerebro.broker.setcash(float(self.portfolio.funds)) 71 | # Get portfoilo total 72 | 73 | def run(self): 74 | stocks = self.db.getStocks() 75 | # for index, stock in tqdm(stocks.iterrows(), desc=" Getting Historic Data", unit="Stock", ascii=False, ncols=120, leave=False): 76 | for index, stock in stocks.iterrows(): 77 | try: 78 | if stock['ticker'] == "COIN": 79 | continue 80 | # load data feeds 81 | historicdata = self.btdb.getHistoricData(stock['ticker']) 82 | feed = bt.feeds.PandasData(dataname=historicdata) 83 | self.cerebro.adddata(feed, name=stock['ticker']) 84 | except Exception as e: 85 | self.log.logger.warning(" BTGolden - Problem loading data.") 86 | self.log.logger.warning(e) 87 | 88 | # load strategy for backtesting 89 | self.cerebro.addstrategy(GoldenStrategy) 90 | # start balance for performance testing 91 | self.initialbalance = self.cerebro.broker.getvalue() 92 | # set commision statement 93 | # self.cerebro.broker.setcommission(**self.COMMINFO_DEFAULT) 94 | # new fixed 2 dolar commission similar to IB 95 | comminfo = FixedCommisionScheme(margin=float(self.portfolio.R)/(1-(1-self.stoplossdistance)) * 96 | self.marginRequirement) 97 | self.cerebro.broker.addcommissioninfo(comminfo) 98 | # Add a FixedSize sizer according to the stake 99 | # Sizing being done at the strategy class 100 | # self.cerebro.addsizer(PercentRiskSizer) 101 | # Add analyzers 102 | self.cerebro.addanalyzer(bt.analyzers.SharpeRatio, _name='mysharpe', riskfreerate=0.1) 103 | self.cerebro.addanalyzer(bt.analyzers.DrawDown, _name="myDrawDown") 104 | self.cerebro.addanalyzer(bt.analyzers.TradeAnalyzer, _name="myTradeAnalysis") 105 | self.cerebro.addanalyzer(bt.analyzers.AnnualReturn, _name='myar') 106 | self.cerebro.addanalyzer(bt.analyzers.SQN, _name="mySqn") 107 | 108 | # try to run the cerebro strategies 109 | try: 110 | strategies = self.cerebro.run() 111 | self.strategy = strategies[0] 112 | except Exception as e: 113 | self.log.logger.warning(" Cerebro Run exception") 114 | self.log.logger.warning(e) 115 | # get final balance for cerebro strategy 116 | self.finalbalance = self.cerebro.broker.getvalue() 117 | self.log.logger.info( 118 | ' Golden Strategy Backtrader') 119 | 120 | # plot the strategy if generates outstanding value 121 | # TODO: IMPORTANT ! comment the plot.show() function in the cerebro.plot() and include the following code to format width and height 122 | """ import matplotlib.pyplot as plt 123 | figs = [] 124 | for stratlist in self.runstrats: 125 | for si, strat in enumerate(stratlist): 126 | rfig = plotter.plot(strat, figid=si * 100, 127 | numfigs=numfigs, iplot=iplot, 128 | start=start, end=end, use=use) 129 | # pfillers=pfillers2) 130 | 131 | figs.append(rfig) 132 | fig = plt.gcf() 133 | fig.set_size_inches(width, height) 134 | """ 135 | figure = self.cerebro.plot(width=32, height=72, dpi=300, tight=False, barupfill=False, bardownfill=False, 136 | style='candle', plotdist=0.5, volume=False, barup='green', valuetags=False, subtxtsize=7, voltrans=0.30)[0][0] 137 | figure.savefig("rrlib/btreports/golden/" + 138 | datetime.datetime.now().strftime("%y-%m-%d")+'.png') 139 | msg = ("\n\n*** PnL: ***\n" 140 | "Start capital : ${start_cash:,.2f}\n" 141 | "Final balance : ${final_balance:,.2f}\n" 142 | "Total net profit : ${np:,.2f}\n" 143 | "Total realized profit : ${rpl:,.2f}\n" 144 | "Total unrlzd profit : ${urpl:,.2f}\n" 145 | "Result winning trades : ${result_won_trades:,.2f}\n" 146 | "Result lost trades : ${result_lost_trades:,.2f}\n" 147 | "Profit factor : {profit_factor:,.2f}\n" 148 | "Total return : {total_return:,.2f}%\n" 149 | "Annual return : {annual_return:,.2f}%\n" 150 | "Annualized returns : {ar}\n" 151 | "Max. money drawdown : ${max_money_drawdown:,.2f}\n" 152 | "Max. percent drawdown : {max_pct_drawdown:,.2f}%\n" 153 | "Total commissions : ${commissions:,.2f}\n\n" 154 | "*** Trades ***\n" 155 | "Number of trades : {total_number_trades:d}\n" 156 | " # Open trades : {open_trades:d}\n" 157 | " # Closed trades : {trades_closed:d}\n" 158 | " %winning : {pct_winning:4.2f}%\n" 159 | " %losing : {pct_losing:4.2f}%\n" 160 | " avg money winning : ${avg_money_winning:,.2f}\n" 161 | " avg money losing : ${avg_money_losing:,.2f}\n" 162 | " best winning trade: ${best_winning_trade:,.2f}\n" 163 | " worst losing trade: ${worst_losing_trade:,.2f}\n\n" 164 | "*** Performance ***\n" 165 | "Sharpe ratio : {sharpe_ratio:4.2f}\n" 166 | "SQN score : {sqn_score:4.2f}\n" 167 | "SQN human : {sqn_human:s}\n\n" 168 | ) 169 | kpis = self.get_performance_stats() 170 | # see: https://stackoverflow.com/questions/24170519/ 171 | # python-# typeerror-non-empty-format-string-passed-to-object-format 172 | kpis = {k: -999 if v is None else v for k, v in kpis.items()} 173 | self.log.logger.info(msg.format(**kpis)) 174 | 175 | def get_performance_stats(self): 176 | """ Return dict with performace stats for given strategy withing backtest 177 | """ 178 | st = self.strategy 179 | dt = st.data._dataname['open'].index 180 | bt_period = dt[-1] - dt[0] 181 | bt_period_days = bt_period.days 182 | drawdown = st.analyzers.myDrawDown.get_analysis() 183 | sharpe_ratio = st.analyzers.mysharpe.get_analysis()['sharperatio'] 184 | sqn_score = st.analyzers.mySqn.get_analysis()['sqn'] 185 | ar = '' 186 | for key, value in st.analyzers.myar.get_analysis().items(): 187 | ar = ar+str(key)+":"+str(round(value*100, 2))+"%, " 188 | 189 | try: 190 | trade_analysis = st.analyzers.myTradeAnalysis.get_analysis() 191 | rpl = trade_analysis.pnl.net.total 192 | total_return = rpl / self.initialbalance 193 | total_number_trades = trade_analysis.total.total 194 | trades_closed = trade_analysis.total.closed 195 | except Exception: 196 | self.log.logger.info(" No trades in this model") 197 | kpi = { # PnL 198 | 'start_cash': self.initialbalance, 199 | 'final_balance': self.finalbalance, 200 | 'np': (self.finalbalance-self.initialbalance), 201 | 'rpl': 0, 202 | 'urpl': 0, 203 | 'result_won_trades': 0, 204 | 'result_lost_trades': 0, 205 | 'profit_factor': 0, 206 | 'rpl_per_trade': 0, 207 | 'total_return': 0, 208 | 'annual_return': 0, 209 | 'ar': ar, 210 | 'max_money_drawdown': drawdown['max']['moneydown'], 211 | 'max_pct_drawdown': drawdown['max']['drawdown'], 212 | 'commissions': 0, 213 | # trades 214 | 'total_number_trades': 0, 215 | 'open_trades': 0, 216 | 'trades_closed': 0, 217 | 'pct_winning': 0, 218 | 'pct_losing': 0, 219 | 'avg_money_winning': 0, 220 | 'avg_money_losing': 0, 221 | 'best_winning_trade': 0, 222 | 'worst_losing_trade': 0, 223 | # performance 224 | 'sharpe_ratio': sharpe_ratio, 225 | 'sqn_score': sqn_score, 226 | 'sqn_human': self._sqn2rating(sqn_score) 227 | } 228 | return kpi 229 | 230 | kpi = { # PnL 231 | 'start_cash': self.initialbalance, 232 | 'final_balance': self.finalbalance, 233 | 'np': (self.finalbalance-self.initialbalance), 234 | 'rpl': rpl, 235 | 'urpl': (self.finalbalance-self.initialbalance)-rpl, 236 | 'result_won_trades': trade_analysis.won.pnl.total, 237 | 'result_lost_trades': trade_analysis.lost.pnl.total, 238 | 'profit_factor': (-1 * trade_analysis.won.pnl.total / trade_analysis.lost.pnl.total), 239 | 'rpl_per_trade': rpl / trades_closed, 240 | 'total_return': 100 * total_return, 241 | 'annual_return': (100 * (1 + total_return)**(365.25 / bt_period_days) - 100), 242 | 'ar': ar, 243 | 'max_money_drawdown': drawdown['max']['moneydown'], 244 | 'max_pct_drawdown': drawdown['max']['drawdown'], 245 | 'commissions': (trade_analysis.pnl.gross.total-trade_analysis.pnl.net.total), 246 | # trades 247 | 'total_number_trades': total_number_trades, 248 | 'open_trades': total_number_trades-trades_closed, 249 | 'trades_closed': trades_closed, 250 | 'pct_winning': 100 * trade_analysis.won.total / trades_closed, 251 | 'pct_losing': 100 * trade_analysis.lost.total / trades_closed, 252 | 'avg_money_winning': trade_analysis.won.pnl.average, 253 | 'avg_money_losing': trade_analysis.lost.pnl.average, 254 | 'best_winning_trade': trade_analysis.won.pnl.max, 255 | 'worst_losing_trade': trade_analysis.lost.pnl.max, 256 | # performance 257 | 'sharpe_ratio': sharpe_ratio, 258 | 'sqn_score': sqn_score, 259 | 'sqn_human': self._sqn2rating(sqn_score) 260 | } 261 | return kpi 262 | 263 | def _sqn2rating(self, sqn_score): 264 | """ Converts sqn_score score to human readable rating 265 | See: http://www.vantharp.com/tharp-concepts/sqn.asp 266 | """ 267 | if sqn_score < 1.6: 268 | return "Poor" 269 | elif sqn_score < 1.9: 270 | return "Below average" 271 | elif sqn_score < 2.4: 272 | return "Average" 273 | elif sqn_score < 2.9: 274 | return "Good" 275 | elif sqn_score < 5.0: 276 | return "Excellent" 277 | elif sqn_score < 6.9: 278 | return "Superb" 279 | else: 280 | return "Holy Grail" 281 | 282 | 283 | class GoldenStrategy(bt.Strategy): 284 | params = ( 285 | ('exitbars', 5), 286 | ('smashort', 50), 287 | ('smalong', 200) 288 | ) 289 | 290 | def __init__(self): 291 | # start logger service 292 | from rrlib.rrLogger import logger 293 | from rrlib.rrPortfolio import rrPortfolio 294 | self.portfolio = rrPortfolio() 295 | self.log = logger() 296 | # To keep track of pending orders 297 | self.buyprice = None 298 | self.buycomm = None 299 | self.oneplot = False 300 | # starting ini parameters 301 | import configparser 302 | config = configparser.ConfigParser() 303 | config.read("rrlib/robotRay.ini") 304 | # max investment in % terms of porfolio 305 | # deprecating margin relates to R not maxinv 306 | self.maxinv = config.get('backtrader', 'maxinv') 307 | self.marginRequirement = float(config.get('backtrader', 'marginreq')) 308 | self.stoplossdistance = float(config.get('backtrader', 'stoploss')) 309 | 310 | # Add two MovingAverageSimple indicator and a crossover 311 | self.inds = dict() 312 | for i, d in enumerate(self.datas): 313 | self.inds[d] = dict() 314 | self.inds[d]['sma1'] = bt.indicators.SimpleMovingAverage( 315 | d.close, period=self.params.smashort) 316 | self.inds[d]['sma2'] = bt.indicators.SimpleMovingAverage( 317 | d.close, period=self.params.smalong) 318 | self.inds[d]['cross'] = bt.indicators.CrossOver( 319 | self.inds[d]['sma1'], self.inds[d]['sma2']) 320 | 321 | if i > 0: # Check we are not on the first loop of data feed: 322 | if self.oneplot is True: 323 | d.plotinfo.plotmaster = self.datas[0] 324 | 325 | # bt.indicators.MACDHisto(self.datas[0]) 326 | # rsi = bt.indicators.RSI(self.datas[0]) 327 | # bt.indicators.SmoothedMovingAverage(rsi, period=10) 328 | # bt.indicators.ATR(self.datas[0], plot=False) 329 | 330 | def notify_order(self, order): 331 | if order.status in [order.Submitted, order.Accepted]: 332 | # Buy/Sell order submitted/accepted to/by broker - Nothing to do 333 | self.log.logger.debug("Order submited accepted") 334 | return 335 | 336 | # Check if an order has been completed 337 | # Attention: broker could reject order if not enough cash 338 | if order.status in [order.Completed]: 339 | if order.isbuy(): 340 | self.log.logger.debug('BUY EXECUTED, %.2f' % order.executed.price) 341 | self.buyprice = order.executed.price 342 | self.buycomm = order.executed.comm 343 | elif order.issell(): 344 | self.log.logger.debug('SELL EXECUTED, %.2f' % order.executed.price) 345 | 346 | self.bar_executed = len(self) 347 | 348 | elif order.status in [order.Canceled, order.Margin, order.Rejected]: 349 | self.log.logger.info('Order Canceled/Margin/Rejected') 350 | self.log.logger.info(order) 351 | 352 | def notify_trade(self, trade): 353 | if not trade.isclosed: 354 | return 355 | 356 | self.log.logger.debug('OPERATION PROFIT, GROSS '+str(trade.pnl) + 357 | ', NET ' + str(trade.pnlcomm)) 358 | 359 | def next(self): 360 | for i, d in enumerate(self.datas): 361 | position = self.getposition(d).size 362 | # of stoploss distance in % terms 363 | stop_price = (d.close * (1 - self.stoplossdistance)) 364 | self.size = math.floor(float(self.portfolio.R) / 365 | (d.close-stop_price)) 366 | if not position: # no market / no orders 367 | if self.inds[d]['cross'][0] == 1: 368 | self.buy(data=d, size=self.size) 369 | self.sell(exectype=bt.Order.Stop, size=self.size, price=stop_price) 370 | elif self.inds[d]['cross'][0] == -1: 371 | self.sell(data=d, size=self.size) 372 | self.buy(exectype=bt.Order.Stop, size=self.size, price=stop_price) 373 | else: 374 | if self.inds[d]['cross'][0] == 1: 375 | self.close(data=d) 376 | self.buy(data=d, size=self.size) 377 | elif self.inds[d]['cross'][0] == -1: 378 | self.close(data=d) 379 | self.sell(data=d, size=self.size) 380 | 381 | if len(d) == (d.buflen()-1): 382 | self.close(d, exectype=bt.Order.Market) 383 | -------------------------------------------------------------------------------- /rrlib/rrController.py: -------------------------------------------------------------------------------- 1 | # !/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on 07 05 2019 5 | robotRay server v1.0 6 | @author: camilorojas 7 | 8 | Controller class file that coordinates channel requests and executes with backend commands 9 | Initially attending Telegram service. Future will connect server interaction 10 | """ 11 | 12 | import threading 13 | import sys 14 | import os 15 | import configparser 16 | import datetime 17 | from rrlib.rrPutSellStrategy import rrPutSellStrategy 18 | from rrlib.rrGoldenStrategy import rrGoldenStrategy 19 | from rrlib.rrBacktrader import rrBacktrader 20 | from rrlib.rrDailyScan import rrDailyScan 21 | 22 | 23 | class rrController(): 24 | def __init__(self, *args, **kwargs): 25 | # starting common services 26 | sys.path.append(os.path.join(os.path.dirname(__file__), '..')) 27 | # starting logging service 28 | from rrlib.rrLogger import logger 29 | self.log = logger() 30 | # starting backend services 31 | from rrlib.rrDb import rrDbManager 32 | self.db = rrDbManager() 33 | self.bt = rrBacktrader() 34 | self.sellp = rrPutSellStrategy() 35 | self.rrGoldenStrategy = rrGoldenStrategy() 36 | # starting ini parameters 37 | config = configparser.ConfigParser() 38 | config.read("rrlib/robotRay.ini") 39 | # run outside trading hours 40 | self.oth = config.get("debug", "oth") 41 | self.log.logger.debug("Initialization finished robotRay controller") 42 | # controller runtime variables 43 | self.runCycle = 0 44 | 45 | def botcommand(self, command=""): 46 | response = [] 47 | command = command.lower() 48 | if (command == "intro" or command == "about"): 49 | response.append("") 50 | response.append("RobotRay by Camilo Rojas") 51 | elif(command == "help"): 52 | response.append("") 53 | response.append( 54 | "RobotRay Help Menu - for Telegram") 55 | response.append( 56 | "General Commands: help, status, source, jobs, intro, about") 57 | response.append( 58 | "Stock Data info commands: printstocks, printintra") 59 | response.append("Option Data info commands: printoptions") 60 | response.append( 61 | "Run prospect info: printallp, printopenp, printclosedp, sendp") 62 | response.append( 63 | "Statistics for bot operations: report, reporty, reportytd, reportsm, reportw") 64 | elif (command == "source"): 65 | response.append("") 66 | if (self.db.getSource() == "public"): 67 | response.append("Current data fetched from: Finviz & Yahoo") 68 | elif (self.db.getSource() == "ib"): 69 | response.append("Current data fetched from: Interactive Brokers") 70 | else: 71 | response.append(self.db.getSource()) 72 | elif (command == "printstocks"): 73 | response.append("") 74 | response.append("Stocks being tracked") 75 | response.append(self.db.printStocks()) 76 | elif (command == "printintra"): 77 | response.append("") 78 | response.append("Stocks current intraday data") 79 | response.append(self.db.printIntradayStocks()) 80 | elif (command == "printoptions"): 81 | response.append("") 82 | response.append("Options data") 83 | response.append(self.db.printOptions()) 84 | elif (command == "printopenp"): 85 | response.append("") 86 | response.append("Open Prospect data") 87 | response.append(self.sellp.printOpenProspects()) 88 | elif (command == "printclosedp"): 89 | response.append("") 90 | response.append("Closed Prospect data") 91 | response.append(self.sellp.printClosedProspects()) 92 | elif (command == "printallp"): 93 | response.append("") 94 | response.append("All Prospect data sorted by PNL") 95 | response.append(self.sellp.printAllProspects()) 96 | elif(command == "sendp"): 97 | response.append("") 98 | response.append("Sent daily report of prospects") 99 | self.sellp.sendDailyReport() 100 | elif(command == "getstockdata"): 101 | response.append("db.getStockData") 102 | response.append("Getting stock data manually") 103 | elif(command == "getintra"): 104 | response.append("db.getIntradayData") 105 | response.append("Getting stock intraday data manually") 106 | elif(command == "getoptiondata"): 107 | response.append("db.getOptionData") 108 | response.append("Getting stock option data manually") 109 | elif(command == "status"): 110 | response.append("") 111 | response.append("Status report RobotRay.") 112 | if (self.db.getSource() == "public"): 113 | response.append("Current data fetched from: Finviz & Yahoo") 114 | elif (self.db.getSource() == "ib"): 115 | response.append("Current data fetched from Interactive Brokers") 116 | else: 117 | response.append(self.db.getSource()) 118 | elif(command == "jobs"): 119 | response.append("") 120 | response.append("Currently running: " + 121 | str(threading.active_count())+" threads.") 122 | elif(command == ""): 123 | response.append("") 124 | response.append("No command sent") 125 | else: 126 | response.append("") 127 | response.append("Unknown command, try help for commands") 128 | return response 129 | 130 | def consolecommand(self, command=""): 131 | response = [] 132 | command = command.lower() 133 | try: 134 | if (command == "intro" or command == "about"): 135 | response.append("intro") 136 | elif(command == "quit" or command == "exit"): 137 | if input("\n998. Really quit? (y/n)>").lower().startswith('y'): 138 | response.append("shutdown") 139 | elif(command == "help"): 140 | response.append("") 141 | response.append("=" * 64) 142 | response.append( 143 | "RobotRay Help Menu - commands and manual override options") 144 | response.append("=" * 64) 145 | response.append("") 146 | response.append( 147 | " General Commands: help, clear, status, source, jobs,") 148 | response.append( 149 | " isdbinuse, quit, exit, intro, about") 150 | response.append("-" * 64) 151 | response.append( 152 | " The following are scheduled automatically, run only for override") 153 | response.append( 154 | " Stock Data refresh manual commands: getstockdata, getintradaydata") 155 | response.append( 156 | " Option Data refresh manual commands: getoptiondata") 157 | response.append("-" * 64) 158 | response.append(" Portfolio commands (TBD): switchsource, ") 159 | response.append(" getPositions, getAccount, getBuyingPower ") 160 | response.append(" getAvailableFunds, getCash, getUnrPNL, getRPNL ") 161 | response.append(" getTrades, getOpenTrades, getOpenOrders, getOrders ") 162 | response.append("-" * 64) 163 | response.append( 164 | " Stock Data info commands: printstocks, printintra") 165 | response.append(" Option Data info commands: printoptions") 166 | response.append( 167 | " Run prospect info: printallp, printopenp, printclosedp, sendp") 168 | response.append("-" * 64) 169 | response.append(" Strategies: sellputs, golden") 170 | response.append(" Backtrader: btdownload, btsellputs, btgolden") 171 | response.append("-" * 64) 172 | response.append(" Daily scanner override: dailyscan") 173 | response.append("-" * 64) 174 | response.append( 175 | " Statistics for bot operations (TBD): report, reporty, ") 176 | response.append( 177 | " reportytd, reportsm, reportw") 178 | response.append("=" * 64) 179 | elif(command == "clear"): 180 | response.append("") 181 | if sys.platform == 'win32': 182 | os.system("cls") 183 | else: 184 | os.system("clear") 185 | elif(command == "isdbinuse"): 186 | response.append("") 187 | if(self.db.isDbInUse()): 188 | response.append("994. DB is currently: Not used by any thread") 189 | else: 190 | response.append("994. DB is currently: In Use by thread") 191 | elif (command == "source"): 192 | response.append("") 193 | if (self.db.getSource() == "public"): 194 | response.append("501. Current data fetched from: Finviz & Yahoo") 195 | elif (self.db.getSource() == "ib"): 196 | response.append("501. Current data fetched from: Interactive Brokers") 197 | else: 198 | response.append("501. "+self.db.getSource()) 199 | # elif (command == "setpassword"): 200 | # passwd = getpass.getpass("Enter password:") 201 | # keyring.set_password("RobotRayIB", "camilo", passwd) 202 | # print(keyring.get_password("RobotRayIB", "camilo")) 203 | elif (command == "printstocks"): 204 | response.append("db.printStocks") 205 | response.append("550. Stocks being tracked:") 206 | elif (command == "printintra"): 207 | response.append("db.printIntradayStocks") 208 | response.append("560. Stocks current intraday data:") 209 | elif (command == "printoptions"): 210 | response.append("db.printOptions") 211 | response.append("570. Options data:") 212 | elif (command == "printopenp"): 213 | response.append("sellp.printOpenProspects") 214 | response.append("130. Open Prospect data:") 215 | elif (command == "printclosedp"): 216 | response.append("sellp.printClosedProspects") 217 | response.append("130. Closed Prospect data:") 218 | elif (command == "printallp"): 219 | response.append("sellp.printAllProspects") 220 | response.append("130. Prospect data:") 221 | elif(command == "sendp"): 222 | self.sellp.sendDailyReport() 223 | elif(command == "status"): 224 | self.status() 225 | elif(command == "getstockdata"): 226 | self.getStockData() 227 | elif(command == "getintradaydata"): 228 | self.getIntradayData() 229 | elif(command == "getoptiondata"): 230 | self.getOptionData() 231 | elif(command == "jobs"): 232 | response.append("") 233 | response.append("996. Currently running: " + 234 | str(threading.active_count())+" threads.") 235 | elif(command == "golden"): 236 | self.goldenstrategy() 237 | elif(command == "sellputs"): 238 | self.sellputsstrategy() 239 | elif(command == "btdownload"): 240 | self.btdownloader() 241 | elif(command == "dailyscan"): 242 | self.dailyScan() 243 | elif(command == "btgolden"): 244 | self.btgolden() 245 | elif(command == "btsellputs"): 246 | self.btsellputs() 247 | elif(command == ""): 248 | pass 249 | else: 250 | response.append("") 251 | response.append("Unknown command, try help for commands") 252 | return response 253 | except Exception as e: 254 | self.log.logger.error(e) 255 | 256 | def status(self): 257 | f = '{:>30}|{:<70}' # format 258 | status = self.db.getServerRun() 259 | for x in range(len(status.columns)): 260 | self.log.logger.info(f.format(status.columns[x], str(status.iloc[0, x]))) 261 | 262 | def ismarketopen(self): 263 | import datetime 264 | if (datetime.datetime.today().weekday() < 5) and ((datetime.datetime.now().time() > datetime.time(7, 30)) and 265 | (datetime.datetime.now().time() < datetime.time(20, 00))): 266 | return True 267 | else: 268 | self.log.logger.info("998. - Market closed or not a working day") 269 | return False 270 | 271 | def getStockData(self): 272 | self.log.logger.info("10. Getting stock data, daily process ") 273 | if self.ismarketopen() or self.oth == "Yes": 274 | try: 275 | self.db.getStockData() 276 | self.log.logger.info( 277 | "10. DONE - Stock data fetched") 278 | self.rrGoldenStrategy.evaluateProspects() 279 | self.db.updateServerRun(lastStockDataUpdate=datetime.datetime.now()) 280 | except Exception as e: 281 | self.log.logger.error("10. Error fetching daily stock data") 282 | self.log.logger.error(e) 283 | 284 | def getOptionData(self): 285 | self.log.logger.info("20. Getting Option Data") 286 | if self.ismarketopen() or self.oth == "Yes": 287 | try: 288 | self.db.getOptionData() 289 | self.log.logger.info( 290 | "20. DONE - Option data successfully fetched") 291 | self.db.updateServerRun(lastOptionDataUpdate=datetime.datetime.now()) 292 | except Exception as e: 293 | self.log.logger.error("20. Error fetching daily option data") 294 | self.log.logger.error(e) 295 | 296 | def getIntradayData(self): 297 | self.log.logger.info("30. Getting Intraday Data") 298 | self.runCycle = self.runCycle + 1 299 | if self.ismarketopen() or self.oth == "Yes": 300 | try: 301 | self.db.getIntradayData() 302 | self.log.logger.info( 303 | "30. DONE - Intraday data successfully fetched") 304 | self.sellputsstrategy() 305 | except Exception as e: 306 | self.log.logger.error("30. Error fetching Intraday data") 307 | self.log.logger.error(e) 308 | 309 | def dailyScan(self): 310 | self.log.logger.info("85. Running daily scan") 311 | if self.ismarketopen() or self.oth == "Yes": 312 | try: 313 | self.btdownloader() 314 | ds = rrDailyScan() 315 | ds.communicateScan() 316 | self.log.logger.info( 317 | "85. DONE - Ran daily scanner") 318 | except Exception as e: 319 | self.log.logger.error("85. Error running daily scann") 320 | self.log.logger.error(e) 321 | 322 | def btdownloader(self): 323 | self.log.logger.info("80. Backtrader downloading data") 324 | if self.ismarketopen() or self.oth == "Yes": 325 | try: 326 | self.bt.downloadStockData() 327 | self.log.logger.info( 328 | "80. DONE - Backtrader successfully fetched") 329 | except Exception as e: 330 | self.log.logger.error("80. Error fetching backtrader data") 331 | self.log.logger.error(e) 332 | 333 | def btgolden(self): 334 | self.log.logger.info("81. Backtrader golden strategy") 335 | if self.ismarketopen() or self.oth == "Yes": 336 | try: 337 | self.bt.btGolden() 338 | self.log.logger.info( 339 | "81. DONE - Backtrader golden strategy") 340 | except Exception as e: 341 | self.log.logger.error("81. Error backtrading golden strategy") 342 | self.log.logger.error(e) 343 | 344 | def btsellputs(self): 345 | self.log.logger.info("82. Backtrader sell puts strategy") 346 | if self.ismarketopen() or self.oth == "Yes": 347 | try: 348 | self.bt.btGolden() 349 | self.log.logger.info( 350 | "82. DONE - Backtrader sell puts strategy") 351 | except Exception as e: 352 | self.log.logger.error("82. Error backtrading sell puts strategy") 353 | self.log.logger.error(e) 354 | 355 | def goldenstrategy(self): 356 | self.log.logger.info("200. Initiating Golden Strategy ...") 357 | if self.ismarketopen() or self.oth == "Yes": 358 | try: 359 | self.log.logger.info( 360 | " 210. Evaluating changes in SMA50 and SMA200 for intersections of elegible stocks") 361 | self.rrGoldenStrategy.evaluateProspects() 362 | self.db.updateServerRun(lastThinkUpdate=datetime.datetime.now()) 363 | self.log.logger.info("200. DONE - Finished strategy") 364 | except Exception as e: 365 | self.log.logger.error("200. Error strategy") 366 | self.log.logger.error(e) 367 | 368 | def sellputsstrategy(self): 369 | self.log.logger.info( 370 | "100. Initiating Sell Puts Strategy ...") 371 | if self.ismarketopen() or self.oth == "Yes": 372 | try: 373 | self.log.logger.info( 374 | " 110. Evaluating daily drops and pricing opptys for elegible stocks") 375 | self.sellp.evaluateProspects() 376 | self.log.logger.info( 377 | " 120. Updating pricing for existing prospects") 378 | self.sellp.updatePricingProspects() 379 | self.log.logger.info( 380 | " 130. Communicating prospects") 381 | self.sellp.communicateProspects() 382 | self.log.logger.info( 383 | " 140. Communicating closings") 384 | self.sellp.communicateClosing() 385 | self.db.updateServerRun(lastThinkUpdate=datetime.datetime.now()) 386 | self.log.logger.info("100. DONE - Finished Sell Puts Strategy") 387 | except Exception as e: 388 | self.log.logger.error("100. Error Sell Puts Strategy") 389 | self.log.logger.error(e) 390 | 391 | def sendReport(self): 392 | self.log.logger.info( 393 | "200. Sending report") 394 | if self.ismarketopen() or self.oth == "Yes": 395 | try: 396 | self.sellp.sendDailyReport() 397 | self.log.logger.info("200. DONE - Finished sending report") 398 | except Exception as e: 399 | self.log.logger.error("200. Error sending report") 400 | self.log.logger.error(e) 401 | -------------------------------------------------------------------------------- /rrlib/rrPutSellStrategy.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on 07 04 2021 5 | robotRay server v1.0 6 | @author: camilorojas 7 | 8 | Put Sell Strategy module (former Thinker module) 9 | 10 | Process for module v1 11 | 1. Evaluate for list of stocks intraday lows greater than 4.5% decrease in price 12 | 2. Retreive last price and price range for elegible stocks 13 | 3. Evaluate pricing opportunities for these stocks with enough volume and open positions 14 | 4. Evaluate best month scenario to recommend 15 | 5. Communicate to Camilor if there are prospects above the limit kpi's 16 | 17 | Active Evaluator module 18 | 1. Save all recommended prospects with decision information 19 | 2. Evaluate if sell premium has been captured 20 | 3. Communicate to Camilor to close positions 21 | 22 | Passive Evaluator module 23 | Batch nature for evaluation of alerted positions 24 | 25 | """ 26 | 27 | import sys 28 | import os 29 | import datetime 30 | from tqdm import tqdm 31 | import pandas as pd 32 | 33 | 34 | class rrPutSellStrategy: 35 | def __init__(self): 36 | # starting common services 37 | sys.path.append(os.path.join(os.path.dirname(__file__), '..')) 38 | # starting logging 39 | from rrlib.rrLogger import logger 40 | self.log = logger() 41 | # starting backend services 42 | from rrlib.rrDb import rrDbManager 43 | self.db = rrDbManager() 44 | # portfolio startup 45 | from rrlib.rrPortfolio import rrPortfolio 46 | self.portfolio = rrPortfolio() 47 | # starting ini parameters 48 | import configparser 49 | config = configparser.ConfigParser() 50 | config.read("rrlib/robotRay.ini") 51 | # daily decrease green if % stock dtd growth < -4.5%, -4.5% < yellow < 2%, red > 2% 52 | self.dayPriceChgGreen = config.get('sellputstrategy', 'dayPriceChgGreen') 53 | self.dayPriceChgRed = config['sellputstrategy']['dayPriceChgRed'] 54 | # expected minimum monthly premium for holding the option 1% 55 | self.monthlyPremium = self.portfolio.monthlyPremium 56 | # sma200 below 0 is red, <0.1 yellow, > 0.1 green 57 | self.smaGreen = config['sellputstrategy']['smaGreen'] 58 | self.smaRed = config['sellputstrategy']['smaRed'] 59 | # sales growth quarter to quarter 60 | self.salesGrowthGreen = config['sellputstrategy']['salesGrowthGreen'] 61 | self.salesGrowthRed = config['sellputstrategy']['salesGrowthRed'] 62 | # retreive R 63 | self.R = self.portfolio.R 64 | self.availableFunds = self.portfolio.funds 65 | # Intraday kpi green and red 66 | self.IntradayKPIGreen = config['sellputstrategy']['IntradayKPIGreen'] 67 | self.IntradayKPIRed = config['sellputstrategy']['IntradayKPIRed'] 68 | # Get number of days to BTC on Options 69 | self.BTCdays = config['sellputstrategy']['BTCdays'] 70 | # Target of premium collected before closing 71 | self.PremiumTarget = config['sellputstrategy']['PremiumTarget'] 72 | # Get option expected price flexiblity to ask limit 73 | self.ExpPrice2Ask = config['sellputstrategy']['ExpPrice2Ask'] 74 | # is telegram bot enabled for commands 75 | self.startbot = config.get('telegram', 'startbot') 76 | # Get verbose option boolean 77 | self.verbose = config['sellputstrategy']['verbose'] 78 | self.log.logger.debug(" Put Sell Strategy module starting. ") 79 | 80 | def evaluateProspects(self): 81 | sys.path.append(os.path.join(os.path.dirname(__file__), '..')) 82 | from rrlib.rrDb import IntradayStockData 83 | from rrlib.rrDb import OptionData 84 | from rrlib.rrDb import StockData 85 | 86 | # print debug init parameters 87 | if(self.verbose == "Yes"): 88 | self.log.logger.info( 89 | " 105. Put Sell Strategy operational parameters: Day Percentage Change for Green day:" + 90 | str(float(self.dayPriceChgGreen)*100) 91 | + "%, for Red Day:" + str(float(self.dayPriceChgRed)*100)+"%") 92 | self.log.logger.info(" Monthly Expected Premium:" + str(float(self.monthlyPremium)*100) 93 | + "%, Simple Moving Average 200 for Green Day:" + 94 | str(float(self.smaGreen)*100) + 95 | "%, for Red Day:" + str(float(self.smaRed*100))+"%") 96 | self.log.logger.info(" Available funds in portfolio: USD$" + 97 | str(self.availableFunds)+", R (risk money per trade):USD$" + self.R) 98 | 99 | try: 100 | for stock in tqdm(IntradayStockData.select(), desc="Getting KPI's of Stock Data:", unit="Stock", ascii=False, ncols=120, leave=False): 101 | strike = StockData.select(StockData.strike).where( 102 | StockData.stock == stock.stock).order_by(StockData.id.desc()).get().strike 103 | if float(stock.pctChange) < float(self.dayPriceChgGreen) and float(stock.kpi) > float(self.IntradayKPIGreen): 104 | try: 105 | higherOptionData = OptionData.select().where( 106 | (OptionData.stock == stock.stock) & (OptionData.strike == strike) & 107 | (OptionData.timestamp > (datetime.datetime.now()-datetime.timedelta(days=4)))).order_by(OptionData.kpi.desc()).get() 108 | if float(higherOptionData.price) > float(higherOptionData.expectedPremium): 109 | price = higherOptionData.price 110 | else: 111 | price = higherOptionData.expectedPremium 112 | # found a prospect 113 | if float(price) < float(higherOptionData.ask)*float(self.ExpPrice2Ask) and float(higherOptionData.contracts) > 0: 114 | self.log.logger.info( 115 | " Put Sell Strategy found a prospect with green day decline and also green KPI, STO Puts for: "+stock.stock) 116 | self.log.logger.info(self.prospectFormatter(stock.stock, str(higherOptionData.expireDate), strike, price, 117 | higherOptionData.contracts, 118 | higherOptionData.bid, higherOptionData.ask, higherOptionData.expectedPremium, 119 | higherOptionData.Rpotential)) 120 | # save prospect db for communication 121 | self.db.saveProspect(stock.stock, strike, higherOptionData.expireDate, price, higherOptionData.contracts, 122 | higherOptionData.stockOwnership, higherOptionData.Rpotential, 123 | kpi=higherOptionData.kpi, color="green") 124 | except OptionData.DoesNotExist: 125 | tqdm.write(str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')) 126 | + " - rrLog - " + 127 | "INFO - Green Potential day decline, but no option data for: "+stock.stock + 128 | " with strike:"+strike + ", in the last 4 days") 129 | # Yellow day decline 130 | elif float(stock.pctChange) < float(self.dayPriceChgRed) and float(stock.kpi) > float(self.IntradayKPIGreen): 131 | try: 132 | higherOptionData = OptionData.select().where( 133 | (OptionData.stock == stock.stock) & (OptionData.strike == strike) & 134 | (OptionData.timestamp > (datetime.datetime.now()-datetime.timedelta(days=4)))).order_by(OptionData.kpi.desc()).get() 135 | if float(higherOptionData.price) > float(higherOptionData.expectedPremium): 136 | price = higherOptionData.price 137 | else: 138 | price = higherOptionData.expectedPremium 139 | # found a prospect 140 | if float(price) < float(higherOptionData.ask)*float(self.ExpPrice2Ask) and float(higherOptionData.contracts) > 0: 141 | self.log.logger.info( 142 | " Put Sell Strategy found a prospect with yellow day decline and also green KPI, STO Puts for: "+stock.stock) 143 | self.log.logger.info(self.prospectFormatter(stock.stock, str(higherOptionData.expireDate), strike, price, 144 | higherOptionData.contracts, 145 | higherOptionData.bid, higherOptionData.ask, higherOptionData.expectedPremium, 146 | higherOptionData.Rpotential)) 147 | self.db.saveProspect(stock.stock, strike, higherOptionData.expireDate, price, higherOptionData.contracts, 148 | higherOptionData.stockOwnership, higherOptionData.Rpotential, 149 | kpi=higherOptionData.kpi, color="yellow") 150 | except OptionData.DoesNotExist: 151 | tqdm.write(str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')) 152 | + " - rrLog - " + 153 | "INFO - Yellow Potential day decline, but no option data for: "+stock.stock + 154 | " with strike:"+strike + ", in the last 4 days") 155 | 156 | except Exception as e: 157 | self.log.logger.error(" Put Sell Strategy evaluation error") 158 | self.log.logger.error(e) 159 | 160 | def prospectFormatter(self, stock="STOCK", expireDate="YYYY-MM-DD", strike="100", price="1", contracts="1", 161 | bid="1.1", ask="1.1", expectedPremium="1", Rpotential="1.1"): 162 | message = "" 163 | try: 164 | message = "\n\n --------------PROSPECT DETAILS-------------------\n" + " STO " + \ 165 | stock + " " + expireDate + "P" + strike + " price:" + str(round(float(price), 2))+"\n" + " Best month is: " + expireDate + \ 166 | ", strike "+strike + ", price " + str(round(float(price), 2)) + ", quantity " + contracts + ", current range is \n" + " Bid: " + \ 167 | str(round(float(bid), 2)) + " and Ask: " + str(round(float(ask), 2)) + " min premium expected is: " + \ 168 | str(round(float(expectedPremium), 2)) + " and RPotential is: " + str(round(float(Rpotential), 2))+"\n" + \ 169 | " BTC when price reaches either Price: " + str(round(float(price)/2, 2)) + "\n" + \ 170 | " --------------PROSPECT DETAILS-------------------\n" 171 | except Exception as e: 172 | self.log.logger.error( 173 | " Put Sell Strategy prospect formatter error") 174 | self.log.logger.error(e) 175 | return message 176 | 177 | def communicateProspects(self): 178 | import datetime 179 | from rrlib.rrTelegram import rrTelegram 180 | from rrlib.rrIFTTT import rrIFTTT 181 | from rrlib.rrDb import ProspectData as pd 182 | try: 183 | for prospect in pd.select().where(pd.STOcomm.is_null()): 184 | report = {} 185 | report["value1"] = "Put Sell Strategy: Prospect Found: Stock:"+prospect.stock+" Strike:" + \ 186 | prospect.strike+" Expiration Date:" + str(prospect.expireDate) 187 | report["value2"] = "Contracts:" + prospect.contracts+" Price:" + str(round(float( 188 | prospect.price), 3)) + " RPotential:"+str(round(float(prospect.Rpotential), 2)) 189 | report["value3"] = "Stock ownership:" +\ 190 | prospect.stockOwnership+" Color:"+prospect.color 191 | self.log.logger.debug( 192 | " Communicator , invoking with these parameters "+str(report)) 193 | self.db.updateServerRun(prospectsFound="Yes") 194 | try: 195 | r = rrIFTTT().send(report) 196 | rrTelegram().sendMessage( 197 | str(report["value1"])+" | "+str(report["value2"])+" | "+str(report["value3"])) 198 | if str(r) == "": 199 | pd.update({pd.STOcomm: datetime.datetime.today()}).where((pd.stock == prospect.stock) & ( 200 | pd.strike == prospect.strike) & (pd.expireDate == prospect.expireDate)).execute() 201 | 202 | except Exception as e: 203 | self.log.logger.error( 204 | " Put Sell Strategy prospect IFTTT error") 205 | self.log.logger.error(e) 206 | except Exception as e: 207 | self.log.logger.error( 208 | " Put Sell Strategy prospect communicator error") 209 | self.log.logger.error(e) 210 | 211 | def communicateClosing(self): 212 | import datetime 213 | from rrlib.rrTelegram import rrTelegram 214 | from rrlib.rrIFTTT import rrIFTTT 215 | from rrlib.rrDb import ProspectData as pd 216 | try: 217 | for prospect in pd.select().where(pd.BTCcomm.is_null()): 218 | if ((float(prospect.price)*float(self.PremiumTarget) > float(prospect.currentPrice)) or 219 | (float((prospect.expireDate-datetime.date.today()).days) < float(self.BTCdays))): 220 | pnl = str(round(float(prospect.contracts) * 221 | (float(prospect.price)-float(prospect.currentPrice))*100-float(prospect.contracts)*2, 2)) 222 | report = {} 223 | report["value1"] = "Time to close the contract
Stock:"+prospect.stock +\ 224 | " Strike:" + str(prospect.strike) +\ 225 | " Expiration Date:" + str(prospect.expireDate) 226 | report["value2"] = "Contracts:" + str(prospect.contracts)+" Closing Price:" +\ 227 | str(round(float(prospect.currentPrice), 3)) +\ 228 | " PNL for this oppty:" + pnl 229 | report["value3"] = "Stock ownership:" +\ 230 | str(prospect.stockOwnership)+" Color:"+prospect.color 231 | self.log.logger.debug( 232 | " Communicator, invoking with these parameters " + str(report)) 233 | self.db.updateServerRun(pnl=pnl) 234 | try: 235 | r = rrIFTTT().send(report) 236 | if (self.startbot == "Yes"): 237 | rrTelegram().sendMessage( 238 | str(report["value1"])+" | "+str(report["value2"])+" | "+str(report["value3"])) 239 | if str(r) == "": 240 | pd.update({pd.BTCcomm: datetime.datetime.today(), pd.pnl: pnl}).where((pd.stock == prospect.stock) & 241 | (pd.strike == prospect.strike) & 242 | (pd.expireDate == prospect.expireDate)).execute() 243 | 244 | except Exception as e: 245 | self.log.logger.error( 246 | " Put Sell Strategy comm closing IFTTT error") 247 | self.log.logger.error(e) 248 | except Exception as e: 249 | self.log.logger.error( 250 | " Put Sell Strategy communicator closing error") 251 | self.log.logger.error(e) 252 | 253 | def diff_month(self, start_date, end_date): 254 | qty_month = ((end_date.year - start_date.year) * 12) + (end_date.month - start_date.month) 255 | return qty_month 256 | 257 | def updatePricingProspects(self): 258 | from rrlib.rrDb import ProspectData as pd 259 | from rrlib.rrDb import OptionData as od 260 | 261 | try: 262 | for pt in pd.select().where(pd.BTCcomm.is_null()): 263 | self.log.logger.debug(" Put Sell Strategy updating prices for: " + str(pt)) 264 | timestamp = od.select(od.timestamp).where((od.stock == pt.stock) & ( 265 | od.strike == pt.strike) & (od.expireDate == pt.expireDate)).get().timestamp 266 | # TODO if timestamp > 1 dia entonces actualizar manualmente la opción y recargar 267 | if ((datetime.datetime.now()-datetime.timedelta(days=1)) > timestamp): 268 | monthdif = int(self.diff_month(datetime.datetime.today(), pt.expireDate)) 269 | self.db.getOption(pt.stock, int(pt.strike), monthdif) 270 | currentPrice = od.select(od.price).where((od.stock == pt.stock) & ( 271 | od.strike == pt.strike) & (od.expireDate == pt.expireDate)).get().price 272 | pnl = str(round(float(pt.contracts) * 273 | (float(pt.price)-float(pt.currentPrice))*100-float(pt.contracts)*2, 2)) 274 | self.log.logger.debug(" Put Sell Strategy updating prices for: " + pt.stock+" current price:"+currentPrice + 275 | " old price:"+pt.currentPrice) 276 | pd.update({pd.currentPrice: currentPrice, pd.pnl: pnl}).where((pd.stock == pt.stock) & 277 | (pd.strike == pt.strike) & 278 | (pd.expireDate == pt.expireDate)).execute() 279 | except Exception as e: 280 | self.log.logger.error( 281 | " Put Sell Strategy pricing update error") 282 | self.log.logger.error(e) 283 | 284 | def printAllProspects(self): 285 | sys.path.append(os.path.join(os.path.dirname(__file__), '..')) 286 | from rrlib.rrDb import ProspectData as pdata 287 | df = pd.DataFrame(list(pdata.select().order_by(pdata.pnl.desc()).dicts())) 288 | return df 289 | 290 | def printOpenProspects(self): 291 | sys.path.append(os.path.join(os.path.dirname(__file__), '..')) 292 | from rrlib.rrDb import ProspectData as pdata 293 | df = pd.DataFrame(list(pdata.select().where( 294 | pdata.BTCcomm.is_null()).order_by(pdata.pnl.desc()).dicts())) 295 | return df 296 | 297 | def printClosedProspects(self): 298 | sys.path.append(os.path.join(os.path.dirname(__file__), '..')) 299 | from rrlib.rrDb import ProspectData as pdata 300 | df = pd.DataFrame(list(pdata.select().where( 301 | pdata.BTCcomm.is_null(False)).order_by(pdata.pnl.desc()).dicts())) 302 | return df 303 | 304 | def sendDailyReport(self): 305 | from rrlib.rrDb import ProspectData as pd 306 | from rrlib.rrTelegram import rrTelegram 307 | from rrlib.rrIFTTT import rrIFTTT 308 | pnlClosed = 0 309 | numClosed = 0 310 | pnlOpen = 0 311 | numOpen = 0 312 | try: 313 | for pt in pd.select().where(pd.BTCcomm.is_null(False)): 314 | pnlClosed = pnlClosed + float(pt.pnl) 315 | numClosed = numClosed + 1 316 | for pt in pd.select().where(pd.BTCcomm.is_null()): 317 | pnlOpen = pnlOpen + float(pt.pnl) 318 | numOpen = numOpen + 1 319 | 320 | report = {} 321 | report["value1"] = "PNL Closed: $" +\ 322 | str(round(pnlClosed, 2))+" with "+str(numClosed)+" prospects" 323 | report["value2"] = "PNL Open: $" +\ 324 | str(round(pnlOpen, 2))+" with "+str(numOpen)+" prospects" 325 | report["value3"] = "PNL Total: $"+str( 326 | round(pnlClosed + pnlOpen, 2))+" with "+str(numClosed+numOpen)+" prospects" 327 | self.log.logger.info("\n\n -------------------DAILY REPORT-------------------\n "+str( 328 | report["value1"])+"\n "+str(report["value2"])+"\n "+str(report["value3"]) + 329 | "\n ------------------DAILY REPORT-------------------\n") 330 | try: 331 | r = rrIFTTT().send(report) 332 | rrTelegram().sendMessage( 333 | str(report["value1"])+" | "+str(report["value2"])+" | "+str(report["value3"])) 334 | if str(r) == "": 335 | pass 336 | except Exception as e: 337 | self.log.logger.error( 338 | " Put Sell Strategy daily report communication error") 339 | self.log.logger.error(e) 340 | except Exception as e: 341 | self.log.logger.error( 342 | " Put Sell Strategy sending daily report error") 343 | self.log.logger.error(e) 344 | -------------------------------------------------------------------------------- /rrlib/rrDb.py: -------------------------------------------------------------------------------- 1 | from tqdm import tqdm 2 | import time 3 | import os 4 | import sys 5 | import datetime 6 | import peewee as pw 7 | import pandas as pd 8 | # !/usr/bin/env python3 9 | # -*- coding: utf-8 -*- 10 | """ 11 | Created on 07 05 2019 12 | robotRay server v1.0 13 | @author: camilorojas 14 | 15 | Database implementation in SQLLite3 16 | 17 | Entities: 18 | - Stocks to watch 19 | - Stock KPI's to monitor from Finviz - updated daily 20 | - Intraday performance - updated every 5 mins overwritten 21 | - Option Put valuation for operational months - updated every 3 hours - 22 | tracking months current + 3-8 months 23 | - Triggers for correct intraday action with monthly recommendation 24 | - Dates for expiration for Y+5 of option puts 25 | 26 | """ 27 | 28 | 29 | sys.path.append(os.path.join(os.path.dirname(__file__), '..')) 30 | db = pw.SqliteDatabase('rrDb.db') 31 | 32 | 33 | class rrDbManager: 34 | 35 | def __init__(self): 36 | # Starting common services 37 | from rrlib.rrLogger import logger, TqdmToLogger 38 | from rrlib.rrPortfolio import rrPortfolio 39 | # Get logging service 40 | self.log = logger() 41 | self.tqdm_out = TqdmToLogger(self.log.logger) 42 | self.log.logger.debug(" DB Manager starting. ") 43 | # start portfolio 44 | self.portfolio = rrPortfolio() 45 | # starting ini parameters 46 | import configparser 47 | config = configparser.ConfigParser() 48 | config.read("rrlib/robotRay.ini") 49 | # db filename to confirm it exists 50 | self.dbFilename = config.get('DB', 'filename') 51 | self.initializeDb() 52 | # Get list of stocks to track 53 | self.stocks = config.get('stocks', 'stocks') 54 | # Get datsource from pubic or ib 55 | self.source = config.get('datasource', 'source') 56 | # Get verbose option boolean 57 | self.verbose = config.get('datasource', 'verbose') 58 | 59 | def initializeDb(self): 60 | Stock.create_table() 61 | StockData.create_table() 62 | ExpirationDate.create_table() 63 | OptionData.create_table() 64 | IntradayStockData.create_table() 65 | ProspectData.create_table() 66 | ServerRun.create_table() 67 | 68 | def startServerRun(self): 69 | sr = ServerRun(startup=datetime.datetime.now()) 70 | sr.save() 71 | 72 | def updateServerRun(self, lastStockDataUpdate="", lastOptionDataUpdate="", 73 | lastThinkUpdate="", telegramBotEnabled="", runCycles="", prospectsFound="", pnl=""): 74 | sr = ServerRun.select().order_by(ServerRun.id.desc()).get() 75 | if telegramBotEnabled != "": 76 | sr.telegramBotEnabled = "Yes" 77 | if lastStockDataUpdate != "": 78 | sr.lastStockDataUpdate = lastStockDataUpdate 79 | if lastOptionDataUpdate != "": 80 | sr.lastOptionDataUpdate = lastOptionDataUpdate 81 | if lastThinkUpdate != "": 82 | sr.lastThinkUpdate = lastThinkUpdate 83 | if sr.runCycles == "": 84 | sr.runCycles = "1" 85 | else: 86 | sr.runCycles = str(int(sr.runCycles)+1) 87 | if prospectsFound != "": 88 | if sr.prospectsFound == "": 89 | sr.prospectsFound = "1" 90 | else: 91 | sr.prospectsFound = str(int(sr.prospectsFound)+1) 92 | if pnl != "": 93 | if sr.pnl == "": 94 | sr.pnl = pnl 95 | else: 96 | sr.pnl = str(float(sr.pnl)+pnl) 97 | sr.save() 98 | 99 | def getServerRun(self): 100 | sr = pd.DataFrame(ServerRun.select().order_by(ServerRun.id.desc()).dicts()) 101 | return sr.head(1) 102 | 103 | def isDbInUse(self): 104 | try: 105 | status = db.connect() 106 | except Exception: 107 | status = False 108 | return status 109 | 110 | def getSource(self): 111 | return self.source 112 | 113 | def initializeStocks(self): 114 | self.log.logger.debug(" DB Manager initializing Stock Table. ") 115 | Stock.drop_table(True) 116 | Stock.create_table() 117 | stockList = [x.strip() for x in self.stocks.split(',')] 118 | self.log.logger.debug(stockList) 119 | stocks = [] 120 | for st in stockList: 121 | stocks.append({'ticker': st}) 122 | self.log.logger.debug(stocks) 123 | Stock.insert_many(stocks).execute() 124 | 125 | def getStocks(self): 126 | df = pd.DataFrame(columns=['ticker']) 127 | try: 128 | for stock in Stock.select(): 129 | df = df.append({'ticker': stock.ticker}, ignore_index=True) 130 | except Exception as e: 131 | self.log.logger.error( 132 | " DB Manager Error. Get Stock Table without table, try initializing. ") 133 | self.log.logger.error(e) 134 | return df 135 | 136 | def getStockData(self): 137 | from rrlib.rrDataFetcher import StockDataFetcher as stckFetcher 138 | from rrlib.rrDataFetcher import OptionDataFetcher as optFetcher 139 | from random import randint 140 | from pprint import pprint 141 | self.log.logger.debug(" DB Manager Get Stock data. ") 142 | StockData.create_table() 143 | try: 144 | # for stock in tqdm(Stock.select(), file=self.tqdm_out, desc=" Getting Stock Data:", unit="Stock", ascii=False, ncols=120, leave=False): 145 | for stock in tqdm(Stock.select(), desc=" Getting Stock Data", unit="Stock", ascii=False, ncols=120, leave=False): 146 | time.sleep(randint(2, 5)) 147 | self.log.logger.debug( 148 | " DB Manager Attempting to retreive data for "+stock.ticker) 149 | try: 150 | dataFetcher = stckFetcher(stock.ticker).getData() 151 | price = float(dataFetcher.iloc[70]['value']) 152 | if dataFetcher.iloc[9]['value'] == "-": 153 | perfWeek = 0 154 | else: 155 | perfWeek = float( 156 | dataFetcher.iloc[9]['value'].strip('%'))/100 157 | if dataFetcher.iloc[15]['value'] == "-": 158 | perfMonth = 0 159 | else: 160 | perfMonth = float( 161 | dataFetcher.iloc[15]['value'].strip('%'))/100 162 | if dataFetcher.iloc[21]['value'] == "-": 163 | perfQuarter = 0 164 | else: 165 | perfQuarter = float( 166 | dataFetcher.iloc[21]['value'].strip('%'))/100 167 | # strikePctg import 168 | import configparser 169 | config = configparser.ConfigParser() 170 | config.read("rrlib/robotRay.ini") 171 | strikePctg = float(config['sellputstrategy']['strikePctg']) 172 | strike = int((price*0.3+price/(1+perfWeek)*0.3+price/(1+perfMonth) 173 | * 0.3+price/(1+perfQuarter)*0.1)*(1-strikePctg)) 174 | # round 175 | if strike < 10: 176 | strike = round(strike, 0) 177 | elif strike < 1000: 178 | strike = round(strike, -1) 179 | elif strike > 1000: 180 | strike = round(strike, -2) 181 | try: 182 | strikes = optFetcher(stock.ticker).getStrikes() 183 | if strike not in strikes.values: 184 | 185 | strike = int(min(strikes.values, key=lambda x: abs(x-strike))) 186 | except Exception: 187 | self.log.logger.warning(" Exception with strikes for:"+stock.ticker) 188 | row = {'stock': stock.ticker, 'strike': str(int(strike)), 'timestamp': str(datetime.datetime.now()), 189 | 'price': dataFetcher.iloc[70]['value'], 'prevClose': dataFetcher.iloc[64]['value'], 190 | 'salesqq': dataFetcher.iloc[54]['value'], 'sales5y': dataFetcher.iloc[48]['value'], 191 | 'beta': dataFetcher.iloc[45]['value'], 'roe': dataFetcher.iloc[36]['value'], 192 | 'roi': dataFetcher.iloc[43]['value'], 'recom': dataFetcher.iloc[71]['value'], 193 | 'earnDate': dataFetcher.iloc[67]['value'], 'targetPrice': dataFetcher.iloc[31]['value'], 194 | 'shortFloat': dataFetcher.iloc[20]['value'], 'shortRatio': dataFetcher.iloc[26]['value'], 195 | 'w52High': dataFetcher.iloc[44]['value'], 'w52Low': dataFetcher.iloc[50]['value'], 196 | 'relVolume': dataFetcher.iloc[58]['value'], 'sma20': dataFetcher.iloc[72]['value'], 197 | 'sma50': dataFetcher.iloc[73]['value'], 'sma200': dataFetcher.iloc[74]['value'], 198 | 'perfDay': dataFetcher.iloc[76]['value'], 'perfWeek': dataFetcher.iloc[9]['value'], 199 | 'perfMonth': dataFetcher.iloc[15]['value'], 'perfQuarter': dataFetcher.iloc[21]['value'], 200 | 'perfHalfYear': dataFetcher.iloc[27]['value'], 'perfYear': dataFetcher.iloc[32]['value'], 201 | 'perfYTD': dataFetcher.iloc[39]['value']} 202 | self.log.logger.debug(" DB Manager Built row:"+str(row)) 203 | StockData.insert(row).execute() 204 | self.log.logger.debug( 205 | " DB Manager DONE Data retreived for "+stock.ticker) 206 | if (self.verbose == "Yes"): 207 | tqdm.write(str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')) 208 | + " - rrLog - " 209 | + "INFO - DONE - Data retreived for " + 210 | stock.ticker+", strike: "+str(strike) 211 | + ", price:$" + 212 | str(price) + 213 | ", sales growth QtQ:"+str(dataFetcher.iloc[54]['value']) 214 | + ", earnings date: "+str(dataFetcher.iloc[67]['value'])+", target price:$"+str(dataFetcher.iloc[31]['value'])) 215 | except Exception as e: 216 | self.log.logger.error( 217 | " DB Manager Error failed to fetch data for:"+stock.ticker) 218 | self.log.logger.error(e) 219 | except Exception as e: 220 | self.log.logger.error( 221 | " DB Manager Error failed to fetch data. Please check internet connectivity or finviz.com for availability." 222 | " Using cached version.") 223 | self.log.logger.error(e) 224 | return False 225 | # db.close() 226 | return True 227 | 228 | def getIntradayData(self): 229 | from random import randint 230 | sys.path.append(os.path.join(os.path.dirname(__file__), '..')) 231 | from rrlib.rrDataFetcher import StockDataFetcher as stckFetcher 232 | IntradayStockData.create_table() 233 | try: 234 | for stock in tqdm(Stock.select(), desc="Getting Stock Data:", unit="Stock", ascii=False, ncols=120, leave=False): 235 | time.sleep(randint(2, 5)) 236 | self.log.logger.debug( 237 | " DB Manager Attempting to retreive intraday data for "+stock.ticker) 238 | try: 239 | dataFetcher = stckFetcher(stock.ticker).getIntradayData() 240 | # Calculate kpi 241 | pctChange = round(float(dataFetcher.iloc[0]['%Change']), 3) 242 | try: 243 | higherOptionData = float(OptionData.select(OptionData.kpi).where( 244 | (OptionData.stock == stock.ticker) & 245 | (OptionData.timestamp > (datetime.datetime.now()-datetime.timedelta(days=4)))) 246 | .order_by(OptionData.kpi.desc()).get().kpi) 247 | except Exception: 248 | higherOptionData = 0 249 | try: 250 | salesQtQ = float((StockData.select(StockData.salesqq).where( 251 | StockData.stock == stock.ticker).order_by(StockData.id.desc()).get().salesqq).strip('%'))/100 252 | except Exception: 253 | salesQtQ = 0 254 | sma200 = float((StockData.select(StockData.sma200).where( 255 | StockData.stock == stock.ticker).order_by(StockData.id.desc()).get().sma200).strip('%'))/100 256 | kpi = round(-22*pctChange*0.5+0.1*higherOptionData + 257 | salesQtQ*0.3+sma200*0.1+0.1*2*salesQtQ, 3) 258 | row = {'stock': stock.ticker, 'price': dataFetcher.iloc[0]['price'], 'pctChange': pctChange, 259 | 'pctVol': dataFetcher.iloc[0]['%Volume'], 'timestamp': str(datetime.datetime.now()), 'kpi': kpi} 260 | # self.log.logger.info(" DB Manager Built row:"+str(row)) 261 | IntradayStockData.insert(row).on_conflict(conflict_target=[IntradayStockData.stock], update={ 262 | IntradayStockData.price: dataFetcher.iloc[0]['price'], IntradayStockData.pctChange: pctChange, 263 | IntradayStockData.pctVol: dataFetcher.iloc[0]['%Volume'], IntradayStockData.timestamp: str(datetime.datetime.now()), 264 | IntradayStockData.kpi: kpi}).execute() 265 | if (self.verbose == "Yes"): 266 | tqdm.write(str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')) 267 | + " - rrLog - " + 268 | "INFO - DONE - Stock intraday "+stock.ticker + 269 | ", price:$"+str(dataFetcher.iloc[0]['price'])+", % price chng:" + str(pctChange) + 270 | "%, % volume chng:"+str(dataFetcher.iloc[0]['%Volume']) + 271 | "%, kpi:"+str(kpi)) 272 | self.log.logger.debug( 273 | " DB Manager intraday data retreived for "+stock.ticker) 274 | except Exception as e: 275 | self.log.logger.warning( 276 | " DB Manager Error failed to fetch intraday data for:"+stock.ticker+". Or several process running at the same time") 277 | self.log.logger.warning(e) 278 | except Exception as e: 279 | self.log.logger.error( 280 | " DB Manager Error failed to fetch intraday data. Please check internet connectivity " 281 | "or yahoo.com for availability. Using cached verssion.") 282 | self.log.logger.error(e) 283 | return False 284 | return True 285 | 286 | def initializeExpirationDate(self): 287 | def third_friday(which_weekday_in_month, day, month, year): # third friday sept 2019 288 | dt = datetime.date(year, month, 1) 289 | dow_lst = [] 290 | while dt.weekday() != day: 291 | dt = dt + datetime.timedelta(days=1) 292 | while dt.month == month: 293 | dow_lst.append(dt) 294 | dt = dt + datetime.timedelta(days=7) 295 | return dow_lst[which_weekday_in_month] 296 | 297 | self.log.logger.debug( 298 | " DB Manager initializing Expiration Date Table. ") 299 | ExpirationDate.drop_table(True) 300 | ExpirationDate.create_table() 301 | month = datetime.datetime.today().month 302 | year = datetime.datetime.today().year 303 | self.log.logger.debug( 304 | " Populating with 24 months after this month:"+str(month)+" "+str(year)) 305 | x = 1 # iterator 306 | while x < 24: 307 | if month == 12: 308 | year = year+1 309 | month = 1 310 | else: 311 | month = month+1 312 | ExpirationDate.insert( 313 | {'date': third_friday(2, 4, month, year)}).execute() 314 | x = x+1 315 | 316 | def completeExpirationDate(self, monthYear): 317 | completeDate = "" 318 | try: 319 | self.log.logger.debug(" Completing expiration date "+monthYear) 320 | retreiveDate = ExpirationDate.select().where( 321 | ExpirationDate.date.contains(monthYear)).get().date 322 | completeDate = retreiveDate.strftime("%y%m%d") 323 | except Exception as e: 324 | self.log.logger.error( 325 | " Error completing expiration date "+monthYear) 326 | self.log.logger.error(e) 327 | return False 328 | return completeDate 329 | 330 | def getDatebyMonth(self, month): 331 | try: 332 | self.log.logger.debug(" Completing expiration date for "+str(month)) 333 | retreiveDate = ExpirationDate.select().where( 334 | ExpirationDate.id == int(month)).get().date 335 | completeDate = retreiveDate.strftime("%Y-%m-%d") 336 | except Exception as e: 337 | self.log.logger.error( 338 | " Error completing expiration date "+month) 339 | self.log.logger.error(e) 340 | return False 341 | return completeDate 342 | 343 | # getOptionData batch getter for stock option data 344 | def getOptionData(self): 345 | from random import randint 346 | # startup 347 | self.log.logger.info(" DB Manager Get Option data. ") 348 | # create table if not created 349 | OptionData.create_table() 350 | try: 351 | for stock in tqdm(Stock.select(), desc="Getting Option Data", unit="Stock", ascii=False, ncols=120, leave=False): 352 | month = 3 353 | time.sleep(randint(2, 5)) 354 | self.log.logger.debug(stock.ticker+" "+str(month)) 355 | # Get stock data for Option analysis 356 | stkdata = StockData.select().where( 357 | StockData.stock == stock.ticker).order_by(StockData.id.desc()).get() 358 | strike = int(stkdata.strike) 359 | mbar = tqdm(total=6, desc="Getting Month Data: ", 360 | unit="Month", ascii=False, ncols=120, leave=False) 361 | if(self.verbose == "Yes"): 362 | tqdm.write(str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')) 363 | + " - rrLog - INFO - Retreving option data for "+stock.ticker) 364 | while month < 9: 365 | try: 366 | # get strike info from stock data 367 | self.log.logger.debug(" DB Manager Attempting to retreive data for option " + 368 | stock.ticker+" month "+str(month)+" at strike:"+str(strike)) 369 | self.getOption(stock.ticker, strike, month) 370 | """if (self.verbose == "Yes"): 371 | tqdm.write(str(datetime.datetime.now().strftime( 372 | '%Y-%m-%d %H:%M:%S')) 373 | + " - rrLog - INFO - DONE - Option data loaded for "+stock.ticker 374 | + ", strike:$"+str(strike)+", for month "+str(month))""" 375 | self.log.logger.debug(" DONE - Option data loaded: " + 376 | stock.ticker+" for month "+str(month)) 377 | month = month+1 378 | mbar.update(1) 379 | except Exception as e: 380 | self.log.logger.warning( 381 | " DB Manager Error failed to fetch data. Possibly no Stock Data loaded. Or several process running at the same time") 382 | self.log.logger.warning(e) 383 | month = month+1 384 | mbar.close() 385 | except Exception as e: 386 | exc_type, exc_obj, exc_tb = sys.exc_info() 387 | fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] 388 | self.log.logger.error(exc_type, fname, exc_tb.tb_lineno) 389 | self.log.logger.error(" DB Manager error." + 390 | str(e)) 391 | self.log.logger.error( 392 | " DB Manager Error failed to fetch data. Please check internet connectivity or yahoo.com for availability. Using cached verssion.") 393 | return False 394 | return True 395 | 396 | # getOption single getter for stock option data 397 | def getOption(self, stock, strike, month): 398 | from rrlib.rrDataFetcher import OptionDataFetcher as optFetcher 399 | import calendar 400 | # startup 401 | self.log.logger.debug(" DB Manager Get Option data. ") 402 | # create table if not created 403 | OptionData.create_table() 404 | # R value from portfolio 405 | R = float(self.portfolio.R) 406 | # minpremium from portfolio 407 | monthlyPremium = float(self.portfolio.monthlyPremium) 408 | # BP from portfolio 409 | BP = float(self.portfolio.BP) 410 | stkdata = StockData.select().where( 411 | StockData.stock == stock).order_by(StockData.id.desc()).get() 412 | stockPrice = float(stkdata.price) 413 | if(stkdata.earnDate == "-"): 414 | EdateMonth = "NA" 415 | else: 416 | EdateMonth = list(calendar.month_abbr).index(stkdata.earnDate[:3]) 417 | if(self.verbose == "Yes"): 418 | self.log.logger.debug(" Retreving option data for "+stock + 419 | ", month "+str(month)+", strike: $"+str(strike)) 420 | try: 421 | dataFetcher = optFetcher(stock).getData(month, strike) 422 | self.log.logger.debug(dataFetcher) 423 | if len(dataFetcher.index) > 0: 424 | # calculate number of contracts, use price if its within bid-ask otherwise use midpoint 425 | price = float(dataFetcher.iloc[10]['value']) 426 | bid = float(dataFetcher.iloc[2]['value']) 427 | ask = float(dataFetcher.iloc[3]['value']) 428 | # set price mid ask bid if price below bid or price above ask and bid ask above 0 429 | if (bid > 0 and ask > 0) and (price < bid or price > ask): 430 | price = (bid + ask)/2 431 | if price > 0: 432 | # with R = 100 then price must be > $6.6, R200=$13.3, R300=20 433 | contracts = round(2*R/(50*price)) 434 | else: 435 | contracts = 0 436 | # calculate worst case on stock ownership 437 | stockOwnership = contracts*strike*100-price*100 438 | # calculate BP withheld to match 439 | withheldBP = max(100*contracts*(0.25*stockPrice+price * 440 | (stockPrice-strike)), 100*contracts*(price+0.1*stockPrice)) 441 | # calculate R potential from selling 442 | Rpotential = 100*contracts*price/R/2 443 | # calculate expected premium 444 | expectedPremium = stockPrice*month*monthlyPremium 445 | # kpi checks for month of earnings, number of contracts, r potential, reduce for buying power 446 | kpi = 0.5 if price > expectedPremium else 0 # pricing premium 447 | if contracts < 10: # contract numbers 448 | kpi = kpi+0.1 449 | elif 10 < contracts < 20: 450 | kpi = kpi+0.05 451 | kpi = kpi+Rpotential*0.05 # r potential 452 | # reduce kpi based on stock ownership vs buying power 453 | kpi = kpi-0.1*(stockOwnership/BP) 454 | if (EdateMonth != "NA"): 455 | if (EdateMonth % 3 == (datetime.datetime.now().month+month) % 3): 456 | kpi = 0 457 | row = {'stock': stock, 'strike': str(strike), 'price': round(price, 3), 458 | 'expireDate': datetime.datetime.strptime(dataFetcher.iloc[5]['value'], '%Y-%m-%d'), 459 | 'openPrice': dataFetcher.iloc[1]['value'], 460 | "bid": str(bid), "ask": str(ask), 461 | "dayRange": dataFetcher.iloc[6]['value'], "volume": dataFetcher.iloc[8]['value'], 462 | "openInterest": dataFetcher.iloc[9]['value'], 'timestamp': datetime.datetime.now(), 463 | 'contracts': str(contracts), 'stockOwnership': str(round(stockOwnership, 3)), 464 | 'withheldBP': str(round(withheldBP, 3)), 465 | 'Rpotential': str(round(Rpotential, 3)), 'kpi': str(round(kpi, 3)), 466 | 'expectedPremium': str(round(expectedPremium, 3))} 467 | self.log.logger.debug( 468 | " DB Manager Built row: strike="+str(strike)+" row:"+str(row)) 469 | OptionData.insert(row).on_conflict(conflict_target=[OptionData.stock, OptionData.expireDate, OptionData.strike], 470 | update={OptionData.price: round(price, 3), 471 | OptionData.openPrice: dataFetcher.iloc[1]['value'], 472 | OptionData.bid: dataFetcher.iloc[2]['value'], 473 | OptionData.ask: dataFetcher.iloc[3]['value'], 474 | OptionData.dayRange: dataFetcher.iloc[6]['value'], 475 | OptionData.volume: dataFetcher.iloc[8]['value'], 476 | OptionData.openInterest: dataFetcher.iloc[9]['value'], 477 | OptionData.timestamp: datetime.datetime.now(), 478 | OptionData.contracts: str(contracts), 479 | OptionData.stockOwnership: str(round(stockOwnership, 3)), 480 | OptionData.withheldBP: str(round(withheldBP, 3)), 481 | OptionData.Rpotential: str(round(Rpotential, 3)), 482 | OptionData.kpi: str(round(kpi, 3)), 483 | OptionData.expectedPremium: str(round(expectedPremium, 3))}).execute() 484 | if (self.verbose == "Yes"): 485 | tqdm.write(str(datetime.datetime.now().strftime( 486 | '%Y-%m-%d %H:%M:%S')) 487 | + " - rrLog - INFO - DONE - Option data loaded for "+stock 488 | + ", strike:$"+str(strike)+", for month "+str(month)) 489 | else: 490 | if (self.verbose == "Yes"): 491 | tqdm.write(str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')) 492 | + " - rrLog - INFO - NOT FOUND - No option for "+stock+", strike:$"+str(strike) + 493 | ", for month "+str(month)) 494 | except Exception as e: 495 | self.log.logger.warning( 496 | " DB Manager Error failed to fetch data. Possibly no Stock Data loaded. Or several process running at the same time") 497 | self.log.logger.warning(e) 498 | 499 | def saveProspect(self, stock, strike, expireDate, price, contracts, stockOwnership, 500 | rPotential, kpi, color): 501 | try: 502 | ProspectData.create_table() 503 | today = datetime.datetime.today() 504 | row = { 505 | "stock": stock, 506 | "dateIdentified": today, 507 | "strike": strike, 508 | "expireDate": expireDate, 509 | "price": price, 510 | "contracts": contracts, 511 | "stockOwnership": stockOwnership, 512 | "Rpotential": rPotential, 513 | "kpi": kpi, 514 | "STOcomm": None, 515 | "BTCcomm": None, 516 | "currentPrice": price, 517 | "color": color, 518 | "pnl": None 519 | } 520 | ProspectData.insert(row).on_conflict(conflict_target=[ProspectData.stock, ProspectData.strike, ProspectData.expireDate], 521 | update={ProspectData.currentPrice: price}).execute() 522 | except Exception: 523 | self.log.logger.error( 524 | " DB Manager error saving prospect." + Exception.with_traceback) 525 | # db.close() 526 | return True 527 | 528 | # Print functions for console or dataframe return from stock, intraday, option list 529 | 530 | def printStocks(self): 531 | df = pd.DataFrame(list(StockData.select(StockData.stock, StockData.price, StockData.prevClose, 532 | StockData.perfDay, StockData.strike, StockData.salesqq, 533 | StockData.sales5y, StockData.earnDate, StockData.targetPrice, 534 | StockData.perfMonth, StockData.perfQuarter, StockData.perfYTD, 535 | StockData.perfYear).order_by(StockData.timestamp.desc()).dicts())) 536 | return df.head(len(self.getStocks().index)) 537 | 538 | def printIntradayStocks(self): 539 | df = pd.DataFrame(list(IntradayStockData.select(IntradayStockData.stock, IntradayStockData.price, 540 | IntradayStockData.pctChange, IntradayStockData.pctVol, 541 | IntradayStockData.kpi).order_by(IntradayStockData.kpi.desc()).dicts())) 542 | return df 543 | 544 | def printOptions(self): 545 | df = pd.DataFrame(list(OptionData.select(OptionData.stock, OptionData.kpi, OptionData.strike, OptionData.price, 546 | OptionData.expireDate, OptionData.contracts, OptionData.volume, 547 | OptionData.openInterest).where( 548 | (OptionData.kpi != "0") 549 | & (OptionData.timestamp > (datetime.datetime.now()-datetime.timedelta(days=3)))) 550 | .order_by(OptionData.kpi.desc()).dicts())) 551 | return df 552 | 553 | 554 | # Data classes from peewee 555 | # Stock entity 556 | 557 | 558 | class Stock(pw.Model): 559 | ticker = pw.CharField(unique=True) 560 | 561 | class Meta: 562 | database = db 563 | db_table = "stock" 564 | 565 | # Expiration fridays for options entity 566 | 567 | 568 | class ExpirationDate(pw.Model): 569 | date = pw.DateField(unique=True) 570 | 571 | class Meta: 572 | database = db 573 | db_table = "expirationDate" 574 | 575 | # Stock Data entity 576 | # updated daily 577 | 578 | 579 | class StockData(pw.Model): 580 | stock = pw.CharField() 581 | strike = pw.CharField() 582 | timestamp = pw.DateTimeField() 583 | price = pw.CharField() 584 | prevClose = pw.CharField() 585 | salesqq = pw.CharField() 586 | sales5y = pw.CharField() 587 | beta = pw.CharField() 588 | roe = pw.CharField() 589 | roi = pw.CharField() 590 | recom = pw.CharField() 591 | earnDate = pw.CharField() 592 | targetPrice = pw.CharField() 593 | shortFloat = pw.CharField() 594 | shortRatio = pw.CharField() 595 | w52High = pw.CharField() 596 | w52Low = pw.CharField() 597 | relVolume = pw.CharField() 598 | sma20 = pw.CharField() 599 | sma50 = pw.CharField() 600 | sma200 = pw.CharField() 601 | perfDay = pw.CharField() 602 | perfWeek = pw.CharField() 603 | perfMonth = pw.CharField() 604 | perfQuarter = pw.CharField() 605 | perfHalfYear = pw.CharField() 606 | perfYear = pw.CharField() 607 | perfYTD = pw.CharField() 608 | 609 | class Meta: 610 | database = db 611 | db_table = "stockData" 612 | 613 | # Option Data entity 614 | # updated every 3 hours 615 | 616 | 617 | class OptionData(pw.Model): 618 | stock = pw.CharField() 619 | strike = pw.CharField() 620 | price = pw.CharField() 621 | expireDate = pw.DateField() 622 | openPrice = pw.CharField() 623 | bid = pw.CharField() 624 | ask = pw.CharField() 625 | dayRange = pw.CharField() 626 | volume = pw.CharField() 627 | openInterest = pw.CharField() 628 | timestamp = pw.DateTimeField() 629 | contracts = pw.CharField() 630 | stockOwnership = pw.CharField() 631 | withheldBP = pw.CharField() 632 | Rpotential = pw.CharField() 633 | kpi = pw.CharField() 634 | expectedPremium = pw.CharField() 635 | 636 | class Meta: 637 | database = db 638 | db_table = "optionData" 639 | primary_key = pw.CompositeKey("stock", "expireDate", "strike") 640 | 641 | # Intraday Stock Data 642 | # updated 5 mins overwrite 643 | 644 | 645 | class IntradayStockData(pw.Model): 646 | stock = pw.CharField(unique=True) 647 | price = pw.CharField() 648 | pctChange = pw.CharField() 649 | pctVol = pw.CharField() 650 | timestamp = pw.DateTimeField() 651 | kpi = pw.CharField() 652 | 653 | class Meta: 654 | database = db 655 | db_table = "intradayStockData" 656 | 657 | # Prospect Oppty data 658 | 659 | 660 | class ProspectData(pw.Model): 661 | stock = pw.CharField() 662 | dateIdentified = pw.DateField() 663 | strike = pw.CharField() 664 | expireDate = pw.DateField() 665 | price = pw.CharField() 666 | contracts = pw.CharField() 667 | stockOwnership = pw.CharField() 668 | Rpotential = pw.CharField() 669 | kpi = pw.CharField() 670 | STOcomm = pw.DateField(null=True) 671 | BTCcomm = pw.DateField(null=True) 672 | currentPrice = pw.CharField() 673 | color = pw.CharField() 674 | pnl = pw.CharField(null=True) 675 | 676 | class Meta: 677 | database = db 678 | db_table = "prospectData" 679 | primary_key = pw.CompositeKey("stock", "strike", "expireDate") 680 | 681 | 682 | class ServerRun(pw.Model): 683 | startup = pw.DateTimeField() 684 | lastThinkUpdate = pw.DateTimeField(null=True) 685 | lastStockDataUpdate = pw.DateTimeField(null=True) 686 | lastOptionDataUpdate = pw.DateTimeField(null=True) 687 | runCycles = pw.CharField(default="") 688 | telegramBotEnabled = pw.CharField(null=True) 689 | prospectsFound = pw.CharField(default="") 690 | pnl = pw.CharField(default="") 691 | 692 | class Meta: 693 | database = db 694 | db_table = "serverRun" 695 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------