Lean의 만기 도우미로 인사이트 만기 예약하기
기사 Strategy library · 저자: QuantConnect
요약
이 Lean 프레임워크 예시는 알파 모델이 만기 도우미를 사용해 생성된 트레이딩 인사이트의 청산 시점을 정하는 방법을 보여줍니다. 알고리즘은 수동으로 선택한 US 주식 유니버스(SPY 포함), 시간봉 데이터, 동일 비중 포트폴리오 구성, 즉시 실행, 종목별 드로다운 한도를 사용합니다. 알파 모델은 예정된 업데이트 시각까지 기다린 뒤 새로운 인사이트를 생성합니다.
예시는 요일에 따라 만기를 정합니다. 한 달, 월말, 주말 또는 당일 마감 중 하나입니다. 생성된 인사이트의 청산 시각과 요일도 기록해 결과 일정을 확인하는 방법을 보여줍니다. 이는 테스트된 거래 신호가 아니라 프레임워크 작동 방식의 예입니다. 모델은 항상 상승 방향을 지정하며, 문서에는 투자 성과나 해당 시점 설정이 수익을 낸다는 증거가 없습니다. 짧은 날짜 범위와 단일 종목 유니버스 때문에 추론할 수 있는 내용도 제한적입니다. 이 예시의 가치는 인사이트 수명을 관리하는 구현 방식에 있으며, 완성된 전략 추천은 아닙니다.
핵심 아이디어
- 알파 모델은 만기 도우미를 사용해 생성된 인사이트의 청산 시점을 지정할 수 있습니다.
- 예시에서는 현재 요일에 따라 만기 간격을 선택합니다.
- 예약된 다음 업데이트 시각으로 데이터가 갱신될 때마다 모델이 인사이트를 내는 것을 방지합니다.
- 생성된 인사이트의 청산 시각을 기록해 만기 동작을 확인할 수 있습니다.
- 이 예시는 프레임워크 사용법을 보여주며 거래 성과의 근거를 제공하지 않습니다.
태그
전문
# ExpiryHelperAlphaModelFrameworkAlgorithm
# ExpiryHelperAlphaModelFrameworkAlgorithm
Expiry Helper framework algorithm uses Expiry helper class in an Alpha Model
Expiry Helper algorithm uses Expiry helper class in an Alpha Model
## Source (Apache-2.0)
```python
# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
# Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from AlgorithmImports import *
### <summary>
### Expiry Helper algorithm uses Expiry helper class in an Alpha Model
### </summary>
class ExpiryHelperAlphaModelFrameworkAlgorithm(QCAlgorithm):
'''Expiry Helper framework algorithm uses Expiry helper class in an Alpha Model'''
def initialize(self) -> None:
''' Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
# Set requested data resolution
self.universe_settings.resolution = Resolution.HOUR
self.set_start_date(2013,10,7) #Set Start Date
self.set_end_date(2014,1,1) #Set End Date
self.set_cash(100000) #Set Strategy Cash
symbols = [ Symbol.create("SPY", SecurityType.EQUITY, Market.USA) ]
# set algorithm framework models
self.set_universe_selection(ManualUniverseSelectionModel(symbols))
self.set_alpha(self.ExpiryHelperAlphaModel())
self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())
self.set_execution(ImmediateExecutionModel())
self.set_risk_management(MaximumDrawdownPercentPerSecurity(0.01))
self.insights_generated += self.on_insights_generated
def on_insights_generated(self, s: IAlgorithm, e: GeneratedInsightsCollection) -> None:
for insight in e.insights:
self.log(f"{e.date_time_utc.isoweekday()}: Close Time {insight.close_time_utc} {insight.close_time_utc.isoweekday()}")
class ExpiryHelperAlphaModel(AlphaModel):
_next_update = None
_direction = InsightDirection.UP
def update(self, algorithm: QCAlgorithm, data: Slice) -> list[Insight]:
if self._next_update and self._next_update > algorithm.time:
return []
expiry = Expiry.END_OF_DAY
# Use the Expiry helper to calculate a date/time in the future
self._next_update = expiry(algorithm.time)
weekday = algorithm.time.isoweekday()
insights = []
for symbol in data.bars.keys():
# Expected CloseTime: next month on the same day and time
if weekday == 1:
insights.append(Insight.price(symbol, Expiry.ONE_MONTH, self._direction))
# Expected CloseTime: next month on the 1st at market open time
elif weekday == 2:
insights.append(Insight.price(symbol, Expiry.END_OF_MONTH, self._direction))
# Expected CloseTime: next Monday at market open time
elif weekday == 3:
insights.append(Insight.price(symbol, Expiry.END_OF_WEEK, self._direction))
# Expected CloseTime: next day (Friday) at market open time
elif weekday == 4:
insights.append(Insight.price(symbol, Expiry.END_OF_DAY, self._direction))
return insights
```출처의 라이선스에 따라 출처를 표시하고 전문을 공개합니다. 라이선스: Apache-2.0
이 요약은 원문을 바탕으로 Stratmill의 리서치 에이전트가 작성했으며, 원문을 복사한 것이 아닙니다.