forked from Lumiwealth/lumibot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathllms.txt
More file actions
150 lines (119 loc) · 5.73 KB
/
Copy pathllms.txt
File metadata and controls
150 lines (119 loc) · 5.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
# Lumibot
> Python trading and backtesting framework for stocks, options, crypto, and futures.
> Supports Alpaca, Interactive Brokers, Tradier, Schwab, ThetaData, Yahoo Finance, and Polygon.
## Critical Rules for Code Generation
- **NEVER** use `datetime.now()` or `datetime.today()` - always use `self.get_datetime()` for backtesting compatibility
- **NEVER** use `from __future__ import annotations` - it breaks Lumibot's type checking
- Use `self.vars` for persistent variables across lifecycle methods (e.g., `self.vars.my_variable = value`)
- Use `self.log_message()` instead of `print()` for proper logging
- Get current prices with `self.get_last_price(asset)` - returns None if unavailable
- Submit orders with `self.submit_order(order)` where `order = self.create_order(asset, quantity, side)`
- Access portfolio with `self.portfolio_value`, `self.cash`, `self.positions`
- Implement `on_trading_iteration()` for main strategy logic - runs once per bar/iteration
- For options: Use `self.create_asset(symbol, asset_type=Asset.AssetType.OPTION, expiration=date, strike=price, right='call'|'put')`
## Full Documentation
For complete API documentation with all method signatures, parameters, return types, and examples, see **llms-full.txt** in this repository.
## Quick Reference
### Lifecycle Methods
- `initialize()` - Called once at strategy start, set up variables here
- `on_trading_iteration()` - Main strategy logic, runs every bar/iteration
- `before_market_opens()` - Called before market opens each day
- `before_market_closes()` - Called before market closes each day
- `after_market_closes()` - Called after market closes each day
- `on_filled_order(position, order, price, quantity)` - Called when order fills
- `trace_stats(context, snapshot_before)` - Log custom stats each iteration
### Order Methods
- `self.create_order(asset, quantity, side, **kwargs)` - Create an order object
- `self.submit_order(order)` - Submit order for execution
- `self.cancel_order(order)` - Cancel a pending order
- `self.sell_all()` - Liquidate all positions
- `self.get_orders()` - Get all orders
- `self.get_order(identifier)` - Get specific order by ID
### Data Methods
- `self.get_last_price(asset)` - Get current/last price
- `self.get_historical_prices(asset, length, timestep)` - Get OHLCV bars
- `self.get_historical_prices_for_assets(assets, length, timestep)` - Get bars for multiple assets
- `self.get_quote(asset)` - Get current quote (bid/ask)
### Account Methods
- `self.get_cash()` - Get available cash
- `self.get_portfolio_value()` - Get total portfolio value
- `self.get_position(asset)` - Get position for asset
- `self.get_positions()` - Get all positions
### DateTime Methods (USE THESE, not datetime.now())
- `self.get_datetime()` - Get current datetime (backtesting-safe)
- `self.get_timestamp()` - Get current timestamp
- `self.get_round_minute(timeshift)` - Get rounded minute
- `self.get_round_day(timeshift)` - Get rounded day
### Options Methods
- `self.get_chains(asset)` - Get option chains
- `self.get_chain(chains, exchange)` - Get chain for specific exchange
- `self.get_strikes(chain)` - Get available strikes
- `self.get_expiration(chain, expiration_date)` - Get specific expiration
- `self.get_greeks(asset)` - Get option greeks
### Key Properties
- `self.cash` - Current cash balance
- `self.portfolio_value` - Total portfolio value
- `self.positions` - Dict of current positions
- `self.first_iteration` - True on first iteration
- `self.is_backtesting` - True if backtesting
- `self.minutes_before_closing` - Minutes before market close
- `self.sleeptime` - Seconds between iterations
### Asset Creation
```python
# Stock
asset = Asset(symbol="AAPL", asset_type=Asset.AssetType.STOCK)
# Option
asset = Asset(
symbol="AAPL",
asset_type=Asset.AssetType.OPTION,
expiration=datetime.date(2024, 1, 19),
strike=150,
right="call" # or "put"
)
# Crypto
asset = Asset(symbol="BTC", asset_type=Asset.AssetType.CRYPTO)
# Future
asset = Asset(symbol="ES", asset_type=Asset.AssetType.FUTURE, expiration=datetime.date(2024, 3, 15))
```
### Basic Strategy Template
```python
from lumibot.strategies import Strategy
from lumibot.entities import Asset
class MyStrategy(Strategy):
parameters = {"symbol": "AAPL", "quantity": 10}
def initialize(self):
self.sleeptime = "1D" # Run once per day
def on_trading_iteration(self):
symbol = self.parameters["symbol"]
qty = self.parameters["quantity"]
# Get current price (use self.get_datetime(), NOT datetime.now())
price = self.get_last_price(symbol)
if price is None:
self.log_message(f"No price for {symbol}")
return
# Check position
position = self.get_position(symbol)
if position is None:
# Buy if no position
order = self.create_order(symbol, qty, "buy")
self.submit_order(order)
```
### Trading Fees
```python
# Stocks: use percent_fee (percentage of order value)
TradingFee(percent_fee=0.001) # 0.1% of order value
# Options: use per_contract_fee (multiplied by number of contracts)
TradingFee(per_contract_fee=0.65) # $0.65 per contract (IBKR standard)
# Futures: use per_contract_fee
TradingFee(per_contract_fee=0.85) # $0.85 per standard contract
# Flat fee: fixed amount per ORDER regardless of quantity
TradingFee(flat_fee=5.00) # $5 per order
# Pass to backtest:
result = MyStrategy.backtest(datasource, buy_trading_fees=[fee], sell_trading_fees=[fee])
```
## Backtesting Data Sources
- `YahooDataBacktesting` - Free, good for stocks
- `PolygonDataBacktesting` - Crypto and stocks (requires API key)
- `ThetaDataBacktesting` - Options and stocks (requires subscription)
Set via environment variable: `BACKTESTING_DATA_SOURCE=yahoo|polygon|thetadata`
# Generated: 2026-01-05T06:59:12Z