如何用索引中的多个股票重新采样OHLC数据?

发布于 2025-02-07 02:24:27 字数 803 浏览 3 评论 0原文

我找不到与此相似的东西,我的OHLC数据是从Y金融中获取的多个股票的。 的多数索引

这导致了OHLC数据和股票名称python脚本 '''

import requests
import pandas as pd
import numpy as np
import yfinance as yf
from datetime import datetime, timedelta
N_DAYS_AGO = 15
now = datetime.now()
today = datetime(now.year,now.month,now.day, now.hour)
n_days_ago = today - timedelta(days=N_DAYS_AGO)

df = yf.download(['SPY','TLT'],  start=n_days_ago, end=now, interval = "60m")  #no error with 1 stock

ohlc_dict = {
    'Adj Close':'last',
    'Open':'first',
    'High':'max',
    'Low':'min',
    'Close':'last',
    'Volume':'sum'
    }

df_sample = df.resample('W-FRI', closed='left').agg(ohlc_dict)
df_sample  #error with 2 stocks

'''

上面的代码无单股票工作,但是当有多个股票/多索引列时失败。

我尝试了堆叠和拆卸,但还没有找到重新置于这些数据的好方法。这里最简单的道路是什么?

I haven't been able to find anything too similar to this I have OHLC data pulled from y-finance for multiple stocks. This results in a multi-index of columns of OHLC data and stock names

Python Script
'''

import requests
import pandas as pd
import numpy as np
import yfinance as yf
from datetime import datetime, timedelta
N_DAYS_AGO = 15
now = datetime.now()
today = datetime(now.year,now.month,now.day, now.hour)
n_days_ago = today - timedelta(days=N_DAYS_AGO)

df = yf.download(['SPY','TLT'],  start=n_days_ago, end=now, interval = "60m")  #no error with 1 stock

ohlc_dict = {
    'Adj Close':'last',
    'Open':'first',
    'High':'max',
    'Low':'min',
    'Close':'last',
    'Volume':'sum'
    }

df_sample = df.resample('W-FRI', closed='left').agg(ohlc_dict)
df_sample  #error with 2 stocks

'''

The code above works without a single stock but fails when there are multiple stocks/ multi index columns.

I've tried stacking and unstacking but haven't found a good way to resample this data. What's the simplest path forward here?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

葬花如无物 2025-02-14 02:24:27

该代码从Yahoo Finance下载数据,以获取多个符号,并将数据从每天到每周重新示例。

# Import libraries
import yfinance as yf
import pandas as pd

# Define symbols/tickers
symbols = ['SPY', 'TLT', 'MSFT']

# Download data from Yahoo Finance
mydf = yf.download(symbols, start='2020-01-01', 
                   end='2023-01-01', group_by = 'ticker')

# Get DataFrame with MultiIndex of "Ticker" and "Date"
mydf = mydf.stack(level = 0, future_stack = True).swaplevel().sort_index()

# Define pandas resample inputs
ohlc_dict = {
    'Open':'first',
    'High':'max',
    'Low':'min',
    'Close':'last',
    'Adj Close':'last',
    'Volume':'sum'
    }

# Loop through symbols and create resampled DataFrame
mydf_resampled = pd.DataFrame()
for symbol in symbols:
    cont = mydf.loc[symbol].resample('W-FRI', closed = 'left').agg(ohlc_dict)
    cont['Ticker'] = symbol
    mydf_resampled = pd.concat([mydf_resampled, cont])

# Create MultiIndex for resampled DataFrame
mydf_resampled = mydf_resampled.reset_index()
mydf_resampled = mydf_resampled.set_index(['Ticker', 'Date'])
mydf_resampled

要选择一个特定的“股票”,请使用mydf_resampled.loc ['spy']

This code downloads data from Yahoo Finance for multiple symbols, and resamples the data from daily to weekly.

# Import libraries
import yfinance as yf
import pandas as pd

# Define symbols/tickers
symbols = ['SPY', 'TLT', 'MSFT']

# Download data from Yahoo Finance
mydf = yf.download(symbols, start='2020-01-01', 
                   end='2023-01-01', group_by = 'ticker')

# Get DataFrame with MultiIndex of "Ticker" and "Date"
mydf = mydf.stack(level = 0, future_stack = True).swaplevel().sort_index()

# Define pandas resample inputs
ohlc_dict = {
    'Open':'first',
    'High':'max',
    'Low':'min',
    'Close':'last',
    'Adj Close':'last',
    'Volume':'sum'
    }

# Loop through symbols and create resampled DataFrame
mydf_resampled = pd.DataFrame()
for symbol in symbols:
    cont = mydf.loc[symbol].resample('W-FRI', closed = 'left').agg(ohlc_dict)
    cont['Ticker'] = symbol
    mydf_resampled = pd.concat([mydf_resampled, cont])

# Create MultiIndex for resampled DataFrame
mydf_resampled = mydf_resampled.reset_index()
mydf_resampled = mydf_resampled.set_index(['Ticker', 'Date'])
mydf_resampled

To select a specific "Ticker", use mydf_resampled.loc['SPY']

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文