bbstrader.core package
Module contents
Overview
The Core Module provides the fundamental building blocks and abstract base classes for the trading system. It defines the essential components that are extended by other modules to create a complete trading application, ensuring a consistent and modular architecture.
Features
Abstract Base Classes: Defines the interfaces for key components like data handlers and strategies, promoting a standardized approach to development.
Modularity: Enforces a modular design by providing a clear separation of concerns between data handling, strategy logic, and execution.
Extensibility: Designed to be easily extended with concrete implementations, allowing for the creation of custom data sources and trading strategies.
Components
Data: Contains the abstract base class DataHandler, which defines the interface for managing market data from various sources.
Strategy: Contains the abstract base class Strategy, which provides the framework for developing trading strategies.
This module contains the abstract classes that form the foundation of the trading system. Implementations of these classes can be found in other modules like btengine and trading.
Submodules
bbstrader.core.data module
- class bbstrader.core.data.FinancialNews[source]
Bases:
objectThe FinancialNews class provides methods to fetch financial news, articles, and discussions from various sources such as Yahoo Finance, Google Finance, Reddit, Coindesk and Twitter. It also supports retrieving news using Financial Modeling Prep (FMP).
- get_coindesk_news(query='', lang: Literal['EN', 'ES', 'TR', 'FR', 'JP', 'PT'] = 'EN', limit=10, list_of_str=False) List[str] | List[dict][source]
Fetches and filters recent news articles from CoinDesk’s News API.
- Parameters:
query – str, optional A search term to filter articles by title, body, or keywords. If empty, all articles are returned without filtering (default is “”).
lang – Literal[“EN”, “ES”, “TR”, “FR”, “JP”, “PT”], optional Language in which to fetch news articles. Supported languages: English (EN), Spanish (ES), Turkish (TR), French (FR), Japanese (JP), and Portuguese (PT). Default is “EN”.
limit – int, optional Maximum number of articles to retrieve. Default is 50.
list_of_str – bool, optional If True, returns a list of strings (concatenated article content). If False, returns a list of filtered article dictionaries. Default is False.
- Returns:
- List[str] | List[dict]
If query is empty: returns a list of filtered article dictionaries.
- If query is provided:
Returns a list of strings if list_of_str=True.
Returns a list of filtered article dictionaries otherwise.
- Each article dictionary contains the following fields:
‘published_on’: datetime of publication
‘title’: article headline
‘subtitle’: secondary headline
‘url’: direct link to the article
‘body’: article content
‘keywords’: associated tags
‘sentiment’: sentiment label
‘status’: publication status
Notes
Articles marked as sponsored are automatically excluded.
- get_google_finance_news(query: str, asset_type: str = 'stock', n_news: int = 10) List[str][source]
Fetches recent Google Finance news headlines for a given financial asset.
- Parameters:
query (str) – The asset symbol or name (e.g., “AAPL”).
asset_type (str, optional) – The type of asset (e.g., “stock”, “crypto”). Defaults to “stock”. Supported types include: - “stock”: Stock symbols (e.g., AAPL, MSFT) - “etf”: Exchange-traded funds (e.g., SPY, QQQ) - “future”: Futures contracts (e.g., CL=F or crude oil) - “forex”: Forex pairs (e.g., EURUSD, USDJPY) - “crypto”: Cryptocurrency pairs (e.g., BTCUSD, ETHUSD)
n_news (int, optional) – The number of news headlines to return. Defaults to 10.
- Returns:
A list of Google Finance news headlines relevant to the query.
- Return type:
list[str]
- get_reddit_posts(symbol: str, client_id=None, client_secret=None, user_agent=None, asset_class='stock', n_posts=10) List[str][source]
Fetches recent Reddit posts related to a financial asset.
This method queries relevant subreddits for posts mentioning the specified symbol and returns posts based on the selected asset class (e.g., stock, forex, crypto). The function uses the PRAW library to interact with Reddit’s API.
- Parameters:
symbol (str) – The financial asset’s symbol or name to search for.
client_id (str, optional) – Reddit API client ID for authentication.
client_secret (str, optional) – Reddit API client secret.
user_agent (str, optional) – Reddit API user agent.
asset_class (str, optional) – The type of financial asset. Defaults to “stock”. - “stock”: Searches in stock-related subreddits (e.g., wallstreetbets, stocks). - “forex”: Searches in forex-related subreddits. - “commodities”: Searches in commodity-related subreddits (e.g., gold, oil). - “etf”: Searches in ETF-related subreddits. - “future”: Searches in futures and options trading subreddits. - “crypto”: Searches in cryptocurrency-related subreddits. - If an unrecognized asset class is provided, defaults to stock-related subreddits.
n_posts (int, optional) – The number of posts to return per subreddit. Defaults to 10.
- Returns:
- A list of Reddit post contents matching the query.
Each entry contains the post title and body. If no posts are found or an error occurs, returns an empty list.
- Return type:
list[str]
- Raises:
praw.exceptions.PRAWException – If an error occurs while interacting with Reddit’s API.
Example
>>> get_reddit_posts(symbol="AAPL", client_id="your_id", client_secret="your_secret", user_agent="your_agent", asset_class="stock", n_posts=5) ["Apple stock is rallying today due to strong earnings.", "Should I buy $AAPL now?", ...]
Notes
Requires valid Reddit API credentials.
- get_twitter_posts(query: str, asset_type: str = 'stock', bearer: str | None = None, api_key: str | None = None, api_secret: str | None = None, access_token: str | None = None, access_secret: str | None = None, n_posts: int = 10) List[str][source]
Fetches recent tweets related to a financial asset.
This method queries Twitter for recent posts mentioning the specified asset and filters the results based on the asset type (e.g., stock, forex, crypto). The function uses the Tweepy API to fetch tweets and returns a list of tweet texts.
- Parameters:
query (str) – The main keyword to search for (e.g., a stock ticker or asset name).
asset_type (str, optional) – The type of financial asset. Defaults to “stock”. - “stock”: Searches for tweets mentioning the stock or shares. - “forex”: Searches for tweets mentioning foreign exchange (forex) or currency. - “crypto”: Searches for tweets mentioning cryptocurrency or related terms. - “commodity”: Searches for tweets mentioning commodities or futures trading. - “index”: Searches for tweets mentioning stock market indices. - “bond”: Searches for tweets mentioning bonds or fixed income securities. - If an unrecognized asset type is provided, defaults to general finance-related tweets.
bearer (str, optional) – Twitter API bearer token for authentication.
api_key (str, optional) – Twitter API consumer key.
api_secret (str, optional) – Twitter API consumer secret.
access_token (str, optional) – Twitter API access token.
access_secret (str, optional) – Twitter API access token secret.
n_posts (int, optional) – The number of tweets to return. Defaults to 10.
- Returns:
- A list of up to n_posts tweet texts matching the query.
If no tweets are found or an API error occurs, returns an empty list.
- Return type:
list[str]
- Raises:
tweepy.TweepyException – If an error occurs while making the Twitter API request.
Example
>>> get_twitter_posts(query="AAPL", asset_type="stock", bearer="YOUR_BEARER_TOKEN", n_posts=5) ["Apple stock surges after strong earnings!", "Is $AAPL a buy at this price?", ...]
- get_yahoo_finance_news(query: str, asset_type: str = 'stock', n_news: int = 10) List[str][source]
Fetches recent Yahoo Finance news headlines for a given financial asset.
- Parameters:
query (str) – The asset symbol or name (e.g., “AAPL”).
asset_type (str, optional) – The type of asset (e.g., “stock”, “etf”). Defaults to “stock”, supported types include: - “stock”: Stock symbols (e.g., AAPL, MSFT) - “etf”: Exchange-traded funds (e.g., SPY, QQQ) - “future”: Futures contracts (e.g., CL=F for crude oil) - “forex”: Forex pairs (e.g., EURUSD=X, USDJPY=X) - “crypto”: Cryptocurrency pairs (e.g., BTC-USD, ETH-USD) - “index”: Stock market indices (e.g., ^GSPC for S&P 500)
n_news (int, optional) – The number of news headlines to return. Defaults to 10.
Note
For commotities and bonds, use the “Future” asset type.
- Returns:
A list of Yahoo Finance news headlines relevant to the query.
- Return type:
list[str]
- class bbstrader.core.data.FmpData(api_key: str = '', symbols: str | list = 'AAPL')[source]
Bases:
ToolkitFMPData class for fetching data from Financial Modeling Prep API using the Toolkit class from financetoolkit package.
See financetoolkit for more details.
- class bbstrader.core.data.FmpNews(api: str)[source]
Bases:
objectFmpNewsis responsible for retrieving financial news, press releases, and articles from Financial Modeling Prep (FMP).FmpNewsprovides methods to fetch the latest stock, crypto, forex, and general financial news, as well as financial articles and press releases.- get_latest_articles(articles: List[Dict[str, Any]] | None = None, save: bool = False, **kwargs: Any) List[Dict[str, Any]][source]
- get_news(query: str, source: str = 'articles', articles: List[Dict[str, Any]] | None = None, symbol: str | None = None, **kwargs: Any) List[str][source]
Retrieves relevant financial news based on the specified source.
- Parameters:
query (str) – The search query or keyword for filtering news, may also be a ticker.
source (str, optional) – The news source to retrieve from. Defaults to “articles”. Available options: “articles”, “releases”, “stock”, “crypto”, “forex”.
articles (list, optional) – List of pre-fetched articles to use when source=”articles”. Defaults to None.
symbol (str, optional) – The financial asset symbol (e.g., “AAPL” for stocks, “BTC” for crypto). Defaults to None.
**kwargs (dict) – Additional arguments required for fetching news data. May include: - start (str): The start period for news retrieval (YYY-MM-DD) - end (str): The end period for news retrieval (YYY-MM-DD) - page (int): The number of page to load for each news - limit (int): Maximum Responses per API Call
- Returns:
- A list of filtered news articles relevant to the query.
Returns an empty list if no relevant news is found.
- Return type:
list[dict]
bbstrader.core.strategy module
- class bbstrader.core.strategy.Strategy[source]
Bases:
objectA Strategy() object encapsulates all calculation on market data that generate advisory signals to a Portfolio object. Thus all of the “strategy logic” resides within this class. We opted to separate out the Strategy and Portfolio objects for this backtester, since we believe this is more amenable to the situation of multiple strategies feeding “ideas” to a larger Portfolio, which then can handle its own risk (such as sector allocation, leverage). In higher frequency trading, the strategy and portfolio concepts will be tightly coupled and extremely hardware dependent.
At this stage in the event-driven backtester development there is no concept of an indicator or filter, such as those found in technical trading. These are also good candidates for creating a class hierarchy.
The strategy hierarchy is relatively simple as it consists of an abstract base class with a single pure virtual method for generating SignalEvent objects. Other methods are provided to check for pending orders, update trades from fills, and get updates from the portfolio.
- abstractmethod calculate_signals(*args: Any, **kwargs: Any) List[TradeSignal][source]
- class bbstrader.core.strategy.TradeAction(*values)[source]
Bases:
EnumAn enumeration class for trade actions.
- BLMT = 'BLMT'
- BMKT = 'BMKT'
- BSTP = 'BSTP'
- BSTPLMT = 'BSTPLMT'
- BUY = 'LONG'
- EXIT = 'EXIT'
- EXIT_ALL_ORDERS = 'EXIT_ALL_ORDERS'
- EXIT_ALL_POSITIONS = 'EXIT_ALL_POSITIONS'
- EXIT_LIMIT = 'EXIT_LIMIT'
- EXIT_LONG = 'EXIT_LONG'
- EXIT_LONG_LIMIT = 'EXIT_LONG_LIMIT'
- EXIT_LONG_STOP = 'EXIT_LONG_STOP'
- EXIT_LONG_STOP_LIMIT = 'EXIT_LONG_STOP_LIMIT'
- EXIT_LOSINGS = 'EXIT_LOSINGS'
- EXIT_PROFITABLES = 'EXIT_PROFITABLES'
- EXIT_SHORT = 'EXIT_SHORT'
- EXIT_SHORT_LIMIT = 'EXIT_SHORT_LIMIT'
- EXIT_SHORT_STOP = 'EXIT_SHORT_STOP'
- EXIT_SHORT_STOP_LIMIT = 'EXIT_SHORT_STOP_LIMIT'
- EXIT_STOP = 'EXIT_STOP'
- LONG = 'LONG'
- SELL = 'SHORT'
- SHORT = 'SHORT'
- SLMT = 'SLMT'
- SMKT = 'SMKT'
- SSTP = 'SSTP'
- SSTPLMT = 'SSTPLMT'
- class bbstrader.core.strategy.TradeSignal(id: int, symbol: str, action: TradeAction, price: float = None, stoplimit: float = None, sl: float = None, tp: float = None, comment: str = None)[source]
Bases:
objectRepresents a trading signal generated by a trading system or strategy.
Notes
Attributes:
id (int): A unique identifier for the trade signal or the strategy.
symbol (str): The trading symbol (e.g., stock ticker, forex pair, crypto asset).
action (TradeAction): The trading action to perform. Must be an instance of the
TradeActionenum (e.g., BUY, SELL).price (float, optional): The price at which the trade should be executed.
stoplimit (float, optional): A stop-limit price for the trade. Must not be set without specifying a price.
sl (float, optional): A stop loss price for the trade.
tp (float, optional): A take profit price for the trade.
comment (str, optional): An optional comment or description related to the trade signal.
- action: TradeAction
- comment: str = None
- id: int
- price: float = None
- sl: float = None
- stoplimit: float = None
- symbol: str
- tp: float = None
- class bbstrader.core.strategy.TradingMode(*values)[source]
Bases:
Enum- BACKTEST = 'BACKTEST'
- LIVE = 'LIVE'
- bbstrader.core.strategy.generate_signal(id: int, symbol: str, action: TradeAction, price: float = None, stoplimit: float = None, sl: float = None, tp: float = None, comment: str = None) TradeSignal[source]
Generates a trade signal for MetaTrader 5.
- Parameters:
id (int) – Unique identifier for the trade signal.
symbol (str) – The symbol for which the trade signal is generated.
action (TradeAction) – The action to be taken (e.g., BUY, SELL).
price (float, optional) – The price at which to execute the trade.
stoplimit (float, optional) – The stop limit price for the trade.
sl (float, optional) – The stop loss price for the trade.
tp (float, optional) – The take profit price for the trade.
comment (str, optional) – Additional comments for the trade.
- Returns:
A TradeSignal object containing the details of the trade signal.
- Return type: