Я уже неделю работаю над сценарием с ChatGPT, но не получил ожидаемого результата.
выход, который мне нужен, - это количество общих ресурсов в каждом дикторе. продолжайте добавлять, например
Начало
# First Transaction
{'date': '01/12/2024', 'tickers': [{'ticker': APPL, 'shares': 20}], 'total_value': 4000.00}
# I purchased 20 in NVDA
{'date': '03/12/2024', 'tickers': [{'ticker': APPL, 'shares': 20}, {'ticker': NVDA, 'shares': 20}}], 'total_value': 5000.00}
# I purchased 5 more in APPL
{'date': '08/12/2024', 'tickers': [{'ticker': APPL, 'shares': 25}, {'ticker': NVDA, 'shares': 20}}], 'total_value': 7000.00}
Итак, мне нужна историческая стоимость на каждую дату транзакции, чтобы я мог создавать символы в Excel с этими историческими данными
но проблема с этим скриптом заключается в том, что он дает мне общую сумму каждой транзакции.
Полный сценарий:
import pandas as pd
import yfinance as yf
from datetime import timedelta, datetime
# Load data
file = "Finance.xlsx"
df = pd.read_excel(file, sheet_name="Data", header=2)
# Normalize column names
df.columns = df.columns.str.strip().str.upper()
# Clean and sort data
df['DATE'] = pd.to_datetime(df['DATE'], errors='coerce')
df = df.dropna(subset=['DATE']).sort_values(by='DATE')
# Dictionary to track cumulative shares per ticker
cumulative_shares = {}
# Initialize list to store dictionaries
data_list = []
# Custom price list for missing data
missing_prices = {
4071: {
'2021-11-15': 104.0,
'2021-11-16': 104.0,
'2021-11-17': 103.80,
'2021-11-18': 102.4,
'2021-11-21': 100.6,
'2021-11-22': 95.4,
'2021-11-23': 97.5,
'2021-11-24': 96.50,
'2021-11-25': 94.00,
'2021-11-28': 86.30,
'2021-11-29': 90.10,
'2021-11-30': 88.30,
'2021-12-01': 87.40,
'2021-12-02': 88.20,
'2021-12-05': 89.80,
'2021-12-06': 89.80,
'2021-12-07': 91.60,
'2021-12-08': 91.60,
'2021-12-09': 89.00,
'2021-12-12': 88.60,
'2021-12-13': 88.70,
'2021-12-14': 88.00,
'2021-12-15': 88.40,
'2021-12-16': 89.80,
'2021-12-19': 88.20,
'2021-12-20': 86.80,
# Add other dates and prices as needed
}
}
# Function to get the close price from Yahoo Finance or custom list
def get_close_price(ticker, target_date, lookback_days=30):
"""
Retrieves the Close price for the given ticker on the target date.
If data for the target date isn't available, it fetches the Close price
from the most recent available date before the target date within the lookback period.
Parameters:
- ticker (int): The stock ticker symbol (e.g., 2222).
- target_date (pd.Timestamp): The target date.
- lookback_days (int): Number of days to look back for available data.
Returns:
- float: The Close price if available, else 0.
"""
try:
if not isinstance(target_date, pd.Timestamp):
raise ValueError("Invalid date format")
target_date_str = target_date.strftime('%Y-%m-%d')
# Check for custom price list
if ticker in missing_prices and target_date_str in missing_prices[ticker]:
return missing_prices[ticker][target_date_str]
ticker_full = str(ticker) + ".SR" # Add .SR to ticker
# Define the date range for fetching data
start_date = (target_date - timedelta(days=lookback_days)).strftime('%Y-%m-%d')
end_date = (target_date + timedelta(days=1)).strftime('%Y-%m-%d') # Make end date inclusive
# Download historical data using yfinance
data = yf.download(ticker_full, start=start_date, end=end_date, progress=False, auto_adjust=True)
if data.empty:
print(f"No data available for {ticker_full} between {start_date} and {end_date}.")
return 0
# Ensure data.index is timezone-naive
if data.index.tz is not None:
data.index = data.index.tz_convert(None)
# Filter data up to and including the target date
data = data[data.index
Подробнее здесь: [url]https://stackoverflow.com/questions/79277025/yfinance-getting-historical-close-price-of-wallet-issues[/url]
Я уже неделю работаю над сценарием с ChatGPT, но не получил ожидаемого результата. выход, который мне нужен, - это количество общих ресурсов в каждом дикторе. продолжайте добавлять, например Начало [code]# First Transaction {'date': '01/12/2024', 'tickers': [{'ticker': APPL, 'shares': 20}], 'total_value': 4000.00}
# I purchased 20 in NVDA {'date': '03/12/2024', 'tickers': [{'ticker': APPL, 'shares': 20}, {'ticker': NVDA, 'shares': 20}}], 'total_value': 5000.00}
# I purchased 5 more in APPL {'date': '08/12/2024', 'tickers': [{'ticker': APPL, 'shares': 25}, {'ticker': NVDA, 'shares': 20}}], 'total_value': 7000.00} [/code] Итак, мне нужна историческая стоимость на каждую дату транзакции, чтобы я мог создавать символы в Excel с этими историческими данными но проблема с этим скриптом заключается в том, что он дает мне общую сумму каждой транзакции. Полный сценарий: [code]import pandas as pd import yfinance as yf from datetime import timedelta, datetime
# Function to get the close price from Yahoo Finance or custom list def get_close_price(ticker, target_date, lookback_days=30): """ Retrieves the Close price for the given ticker on the target date. If data for the target date isn't available, it fetches the Close price from the most recent available date before the target date within the lookback period.
Parameters: - ticker (int): The stock ticker symbol (e.g., 2222). - target_date (pd.Timestamp): The target date. - lookback_days (int): Number of days to look back for available data.
Returns: - float: The Close price if available, else 0. """ try: if not isinstance(target_date, pd.Timestamp): raise ValueError("Invalid date format")
# Check for custom price list if ticker in missing_prices and target_date_str in missing_prices[ticker]: return missing_prices[ticker][target_date_str]
ticker_full = str(ticker) + ".SR" # Add .SR to ticker
# Define the date range for fetching data start_date = (target_date - timedelta(days=lookback_days)).strftime('%Y-%m-%d') end_date = (target_date + timedelta(days=1)).strftime('%Y-%m-%d') # Make end date inclusive
# Download historical data using yfinance data = yf.download(ticker_full, start=start_date, end=end_date, progress=False, auto_adjust=True)
if data.empty: print(f"No data available for {ticker_full} between {start_date} and {end_date}.") return 0
# Ensure data.index is timezone-naive if data.index.tz is not None: data.index = data.index.tz_convert(None)
# Filter data up to and including the target date data = data[data.index
Недавно я использовал Yahoofinance для тестирования созданного мною торгового алгоритма. Проблема в том, что есть определенные элементы, которые я пытаюсь закодировать в алгоритме, и это должно быть легко осуществимо, но нигде в Google,...
Я получаю данные индекса S&P за каждый день и хочу вставить цену закрытия и дату в свою базу данных, однако я новичок в Python и понятия не имею, как ориентироваться в этой странной структуре данных. Вот что возвращает print(spxHistoricalData):...
Я хочу использовать свой собственный кошелек, используя Tonconnect и Ton SDK в Python, и как я могу подключить свой собственный кошелек к веб -сайту, используя Tonconnect, используя эту ссылку
tc://?v=2&id=10eddc8ad2e....3fea36&r={ manifestUrl :...
Я столкнулся с проблемой при попытке реализовать проверку приложений Firebase в моем приложении Flutter для выпускных сборок на Android. Для отладки я могу получить токен отладки с консоли, и когда я добавляю его в Firebase, запросы становятся...