<commit_before>---
layout: post
title: 金融数据处理常用代码
category: tool
tags: Essay
keywords: code
---

>### pandas code 合集

#### 生成ohlc数据

```python
def ohlc_resample(dataframe,freq,index_name = 'datetime'):
    """
    D:day
    W:week
    H:hour
    T/M : min
    S:seconds
    """
    resampled = pd.DataFrame()
    resampled['open'] = data.set_index(index_name).resample(freq).open.first()
    resampled['high'] = data.set_index(index_name).resample(freq).high.max()
    resampled['low'] = data.set_index(index_name).resample(freq).low.min()
    resampled['close'] = data.set_index(index_name).resample(freq).close.last()
    return resampled
```

#### 交易胜率

```python
loss = 0
count =0 
for i in back_summary.daily_pnl:
    if i==0 and count ==0:
        pass
    elif i==0 and count!=0:
        if count < 0:
            loss+=1
        count =0
    else:
        count += i
        
trade_times = int(((back_summary.pos - back_summary.pos.shift(1)).abs() >0).sum()/2)
trade_times
win_ratio = 1- loss/trade_times
win_ratio
```





<commit_msg>Update 2019-03-17-金融数据处理常用代码.md<commit_after>---
layout: post
title: 金融数据处理常用代码
category: tool
tags: Essay
keywords: code
---

>### pandas code 合集

#### 生成ohlc数据

```python
def ohlc_resample(data,freq,index_name = 'datetime'):
    """
    D:day
    W:week
    M : month
    H:hour
    T: minutes
    S:seconds
    """
    resampled = pd.DataFrame()
    resampled['open'] = data.set_index(index_name).resample(freq).open.first()
    resampled['high'] = data.set_index(index_name).resample(freq).high.max()
    resampled['low'] = data.set_index(index_name).resample(freq).low.min()
    resampled['close'] = data.set_index(index_name).resample(freq).close.last()
    return resampled
```

#### 交易胜率

```python
loss = 0
count =0 
for i in back_summary.daily_pnl:
    if i==0 and count ==0:
        pass
    elif i==0 and count!=0:
        if count < 0:
            loss+=1
        count =0
    else:
        count += i
        
trade_times = int(((back_summary.pos - back_summary.pos.shift(1)).abs() >0).sum()/2)
trade_times
win_ratio = 1- loss/trade_times
win_ratio
```

#### 分组统计行业排名

```
df2['rankinfo'] = df2.groupby(['ind_lv2','date'])['turnover'].rank(pct=True,na_option= 'bottom')
```






{'fraction_non_alphanumeric': 0.16852928028609745, 'fraction_numerical': 0.016540008940545373, 'mean_word_length': 3.1521335807050095, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3135923', 'n_tokens_mistral': 902, 'n_tokens_neox': 876, 'n_words': 157}