tibbletime获取前一日收盘价及DataFrame每日计算技术咨询
Hey there! No worries about not sharing code/data yet—let's walk through exactly how to handle this daily calculation workflow with tibbletime. Here's a step-by-step breakdown tailored to your needs:
Step 1: Prep Your Environment & Data
First, make sure you've got the necessary packages loaded. You'll need tibbletime for time-series manipulation and dplyr for data wrangling:
library(tibbletime) library(dplyr)
Next, ensure your date column is formatted as a date type (critical for tibbletime to work properly). If it's not already, convert it:
# Replace "date_col" with your actual date column name your_df$date_col <- as.Date(your_df$date_col)
Then convert your regular DataFrame into a tibbletime object—this lets you leverage time-specific functions:
time_df <- as_tbl_time(your_df, index = date_col)
Pro tip: Always sort your data by date first to avoid off-by-one errors with lagged values:
time_df <- time_df %>% arrange(date_col)
Step 2: Get the Previous Day's Close Price
Tibbletime plays nicely with dplyr's lag() function, which is perfect for grabbing the prior day's CloseUnits. Add this as a new column to your data:
time_df <- time_df %>% mutate(prev_day_close = lag(CloseUnits, n = 1))
- The
n = 1argument tells it to pull the value from 1 period back (which is 1 day, since your data is daily). - Note: The first row will have an
NAforprev_day_close(since there's no prior day). You can handle this withreplace_na()if needed (e.g., set it toCloseUnitsitself for the first day, or 0, depending on your business logic):
time_df <- time_df %>% mutate(prev_day_close = replace_na(prev_day_close, CloseUnits))
Step 3: Perform Your Daily Calculations
Now you can use the prev_day_close column to run whatever daily calculations you need. Let's cover a few common examples based on your fields:
Example 1: Calculate Daily Position Change
time_df <- time_df %>% mutate(daily_position_change = CloseUnits - prev_day_close)
Example 2: Calculate Net Units Traded + Position Validation
time_df <- time_df %>% mutate(net_traded_units = BuyUnits - SellUnits, daily_position_change = CloseUnits - prev_day_close, # Verify that position change matches net traded units (adjust if other factors apply) position_validation = daily_position_change - net_traded_units)
Example 3: Calculate Daily Return Including Interest
time_df <- time_df %>% mutate(daily_return = (CloseUnits - prev_day_close)/prev_day_close + Interest)
Key Notes
- If your data has gaps (e.g., missing weekends/holidays), tibbletime's
pad_time()function can fill in those gaps withNAvalues, ensuring your lagged values pull the actual prior trading day's close instead of just the calendar day. Use it like this:
time_df <- time_df %>% pad_time(unit = "day")
- Always double-check the sorted order of your dates—if they're out of order,
lag()will pull the wrong values!
内容的提问来源于stack exchange,提问作者M du Toit

