speterlin-stocks 1.0.6__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- speterlin_stocks-1.0.6/LICENSE +21 -0
- speterlin_stocks-1.0.6/PKG-INFO +25 -0
- speterlin_stocks-1.0.6/README.md +153 -0
- speterlin_stocks-1.0.6/pyproject.toml +33 -0
- speterlin_stocks-1.0.6/setup.cfg +4 -0
- speterlin_stocks-1.0.6/speterlin_stocks/__init__.py +16 -0
- speterlin_stocks-1.0.6/speterlin_stocks/module1.py +2151 -0
- speterlin_stocks-1.0.6/speterlin_stocks.egg-info/PKG-INFO +25 -0
- speterlin_stocks-1.0.6/speterlin_stocks.egg-info/SOURCES.txt +10 -0
- speterlin_stocks-1.0.6/speterlin_stocks.egg-info/dependency_links.txt +1 -0
- speterlin_stocks-1.0.6/speterlin_stocks.egg-info/requires.txt +15 -0
- speterlin_stocks-1.0.6/speterlin_stocks.egg-info/top_level.txt +1 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) [2025] [Sebastian B. Peterlin]
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: speterlin-stocks
|
|
3
|
+
Version: 1.0.6
|
|
4
|
+
Summary: A Python package for a suite of quant-trading opportunities in stocks with API integration: Alpaca brokerage for storing USD assets and margin trading (2x) on exchanges NYSE & NASDAQ, Financial Modeling Prep (FMP) & Google Trends & Yahoo Finance & Google Finance & ExchangeRate & MarketBeat & CrunchBase for data collection, OpenAI & Google Gemini-Pro for AI analysis.
|
|
5
|
+
Author-email: Sebastian Peterlin <speterlin@smartxchange.xyz>
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/speterlin/speterlin-stocks
|
|
8
|
+
Requires-Python: >=3.12
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Requires-Dist: requests>=2.20
|
|
11
|
+
Requires-Dist: numpy
|
|
12
|
+
Requires-Dist: pandas>=2.0
|
|
13
|
+
Requires-Dist: datetime
|
|
14
|
+
Requires-Dist: yfinance==0.1.52
|
|
15
|
+
Requires-Dist: beautifulsoup4
|
|
16
|
+
Requires-Dist: pytrends
|
|
17
|
+
Requires-Dist: openai
|
|
18
|
+
Requires-Dist: langchain-openai
|
|
19
|
+
Requires-Dist: google-generativeai
|
|
20
|
+
Requires-Dist: unidecode
|
|
21
|
+
Requires-Dist: fake-headers
|
|
22
|
+
Requires-Dist: pytz
|
|
23
|
+
Requires-Dist: alpaca-trade-api
|
|
24
|
+
Requires-Dist: twilio
|
|
25
|
+
Dynamic: license-file
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
# speterlin-stocks
|
|
2
|
+
|
|
3
|
+
A Python package for a suite of quant-trading opportunities in stocks with API integration: Alpaca brokerage for storing USD assets and margin trading (2x) on exchanges NYSE & NASDAQ, Financial Modeling Prep (FMP) & Google Trends & Yahoo Finance & Google Finance & ExchangeRate & MarketBeat & CrunchBase for data collection, OpenAI & Google Gemini-Pro for AI analysis.
|
|
4
|
+
|
|
5
|
+
Please see [quant-trading](https://github.com/speterlin/quant-trading) for writing scripts, backtesting, other analysis. Make sure to install package like this (with python>=3.12 and latest pip) in your environment or (recommended) virtual environment:
|
|
6
|
+
```python
|
|
7
|
+
pip install speterlin-stocks
|
|
8
|
+
```
|
|
9
|
+
And then import package like this:
|
|
10
|
+
```python
|
|
11
|
+
import speterlin_stocks.module1 as stocks
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
For the following calls set up your Python virtual environment shell and import packages like in [quant-trading#Python script for Stocks](https://github.com/speterlin/quant-trading?tab=readme-ov-file#python-script-for-stocks-programsstocksstocks_alpaca_your_usernamepy)
|
|
15
|
+
|
|
16
|
+
## Get and analyze your saved Portfolio
|
|
17
|
+
|
|
18
|
+
```python
|
|
19
|
+
portfolio = stocks.get_saved_portfolio_backup("portfolio_rr_50_-50_20_-0.2_0.2_-0.05_2000_100_True_False_False_{'usd': 10000}_2024-12-01_to_" + datetime.now().strftime('%Y-%m-%d'))
|
|
20
|
+
|
|
21
|
+
# View open positions in two rows
|
|
22
|
+
print(str(portfolio['open'].drop(['fmp_24h_vol', 'gtrends_15d', 'rank_rise_d', 'tsl_armed', 'tsl_max_price', 'trade_notes', 'other_notes'], axis=1)) + "\n" + str(portfolio['open'].drop(['position', 'buy_date', 'buy_price', 'balance', 'current_date',\
|
|
23
|
+
'current_price', 'current_roi'], axis=1)))
|
|
24
|
+
|
|
25
|
+
# View sold positions
|
|
26
|
+
portfolio['sold'].tail(40).drop(['fmp_24h_vol', 'rank_rise_d', 'tsl_max_price', 'gtrends_15d'], axis=1)
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
## Check Assets
|
|
30
|
+
|
|
31
|
+
```python
|
|
32
|
+
account, alpaca_open_orders = stocks._fetch_data(stocks.alpaca_api.get_account, params={}, error_str=" - No account from Alpaca on: " + str(datetime.now()), empty_data = {}), stocks._fetch_data(stocks.alpaca_api.list_orders, params={'status': 'open', 'nested': True}, error_str=" - Alpaca open orders error on: " + str(datetime.now()), empty_data=[])
|
|
33
|
+
assets = stocks.get_alpaca_assets(alpaca_account=account, alpaca_open_orders=alpaca_open_orders)
|
|
34
|
+
print(str(assets) + "\nTotal Current Value: " + str(assets['current_value'].sum()) + "\nAccount Equity: " + str(account.equity) + "\nAccount Buying Power: " + str(account.buying_power))
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
## Market calls
|
|
38
|
+
|
|
39
|
+
```python
|
|
40
|
+
last_trade_data = stocks._fetch_data(stocks.alpaca_api.get_latest_trade, params={'symbol': ticker}, error_str=" - No last trade from Alpaca for ticker: " + ticker + " on: " + str(datetime.now()), empty_data = {})
|
|
41
|
+
price, timestamp = last_trade_data.price, last_trade_data.timestamp
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
## USA Holidays
|
|
45
|
+
|
|
46
|
+
```python
|
|
47
|
+
from pandas.tseries.holiday import USFederalHolidayCalendar
|
|
48
|
+
usa_cal = USFederalHolidayCalendar()
|
|
49
|
+
|
|
50
|
+
from pytz import timezone
|
|
51
|
+
|
|
52
|
+
eastern = timezone('US/Eastern')
|
|
53
|
+
|
|
54
|
+
usa_holidays = usa_cal.holidays(start=datetime.now(eastern).replace(month=1, day=1).strftime('%Y-%m-%d'), end=datetime.now(eastern).replace(month=12, day=31).strftime('%Y-%m-%d')).to_pydatetime()
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
## Get and save todays FMP data
|
|
58
|
+
|
|
59
|
+
Single ticker detailed data:
|
|
60
|
+
```python
|
|
61
|
+
ticker = 'GOOGL'
|
|
62
|
+
ticker_data_detailed = stocks._fetch_data(stocks.get_ticker_data_detailed_fmp, params={'ticker': ticker}, error_str=" - No ticker data detailed FMP for ticker: " + ticker + " on: " + str(datetime.now()), empty_data={})
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
All of Alpaca's USA tickers (takes roughly 2-3 hours to save):
|
|
66
|
+
```python
|
|
67
|
+
todays_date = datetime.now()
|
|
68
|
+
stocks.save_usa_alpaca_tickers_fmp_data(date=todays_date.strftime('%Y-%m-%d'))
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
## Retrieve past saved FMP data
|
|
72
|
+
|
|
73
|
+
```python
|
|
74
|
+
df_tickers_2025_11_17 = stocks.get_saved_tickers_data(date='2025-11-17')
|
|
75
|
+
# View the 48 saved data points on GOOGL
|
|
76
|
+
df_tickers_2025_11_17.loc['GOOGL']
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
## Get todays other (Google Trends & Yahoo Finance & Google Finance & ExchangeRate & MarketBeat & CrunchBase) data
|
|
80
|
+
|
|
81
|
+
```python
|
|
82
|
+
import pandas as pd
|
|
83
|
+
|
|
84
|
+
ticker, stop_day ='TSLA', datetime.now()
|
|
85
|
+
|
|
86
|
+
# 15 days Google Trends of a Ticker
|
|
87
|
+
google_trends = stocks._fetch_data(stocks.get_google_trends_pt, params={'kw_list': [ticker], 'from_date': stop_day - timedelta(days=15), 'to_date': stop_day}, error_str=" - No " + "google trends" \
|
|
88
|
+
+ " data for ticker search term: " + ticker + " from: " + str(stop_day - timedelta(days=15)) + " to: " + str(stop_day), empty_data=pd.DataFrame())
|
|
89
|
+
# Add a trendline to determine (+/- and degree of google_trends)
|
|
90
|
+
google_trends_slope = stocks.trendline(google_trends.sort_values('date', inplace=False, ascending=True)[ticker]) if not google_trends.empty else float("NaN") # sort_values is precautionary, should already be ascending
|
|
91
|
+
|
|
92
|
+
# Yahoo Finance Scraped Data
|
|
93
|
+
ticker_data_detailed = stocks._fetch_data(stocks.get_ticker_data_detailed_yfinance, params={'ticker': ticker}, error_str=" - No ticker data detailed Yahoo Finance for ticker: " + ticker + " on: " + str(datetime.now()), empty_data={})
|
|
94
|
+
|
|
95
|
+
# Google Finance Scraped Data for Tech companies (NASDAQ exchange, if loop through Alpaca assets ie for asset in stocks._fetch_data(stocks.alpaca_api.list_assets ...): asset.exchange can be extracted for every ticker = asset.symbol)
|
|
96
|
+
exchange = 'NASDAQ'
|
|
97
|
+
ticker_data_detailed = stocks._fetch_data(stocks.get_ticker_data_detailed_gfinance, params={'ticker': ticker, 'exchange': exchange}, error_str=" - No ticker data detailed gfinance for ticker: " + ticker + " on exchange: " + exchange + " on: " + str(datetime.now()), empty_data={})
|
|
98
|
+
|
|
99
|
+
# ExchangeRate
|
|
100
|
+
exchange_rates_usd = stocks._fetch_data(stocks.get_exchange_rates_exchangerate, params={'base_currency': 'USD'}, error_str=" - No Exchange Rates (USD) from ExchangeRate-api on: " + str(datetime.now()), empty_data = {})
|
|
101
|
+
|
|
102
|
+
# MarketBeat
|
|
103
|
+
df_tickers_sp500 = stocks._fetch_data(stocks.get_sp500_ranked_tickers_by_marketbeat, params={}, error_str=" - No s&p 500 tickers data from MarketBeat on: " + str(datetime.now()), empty_data = pd.DataFrame())
|
|
104
|
+
|
|
105
|
+
# CrunchBase downloading Tech Company data, bot detectors are quite good so currently blocked even with fake_headers and cookies
|
|
106
|
+
from fake_headers import Headers
|
|
107
|
+
import re
|
|
108
|
+
|
|
109
|
+
todays_date = datetime.now()
|
|
110
|
+
df_tickers_today = stocks.get_saved_tickers_data(date=todays_date.strftime('%Y-%m-%d'))
|
|
111
|
+
|
|
112
|
+
# Peer Company Tech Company data
|
|
113
|
+
# tech_companies = df_tickers_today[df_tickers_today['Sector'] == 'Technology']
|
|
114
|
+
|
|
115
|
+
headers, cookies = Headers(os="mac", headers=True).generate(), {'cid': 'CihjF2EJua4XkgAtPH5jAg==', '_pxhd': 'IhifXsIJ7A98ehR9VBprDcS2R0QJLw7ZvwUY8CR9jpoQ3fvPaRezXrWDUfCcqC75orD5OSnwJYS1ZP1A9ieOqQ==:-teWJPV0KWw6Vvnu46qXzIor-OW/6skuVb7jq-NfX4yCB-PpRiHoi31hJLDhl9vQQvj7qfVoeGpVqjlXPiFQqX6rZ/ihiPQ72Z1oh0nv1SE=', '__cflb': '02DiuJLCopmWEhtqNz5agBnHnWotHyxG4jgU9FLJcAXuE'}
|
|
116
|
+
company_name_re = re.compile(r'\b(?:{0}?\.)\b'.format('|'.join(['inc', 'incorporated', 'co', 'corp', 'corporation', 'ltd', 'limited', 'class a', 'american depositary shares', 'common stock', 'ordinary shares'])))
|
|
117
|
+
permalink = "-".join(company_name_re.split(df_tickers_today.loc[ticker, 'Name (Alpaca)'].lower())[0].replace(',','').strip().split(" ")) # re.sub(",?(\s)", "",
|
|
118
|
+
[crunchbase_data, resp_status_code] = stocks._fetch_data(stocks.get_crunchbase_data_for_ticker, params={'ticker': ticker, 'permalink_original': permalink, 'headers': headers, 'cookies': cookies}, error_str=" - No CrunchBase data for ticker: " + ticker + " with permalink_original: " + permalink + " on: " + str(datetime.now()), empty_data={})
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
## AI Analysis
|
|
122
|
+
|
|
123
|
+
```python
|
|
124
|
+
ticker = 'GOOGL'
|
|
125
|
+
company_name, location = df_tickers_today.loc[ticker, ['Name (Alpaca)', 'Location']]
|
|
126
|
+
buy_or_not_analysis = stocks.should_I_buy_the_stock_google_gemini_pro(ticker, company_name, location)
|
|
127
|
+
rating = stocks.extract_investment_recommendation(buy_or_not_analysis, ticker)
|
|
128
|
+
rating = rating if rating else stocks.extract_investment_recommendation_2(buy_or_not_analysis, ticker)
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
## Algorithms
|
|
132
|
+
|
|
133
|
+
```python
|
|
134
|
+
# Algorithms and their description, algorithms check for buy & sell opportunities every market day night except for random_sp500 (one every month), market checks during market hours every 4 minutes 365 days / year (for Stop-Loss, Trailing Stop-Loss)
|
|
135
|
+
portfolios = {
|
|
136
|
+
'zr': 'Zacks Rank - Buy or sell tickers depending on their Zanks rank (ie buy if rank > 3/5, sell if in portfolio and rank < 2/5)',
|
|
137
|
+
'rr': 'Relative Rank - Buy or sell tickers depending if their Market Cap relative rank has moved above or below a threshold over the past interval days (ie buy if Market Cap rank has increased 50 over the past 20 days, sell if in portfolio and Market Cap rank has decreased 50 over the past 20 days)',
|
|
138
|
+
'tilupccu': 'Top-Interval Loser (U = customizable ie # of losers, ranked by Market Cap or Percentage Loss) Peer Company Check (U = customizable ie EPS, PB, etc) - Buy tickers depending on their Market Cap and Percentage Loss over interval days and how strong their Peer Companies are (ie is it more likely to bounce back)'
|
|
139
|
+
'mmtv': 'Momentum Mean Trading Volume - Buy the ticker if the Trading Volume is greater than the Mean Trading Volume over the interval days',
|
|
140
|
+
'random_sp500': 'Random S&P 500 - Buy S&P500 tickers randomly weighted by price change over interval days checked every interval days (the algorithm I read about checks buys and sells every month)',
|
|
141
|
+
'mm': 'Momentum - Buy the ticker ranked by price change over the past interval days (meant for long-term 3-12 months ~90-~365days interval days)',
|
|
142
|
+
'airs': 'Aritifical Intelligence Recommendation in Sector - Iterates over a limited number of tickers in given sector (default is "Financial Services"), buys if AI (default is Gemini-Pro) gives a ranking >= 8/10, sells if AI gives a ranking <= 4/10, skips if issue with AI analysis (hallucination / not a proper ranking)',
|
|
143
|
+
'tngaia': 'Top-N Gainers Artificial Intelligence Analysis - Iterates over the Top N ticker gainers that FMP returns, buys if AI (default is Gemini-Pro) gives a ranking >= 8/10, sells if AI gives a ranking <= 4/10, skips if issue with AI analysis (hallucination / not a proper ranking)',
|
|
144
|
+
'senate_trading': 'Senate Trading - Iterates over tickers in the FMP Senate trading data (Senate timestamps and tickers inflows and outflows by month) that fall within a rank limit, buy ticker if rank is above 0, sell if rank is below 0',
|
|
145
|
+
'sma_mm': 'Simple Moving Average Momentum Move - Buy / sell if Price moves above or below customizable SMA range (200-day, 200-day in S&P 500, 8-day > 13-day and 5-day > 8-day)'
|
|
146
|
+
}
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
## Send message to your Phone via Twilio
|
|
150
|
+
|
|
151
|
+
```python
|
|
152
|
+
twilio_message = stocks._fetch_data(stocks.twilio_client.messages.create, params={'to': twilio_phone_to, 'from_': twilio_phone_from, 'body': "Q Trading @stocks #" + stocks.portfolio_account + ": running on " + str(datetime.now()) + " :)"}, error_str=" - Twilio msg error to: " + twilio_phone_to + " on: " + str(datetime.now()), empty_data=None)
|
|
153
|
+
```
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "speterlin-stocks"
|
|
3
|
+
version = "1.0.6"
|
|
4
|
+
description = "A Python package for a suite of quant-trading opportunities in stocks with API integration: Alpaca brokerage for storing USD assets and margin trading (2x) on exchanges NYSE & NASDAQ, Financial Modeling Prep (FMP) & Google Trends & Yahoo Finance & Google Finance & ExchangeRate & MarketBeat & CrunchBase for data collection, OpenAI & Google Gemini-Pro for AI analysis."
|
|
5
|
+
authors = [
|
|
6
|
+
{ name = "Sebastian Peterlin", email = "speterlin@smartxchange.xyz" },
|
|
7
|
+
]
|
|
8
|
+
license = { text = "MIT" }
|
|
9
|
+
requires-python = ">=3.12"
|
|
10
|
+
dependencies = [
|
|
11
|
+
"requests>=2.20",
|
|
12
|
+
"numpy",
|
|
13
|
+
"pandas>=2.0",
|
|
14
|
+
"datetime",
|
|
15
|
+
"yfinance==0.1.52",
|
|
16
|
+
"beautifulsoup4", # bs4
|
|
17
|
+
"pytrends",
|
|
18
|
+
"openai", # ~
|
|
19
|
+
"langchain-openai",
|
|
20
|
+
"google-generativeai",
|
|
21
|
+
"unidecode",
|
|
22
|
+
"fake-headers",
|
|
23
|
+
"pytz",
|
|
24
|
+
"alpaca-trade-api", # ~ --no-dependencies
|
|
25
|
+
"twilio" # ~
|
|
26
|
+
]
|
|
27
|
+
|
|
28
|
+
[build-system]
|
|
29
|
+
requires = ["setuptools>=61.0", "wheel"]
|
|
30
|
+
build-backend = "setuptools.build_meta"
|
|
31
|
+
|
|
32
|
+
[project.urls]
|
|
33
|
+
Homepage = "https://github.com/speterlin/speterlin-stocks"
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"""A Python package for a suite of quant-trading opportunities in stocks with API integration: Alpaca brokerage for storing USD assets and margin trading (2x) on exchanges NYSE & NASDAQ, Financial Modeling Prep (FMP) & Google Trends & Yahoo Finance & Google Finance & ExchangeRate & MarketBeat & CrunchBase for data collection, OpenAI & Google Gemini-Pro for AI analysis.
|
|
2
|
+
|
|
3
|
+
.. moduleauthor:: Sebastian B. Peterlin
|
|
4
|
+
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
__version__ = '1.0.6'
|
|
8
|
+
|
|
9
|
+
# from .module1 import *
|
|
10
|
+
# from . import module1
|
|
11
|
+
|
|
12
|
+
# def __getattr__(name):
|
|
13
|
+
# return getattr(module1, name)
|
|
14
|
+
#
|
|
15
|
+
# def __setattr__(name, value):
|
|
16
|
+
# setattr(module1, name, value)
|