반응형

해석이 필요한 코드

    df = pyupbit.get_ohlcv(coin_ticker, interval="day", count=get_count)
    
# 이동평균선 계산
ma_dfs = []  # 이동평균 데이터를 저장할 리스트

for ma in range(3, 201):  # 3일선부터 200일선까지 반복
    ma_df = df['close'].rolling(ma).mean().rename(str(ma) + 'ma')  # 이동평균 계산
    ma_dfs.append(ma_df)  # 리스트에 추가

ma_df_combined = pd.concat(ma_dfs, axis=1)  # 여러 개의 이동평균선을 하나의 데이터프레임으로 합침
df = pd.concat([df, ma_df_combined], axis=1)  # 기존 데이터프레임(df)과 합침

df.dropna(inplace=True)  # NaN(결측치) 제거 → 가장 긴 이동평균선(200ma)까지 계산하려면 최소 200개의 데이터가 필요
df = df[:len(df)-cut_count]  # 최신 데이터 중 'cut_count' 개수만큼 제거

 

📌 예제 데이터

import pandas as pd

data = {
    'close': [100, 102, 105, 103, 107, 110, 112, 115, 118, 120]
}
df = pd.DataFrame(data)
print(df)
 

🔹 데이터프레임(df)

   close
0    100
1    102
2    105
3    103
4    107
5    110
6    112
7    115
8    118
9    120

 

📌 rolling(ma).mean() 적용 (5일 이동평균)

df['5ma'] = df['close'].rolling(5).mean()
print(df)

🔹 실행 결과

   close   5ma
0    100   NaN
1    102   NaN
2    105   NaN
3    103   NaN
4    107  103.4
5    110  105.4
6    112  107.4
7    115  109.4
8    118  112.4
9    120  115.0

 

  • 처음 4개의 값은 NaN → 이유는 5개의 데이터를 모아야 평균을 낼 수 있기 때문.
  • 이후부터는 5개 값의 평균이 계산됨.

🔥 결론

📌 이 코드가 하는 일

  1. ma일 동안의 종가 평균을 계산하여 이동평균선 생성.
  2. 새로운 컬럼 이름을 "{ma}ma" 형식으로 변경 (예: "5ma", "20ma").

 

 

📌 이동평균선 추가

ma_dfs = []
for ma in range(3, 6):  # 3~5일 이동평균선만 계산 (예제 데이터가 적어서)
    ma_df = df['close'].rolling(ma).mean().rename(str(ma) + 'ma')
    ma_dfs.append(ma_df)

ma_df_combined = pd.concat(ma_dfs, axis=1)
df = pd.concat([df, ma_df_combined], axis=1)
df.dropna(inplace=True)
df = df[:len(df)-2]  # 최신 2개 데이터 삭제

print(df)

🔹 결과 데이터프레임

    close    3ma    4ma    5ma
4    107  104.67  104.25  103.40
5    110  106.67  106.00  105.40
6    112  109.00  108.00  107.40
7    115  112.33  111.00  109.40
8    118  115.00  113.75  112.40
반응형
반응형

 

가상환경을 설치 하니 복잡하다으~

 

source 가상환경이름(myenv)/bin/activate

 

하면 활성화됨

 

crontab 이 안돌길래 보니 가상환경에만 라이브러리가 있었다

 

crontab -e 

 

0 0,9 * * * 가상환경경로(/myenv/bin/python) 실행할 파일( var/source/test.py)

 

요로코롬 하니까 잘 동작하는듯

 

9시 6시에 알림이 오고있으요 

 

 

반응형
반응형

def water_average_price(old_price, old_quantity, new_price, new_quantity):
    # 평균 매입가 계산
    total_price = (old_price * old_quantity) + (new_price * new_quantity)
    total_quantity = old_quantity + new_quantity
    average_price = total_price / total_quantity
    return average_price

# 예시 입력
old_price = 50000  # 기존 매입 가격
old_quantity = 10  # 기존 주식 수
new_price = 45000  # 추가 매수 가격
new_quantity = 5  # 추가 매수 주식 수

average_price = water_average_price(old_price, old_quantity, new_price, new_quantity)
print(f"평균 매입가는 {average_price:.2f}원 입니다.")

 

반응형
반응형
<template>
 	<div>{{ this.titleChk }}</div>
</template>
    data() {
        return {
            title:'',
         }
    },
    watch: {
            title(){
               // title input 이 비어있거나 혹은 공백일때 처리
                var blank_pattern = /^\s+|\s+$/g;
                if( _.isEmpty(this.title) || this.title.replace( blank_pattern, '' ) == "" ){
                    this.titleChk= false
                }else{
                    this.titleChk= true
                }
            }
    },

 

반응형
반응형
let prices = {
  banana: 1,
  orange: 2,
  meat: 4,
};

let doublePrices = Object.fromEntries(
  // 객체를 배열로 변환해서 배열 전용 메서드인 map을 적용하고 fromEntries를 사용해 배열을 다시 객체로 되돌립니다.
  Object.entries(prices).map(([key, value]) => [key, value * 2])
);

alert(doublePrices.meat); // 8

//객체 > 배열
// 배열 > 객체 전환

      let list = {
            banana: {
              title: '서울 바나나',
              배송유무: true
            },
            orange: {
              title: '서울 오랜지',
              배송유무: false
            },
      };
      let 배송체크 = Object.fromEntries(
        // 객체를 배열로 변환해서 배열 전용 메서드인 map을 적용하고 
        // fromEntries를 사용해 배열을 다시 객체로 되돌립니다.
        Object.entries(list).map(([key, value]) => [key, value.배송유무])
      );

      console.log(배송체크); //{banana: true, orange: false}

자료구조를 언제쯤 검색 안하고 다룰수 있을까요~~~~~~~

 

 

https://ko.javascript.info/keys-values-entries

 

반응형
반응형
<script>
    export default {
        data() {
            return {
                inputs: [
                    { id: Date.now(), name: '', lastName: '' }
                ]
            }
        },
        methods: {
            displayRef(ref) {
                console.log(this.$refs[ref]) // <= accessing the dynamic ref
                console.log('The value of input is:',this.$refs[ref][0].value) //<= outpouting value of input
            },
            displayAllRefs() {
                console.log(this.$refs)
            }
        }
    }
</script>

참조 : https://stackoverflow.com/questions/45563329/how-to-add-dynamic-ref-in-vue-js

반응형
반응형

 

  methods: {
        btcTrkAPICall: function () {
            axios    
                .get('https://www.api1.com/api/ticker')    
                .then(response => (this.btctrk = response.data))    
                .catch(error => console.log(error))    
        },
        bnncAPICall: function () {
            axios    
                .get('https://api.api2.com/api/v3/ticker/bookTicker')    
                .then(response => (this.bnnc = response.data))    
                .catch(error => console.log(error))    
        },
        intervalFetchData: function () {
            setInterval(() => {    
                this.btcTrkAPICall();
                this.bnncAPICall();
                }, 1000);    
        }
    },
    mounted () {
        // Run the functions once when mounted 
        this.btcTrkAPICall();
        this.bnncAPICall();
        // Run the intervalFetchData function once to set the interval time for later refresh
        this.intervalFetchData();
    }

https://stackoverflow.com/questions/54601694/how-to-auto-refresh-a-computed-property-at-axios-in-vuejs

반응형
반응형

구글 검색 해도 오래 걸려서 .. 따로 정리 

 

webpack.config.js 설정

test: 정규표현식 : 정규표현식과 같은 파일 찾아준다.

정규표현식.test(문자)이렇게 사용하면 문자 내부에 정규표현식과 일치하는 내용 확인하는 것)
use: 'vue-loader': test를 잘 할 수 있게 vue-loader의 도움을 받는다.

 

//const VueLoaderPlugin = require('vue-loader/dist/plugin');
const { VueLoaderPlugin } = require('vue-loader');
const path = require('path')

module.exports = {
    mode: 'development',
    //대표가 되는 파일 ( 하나로 합쳐진다 vue + js ..)
    entry:{
        app:  path.join(__dirname,'main.js')
    },
    module:{
        rules:[{
            test: /\.vue$/,
            loader: 'vue-loader',
        }],

    },
    plugins: [
        new VueLoaderPlugin(),
    ],
    //./output/app.js 로 최종 합쳐진 js 생성
    output:{
        filename: 'app.js',
        path: path.join(__dirname,'output'),
    },

};

최종 코드 

압축된 js

app.js
0.41MB

반응형
반응형

_.remove

마지막 객체가 삭제가 안되는거.. 쓰앙 삽질을 몇번을 하는거니..

 

그냥 

스크립트 기본 기능인 spice 로 하기로 함

 

근데 계속 안됨.. slice 로 입력하고 테스트 하고 있었음 ..

죽어서 고쳐질 삽질에 연속 ...

 

셀렉트 박스에서 선택 된 데이터 옆으로 쌓임 

쌓인 데이터 삭제 코드 공유

 

let temp = this.전체리스트

temp.splice(temp.indexOf(삭제값(유저클릭값)),1)

 

            const array = [1, 2, 3, 4, 5]; // 3 을 제거 하고 싶다. 
            const deletedIndex = 2	       // 3의 인덱스는 2 이다.
            array.splice(deletedIndex, 1); // 삭제할 인덱스, 1 개만 삭제 (즉, 3만 삭제)

 

끝 

 

잊지 않겠다 lodash   remove .. 쓰밤쉐

반응형
반응형

3depth 구현

<template>
    <div>
        <ul>
            <li v-for="item in treeData" :key="item.name">
                {{ item.name }}
                <ul v-if="item.type === 'directory' && item.children">
                    <li v-for="childItem in item.children" :key="childItem.name">
                        {{ childItem.name }}

                        <ul v-if="childItem.type ==='directory' && childItem.children">
                            <li v-for="childItem in childItem.children" :key="childItem.name">
                            {{ childItem.name }}
                            </li>
                        </ul>

                    </li>
                </ul>
            </li>
        </ul>
    </div>
</template>

<script>

export default {
    name: 'testView',
    data() { //함수 형태
        return {
            treeData: [{
                "name": "root",
                "type": "directory",
                "children": [
                    {
                        "name": "folder1",
                        "type": "directory",
                        "children": [
                            {
                                "name": "file1.txt",
                                "type": "file"
                            },
                            {
                                "name": "file2.txt",
                                "type": "file"
                            }
                        ]
                    },
                    {
                        "name": "folder2",
                        "type": "directory",
                        "children": [
                            {
                                "name": "subfolder1",
                                "type": "directory",
                                "children": [
                                    {
                                        "name": "file3.txt",
                                        "type": "file"
                                    }
                                ]
                            },
                            {
                                "name": "file4.txt",
                                "type": "file"
                            }
                        ]
                    },
                    {
                        "name": "file5.txt",
                        "type": "file"
                    }
                ]
            }],
        }
    },
    methods: {
        toggleNode(item) {
            if (item.type === 'directory' && item.children) {
                item.expanded = !item.expanded;
            }
        }
    }

}

</script>
<style>
ul {
    list-style: none;
    padding: 0;
}

li {
    cursor: pointer;
}

.nested {
    display: none;
}

.active {
    display: block;
}
</style>

반응형

+ Recent posts