Hi, I am trying to access self.History() in a PythonData Class. My goal is to build a custom data source that switches between custom data and historical data from Quantconnect.
Here is the code:
import pandas as pd
from datetime import datetime
from AlgorithmImports import *
class HybridKMLMXData(PythonData):
def __init__(self):
super().__init__()
self.equity_symbol = Symbol.create("KMLM", SecurityType.EQUITY, Market.USA)
def get_source(self, config, date, isLiveMode):
source = "https://gist.githubusercontent.com/chrswrmr/3a7522de7c9429e6dc2c8d29627e6e33/raw/510aeeaa5dc64dbd2e59ee5138ac66edff9018ca/KMLMX_rev.csv"
return SubscriptionDataSource(source, SubscriptionTransportMedium.REMOTE_FILE)
def reader(self, config, line, date, isLiveMode):
try:
if not line.strip() or line.startswith("date"):
return None
parts = line.split(",")
parsed_date = pd.Timestamp(parts[0])
data = HybridKMLMXData()
data.Symbol = config.Symbol
data.Time = parsed_date
if parsed_date < datetime(2021, 1, 1):
value = round(float(parts[1]), 4)
data.value = value
data.close = value
else:
# Use the History method to get QuantConnect data
history = self.history(self.equity_symbol, parsed_date, parsed_date, Resolution.DAILY)
if not history.empty:
equity_data = history.iloc[0]
data.value = equity_data['close']
data.close = equity_data['close']
else:
# Fallback to CSV data if history is empty
data.value = float(parts[1])
data.close = float(parts[1])
return data
except Exception as e:
print(f"Error processing data: {e}")
return None
class CustomDataAlgorithm(QCAlgorithm):
def initialize(self):
self.set_start_date(2020, 12, 1)
self.set_end_date(2021, 1, 31)
self.set_cash(100000)
# Only add the hybrid data source
self.symbol = self.add_data(HybridKMLMXData, "KMLMX", Resolution.DAILY).Symbol
def on_data(self, slice):
# Access KMLMX data
data = slice.get(HybridKMLMXData).get(self.symbol)
if data:
self.log(f"KMLMX - Date: {data.Time}, Close: {data.close}")
The main problem: In a PythonData class, I don't have direct access to the QCAlgorithm's History method. The PythonData class doesn't inherit from QCAlgorithm. How can I get access to the History method inside a PythonData class?
Mia Alissi
Sources: Custom Data Type History Algorithm, History With Custom Data Source Regression Algorithm, Pandas Data Frame History Algorithm, Custom Data - QuantConnect.com, History Algorithm
The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.
Kryz
The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.
To unlock posting to the community forums please complete at least 30% of Boot Camp.
You can continue your Boot Camp training progress from the terminal. We hope to see you in the community soon!